Created
August 19, 2023 04:17
-
-
Save valterlobo/f9243af29e9ec69dbce03d43cfec0522 to your computer and use it in GitHub Desktop.
Returning Arrays of Dynamic Size in Solidity Smart Contracts
This file contains hidden or 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.9; | |
//Issues of Returning Arrays of Dynamic Size in Solidity Smart Contracts | |
//https://betterprogramming.pub/issues-of-returning-arrays-of-dynamic-size-in-solidity-smart-contracts-dd1e54424235 | |
contract ReturnLimitTestWithPagination { | |
uint256[] private array; | |
function addToArray(uint256 count) external { | |
for (uint256 i = 0; i < count; i++) { | |
array.push(array.length); | |
} | |
} | |
function getArray(uint256 page, uint256 pageSize) external view returns (uint256[] memory, uint256) { | |
require(pageSize > 0, "page size must be positive"); | |
require(page == 0 || page*pageSize <= array.length, "out of bounds"); | |
uint256 actualSize = pageSize; | |
if ((page+1)*pageSize > array.length) { | |
actualSize = array.length - page*pageSize; | |
} | |
uint256[] memory res = new uint256[](actualSize); | |
for (uint256 i = 0; i < actualSize; i++) { | |
res[i] = array[page*pageSize+i]; | |
} | |
return (res, array.length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment