0

I have the following stake function that whenever I call it uses almost 100.000 gas. I did the usual stuff optimizing the code to use less gas like using structs and uint256, but the gas price is still abnormally high.

Gas:101721 Transaction cost:101721

function stake(uint256 amount) external updateReward(_msgSender()) {
    require(amount > 0, "Cannot stake 0");
    totalStakeAmount = totalStakeAmount.add(amount);
    User storage _user = userInfo[_msgSender()];
    _user.stakeAmount = _user.stakeAmount.add(amount);
    emit Staked(_msgSender(), amount);
}

function unstake(uint256 amount) public updateReward(_msgSender()) {
    require(amount > 0, "Cannot withdraw 0");
    User storage _user = userInfo[_msgSender()];
    totalStakeAmount = totalStakeAmount.sub(amount);
    _user.stakeAmount = _user.stakeAmount.sub(amount);
    IERC20(stakeToken).safeTransfer(_msgSender(), amount);
    emit Unstaked(_msgSender(), amount);
}
4
  • 1
    can you show your Struct? 100000 gas is not a lot
    – Majd TL
    Oct 12, 2021 at 13:54
  • @MajdTL struct User { uint256 stakeAmount; uint256 rewards; uint256 userRewardPerTokenPaid; } Oct 12, 2021 at 14:19
  • 1
    okay your struct is okay, as I said 100k seems okay, you do a lot of stuff, updateReward, change storage variable, transfer erc20Tokens.
    – Majd TL
    Oct 12, 2021 at 14:33
  • What does updateReward do?
    – Ismael
    Oct 14, 2021 at 3:55

1 Answer 1

0

Your contract looks like a Synthetix derivative. If that's the case, then updateReward is here: https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol#L152

The Synthetix contract uses a complicated staking algorithm. That means it's not very cheap to use. But the good thing is that the cost doesn't go up as the number of stakers goes up, so the usage costs are constant. This makes it truly scalable. You simply have to accept that or use some other staking algorithm - although I doubt there are many more efficient ones.

Your Answer

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

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