Store Data in a Smart Contract struct Variable

Share this video with your friends

Social Share Links

Send Tweet

Now, we have the base contract to work on. The goal of the contract is to act as a tip jar, a way to allow users or followers to send you some ETH through the web, including some message. But also, to showcase the people that sent you that money by making the actions public in the web too. This means that the contract need to:

  1. Identify to who to send the tip
  2. Store the tip sender data including the message, and the amount of eth.
  3. Allow a way to retrieve the actions (the tips sent) made through it.

We will add an address payable variable of owner to tell the contract that the contract will receive payments.

For the actual tip data, we will define a Tip struct that will have all the information needed to send a tip.

Man 1: [0:00] The goal in this lesson is to build a smart contract that functions like a tip jar that allows users to send ETH to the contract owner along with some other metadata. To achieve this, you'll need a way to store some data in the smart contract. [0:18] Remember that the smart contract will store this data into the blockchain, so you need a way to identify each piece of data. First, declare an identifier or variable for the contract owner using address as the type of the payable modifier to let the contract note that this address can receive some ETH.

[0:43] Then, let's create a custom and more complex data structure to hold information about the tip sent. This will be a struct. This allows you to create a custom structure that can hold different set of properties with different types. You may notice that this is very similar to a JavaScript object.

[1:04] In this case, the struct will hold an address to identify the sender of a tip, a string to store a message, another string to store the name, an integer to store a timestamp. Finally, another integer to store the amount of eth sent in the tip. Let's create a collection of tips by using an array structure for the previous struct named tips.

[1:32] Lastly, since the constructor is called when the contract is instantiated, you can use it to identify or define the value of the owner as a payable address. You can do this by using the message sender variable that tells you who instantiated the contract.

[1:51] In summary, in this step of the smart control creation, you define what you want to store in the blockchain by using different data types. This includes a custom data structure using the struct keyword.