Search code examples
blockchainsolidityremix

ParserError: Expected ';' but got reserved keyword 'in'


In this part of my smart contract, Remix is displaying an error:

function rebase() public {
    for (address wallet in balances) {
        uint256 reward = balances[wallet] * 0.002;
        balances[wallet] += reward;
        totalSupply -= reward;
    }
}

The error is:

ParserError: Expected ';' but got reserved keyword 'in'
--> test.sol:70:25: | 70 | for (address wallet in balances) { | ^^

I also tried another method:

function rebase() public {
    for (uint i = 0; i < balances.length; i++) {
bytes32 walletHash = balances[i];
        address wallet = address(walletHash);
        uint256 reward = balances[wallet] * 0.002;
        balances[wallet] += reward;
        totalSupply -= reward;
    }
}

What could be the issue? I tried a lot been on this since yesterday, I would be very happy if someone could assist me. What I'm trying to do is add the rebase function to the smart contract, where each wallet receives 0.2% / day based on the amount of tokens they have in their wallet.

function rebase() public {
    for (uint i = 0; i < balances.length; i++) {
bytes32 walletHash = balances[i];
        address wallet = address(walletHash);
        uint256 reward = balances[wallet] * 0.002;
        balances[wallet] += reward;
        totalSupply -= reward;
    }
}

Solution

  • for (address wallet in balances) {
    

    This is a JavaScript syntax (and possibly some other languages use it too) but it's not valid syntax in Solidity.


    for (uint i = 0; i < balances.length; i++) {
    

    This is a valid Solidity syntax, assuming balances is an array.

    If it's a mapping, then you cannot iterate through it, as the list of keys that have set values is unknown.

    You might use the iterable mapping pattern. However, a common approach to rebase tokens is to update a multiplier - rather than update balance of each holder.

    // how many % of the total supply each address owns
    mapping(address => uint256) balancePercentages;
    
    uint256 multiplier;
    
    function rebase(uint256 _multiplier) external {
        // the percentage of each holder stays the same
        multiplier = _multiplier;
    }
    
    function balanceOf(address holder) external view returns (uint256) {
        return balancePercentages * multiplier;
    }