Skip to content

Instantly share code, notes, and snippets.

@marsrvr
Created December 27, 2019 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marsrvr/223944cab3b30be14ae564cd63613ddf to your computer and use it in GitHub Desktop.
Save marsrvr/223944cab3b30be14ae564cd63613ddf to your computer and use it in GitHub Desktop.
My diagnosis and solution to a storage location issue problem in Solidity 101.
pragma solidity 0.5.1;
contract MemorySolution {
mapping(uint => User) users;
struct User{
uint id;
uint balance;
}
function addUser(uint id, uint balance) public {
users[id] = User(id, balance);
}
function updateBalance(uint id, uint balance) public {
// Problem: update is executing but no affect on balance
User memory user = users[id]; // Copies mapped user to a memory User struct
user.balance = balance; // Updates balance of memory User struct.
// fails to push memory User struct to mapping in storage.
users[id] = user; // <-- should fix it, if overwrites are allowed.
// Note: User.id is superfluous to users[id]
}
function getBalance(uint id) view public returns (uint) {
return users[id].balance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment