Created
June 28, 2021 07:49
-
-
Save nhancv/f7178e4bf616817ede186df4fac84f93 to your computer and use it in GitHub Desktop.
Smart contract pagination for list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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