Skip to content

Instantly share code, notes, and snippets.

@nhancv
Created June 28, 2021 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhancv/f7178e4bf616817ede186df4fac84f93 to your computer and use it in GitHub Desktop.
Save nhancv/f7178e4bf616817ede186df4fac84f93 to your computer and use it in GitHub Desktop.
Smart contract pagination for list
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
contract TestPlayerRead {
struct Player {
uint id;
}
Player[] public playerList;
mapping(uint => Player) public playerMap;
constructor () {}
function addPlayers(uint more) public {
uint currentSize = getPlayerSize();
for (uint i = currentSize; i < currentSize + more; i++) {
uint id = i + 1;
Player memory player = Player(id);
playerList.push(player);
playerMap[id] = player;
}
}
function getPlayerSize() public view returns (uint length) {
return playerList.length;
}
function getPlayers() public view returns (Player[] memory players) {
return playerList;
}
function getPlayersPaging(uint offset, uint limit) public view returns (Player[] memory players, uint nextOffset, uint total) {
uint totalPlayers = playerList.length;
if(limit == 0) {
limit = 1;
}
if (limit > totalPlayers- offset) {
limit = totalPlayers - offset;
}
Player[] memory values = new Player[] (limit);
for (uint i = 0; i < limit; i++) {
values[i] = playerList[offset + i];
}
return (values, offset + limit, totalPlayers);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment