1

I'm trying to start a stacking smart contract. Each user can stake different ERC20 Token.

I'm using follwing struct :

   struct Token {
        address tokenAddress;
        uint256 stakedAmount;
        uint lastTransactionDate;
        bool isUsed;
    }

I define a relation User-Token with :

mapping(address => Token) stakingUserBalance;

On my stake function I need to store an ERC20 token for user :

function stakeToken(address tokenAddress, uint256 amount) public {
    require(amount > 0, "You cannot stake 0 token");

    //Transfer amount to smartcontract
    IERC20(tokenAddress).transferFrom(msg.sender, address(this), amount);

    //Update user balance
    Token storage userToken = stakingUserBalance[msg.sender];
    userToken.lastTransactionDate = block.timestamp;
    userToken.stakedAmount += amount;
  

    //fire event
    emit TokenStaked(tokenAddress, amount);
}

So my question is : how get a specific token address in stakingUserBalance to update the value of stakedAmount for right token ?

thanks for your help

2 Answers 2

2

As in your use case each user (represented by an address) can stake a token (represented by an address) for which you store the information (represented by the Token struct) I would recommend to adjust your mapping structure to:

// user address -> token address -> information
mapping(address => mapping(address => Token)) stakingUserBalance;

This allows you to access the information by using the following:

Token storage userToken = stakingUserBalance[msg.sender][tokenAddress];
0
1

The way you've defined the Token and stakingUserBalance, a user can only stake once type of token. User address is used as the only unique key. You'd have to restructure the data structure to use address-token as a unique combination.

One way would be to use a mapping of mapping.

mapping (address => mapping(address => Token)) public stakedTokens;

This would let create a mapping of tokenAddress => Token for each user address. This way, you can support multiple tokens for each user.

To access a token balance, you can use the following method.

stakedTokens[userAddress][tokenAddress].stakedAmount;

Hope this clarifies your questions.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.