Storage operations are very expensive and everything pales in comparison as soon as you start using them.

So I was wondering, what clever way one could use to reduce the following storage write operations (20000/5000 gas each).

function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
  uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether);
  tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer));
  tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], amount);
  tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], feeTakeXfer);
  tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet);
  tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet);

They are stored like this: mapping (address => mapping (address => uint)) public tokens;

1 Answer 1


Although there is a nested mapping here, only a single storage slot is used for each write. Solidity uses the two keys that access the value in the mapping together to figure out the slot index in the storage. In this particular method 5 storage slots are used.

There is really no way to optimize here other than using a smaller type for values such as uint128 or uint64 and then packing the values together.

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.