How to persist data after deployment in Solidity

639 views Asked by At

I am pretty new to Solidity and working with Ethereum in general. In the (d)app I'm working on I need to be able to persist data onto the ledger, but I'm not sure I understand how this works.

Let's say I have the following contract (simplified for practicality):

contract UserContract {
    struct User {
        address walletAddress;
        string organisation;
        string fName;
        string lName;
        string email;
        uint index;
    }
    mapping(address => User) private users;
    address[] private userIndex;


    function insertUser(
        address walletAddress,
        string organisation,
        string fName,
        string lName,
        string email        )
      public
      returns(uint index) {
          User memory newUser = User({
            walletAddress: walletAddress,
            organisation: organisation,
            fName: fName,
            lName: lName,
            email: email,
            index: users.length
            });

            users.push(newUser);
            userIndex[walletAddress] = newUser.index;
            return newUser.index;
    }
}

Using the insertUser() method, I can insert a new user, and using a getter method I could retrieve the user's information.

Now, if I update the contract (thus deploy a new one), the users mapping is empty again, not surprising.

My question: how do I store data in a way that it will be accessible for future versions of the contract? Any design patterns that go along with this process?

Thanks!

1

There are 1 answers

3
ReyHaynes On BEST ANSWER

Since, as you know, stored data will not travel with a new contract and copying over data to a new contract would be expensive task after a few uses...your best bet is to separate functionality from data storage.

Create a contract with some basic setters and getters that only deals with data storage (from a particular contract address if necessary)...then create your main functional contract that connects to the data contract.