Home > front end >  How can I sum the uint values ​inside the tokenRewards array?
How can I sum the uint values ​inside the tokenRewards array?

Time:04-11

I want to get the sum of the number of rewards I have earned per token I have from this function getCurrentTotalStakeEarned.

    uint256 public tokensPerBlock;
    mapping(address => uint256) public _balances;
    mapping(address => mapping(uint256 => uint256)) public _ownedTokens;

    function getCurrentTotalStakeEarned(address targetAddress) external view returns (uint256[] memory, uint256[] memory) {
        uint256 [] memory tokenIds = new uint256[](_balances[targetAddress]); 
        uint256 [] memory tokenRewards = new uint256[](_balances[targetAddress]); 
        for(uint256 i = 0; i < _balances[targetAddress]; i  ){
            tokenIds[i] = _ownedTokens[targetAddress][i];
            tokenRewards[i] = _getTimeStaked(tokenIds[i]  ).mul(tokensPerBlock);
        }
        return (tokenIds, tokenRewards);
    }

    function _getTimeStaked(uint256 tokenId) internal view returns (uint256) {
        if (receipt[tokenId].stakedFromBlock == 0) {
            return 0;
        }

        return block.number.sub(receipt[tokenId].stakedFromBlock);
    }

With an array, I can see how much each token gives me. But I want to sum them.

image I just want the values ​​I marked in red to be summed

CodePudding user response:

What do we want?

Total value of rewards per address.

What do we have?

An array of rewards per address returned from getCurrentTotalStakeEarned

We can simply iterate the array and sum the values.

function reduce(uint256[] arr) pure internal returns (uint256 result){
    for (uint256 i = 0; i < arr.length; i  ) {
        result  = arr[i];
    }
 
    return;
}
  • Related