Data Persistence
Step 1: Create a new directory
Earlier, you created a contract directory, navigate there now.
cd CONTRACTS_DIRCreate a new directory for our contract and enter the directory
mkdir addressbook
cd addressbookStep 2: Create and open a new file
touch addressbook.cppOpen the file in your favorite editor.
Step 3: Write an Extended Standard Class and Include EOSIO
In a previous tutorial, you created a hello world contract and you learned the basics. You will be familiar with the structure below, the class has been named addressbook respectively.
#include <eosio/eosio.hpp>
using namespace eosio;
class [[eosio::contract("addressbook")]] addressbook : public eosio::contract {
public:
private:
};Step 4: Create The Data Structure for the Table
Before a table can be configured and instantiated, a struct that represents the data structure of the address book needs to be written. Since it's an address book, the table will contain people, so create a struct called "person"
When defining the structure of a multi_index table, you will require a unique value to use as the primary key.
For this contract, use a field called "key" with type name. This contract will have one unique entry per user, so this key will be a consistent and guaranteed unique value based on the user's name
Since this contract is an address book it probably should store some relevant details for each entry or person
Great. The basic data structure is now complete.
Next, define a primary_key method. Every multi_index struct requires a primary key to be set. Behind the scenes, this method is used according to the index specification of your multi_index instantiation. Antelope wraps boost::multi_index
Create an method primary_key() and return a struct member, in this case, the key member as previously discussed.
A table's data structure cannot be modified while it has data in it. If you need to make changes to a table's data structure in any way, you first need to remove all its rows
Step 5: Configure the Multi-Index Table
Now that the data structure of the table has been defined with a struct we need to configure the table. The eosio::multi_index constructor needs to be named and configured to use the struct we previously defined.
With the above multi_index configuration there is a table named people, that
Uses the
_noperator to define an eosio::name type and uses that to name the table. This table contains a number of different singular "persons", so name the table "people".Pass in the singular
personstruct defined in the previous step.Declare this table's type. This type will be used to instantiate this table later.
There are some additional configurations, such as configuring indices, that will be covered further on.
So far, our file should look like this.
Step 6: The Constructor
When working with C++ classes, the first public method you should create is a constructor.
Our constructor will be responsible for initially setting up the contract.
EOSIO contracts extend the contract class. Initialize our parent contract class with the code name of the contract and the receiver. The important parameter here is the code parameter which is the account on the blockchain that the contract is being deployed to.
Step 7: Adding a record to the table
Previously, the primary key of the multi-index table was defined to enforce that this contract will only store one record per user. To make it all work, some assumptions about the design need to be established.
The only account authorized to modify the address book is the user.
the primary_key of our table is unique, based on username
For usability, the contract should have the ability to both create and modify a table row with a single action.
In EOSIO a chain has unique accounts, so name is an ideal candidate as a primary_key in this specific use case. The name type is a uint64_t.
Next, define an action for the user to add or update a record. This action will need to accept any values that this action needs to be able to emplace (create) or modify.
For user-experience and interface simplicity, have a single method be responsible for both creation and modification of rows. Because of this behavior, name it "upsert," a combination of "update" and "insert."
Earlier, it was mentioned that only the user has control over their own record, as this contract is opt-in. To do this, utilize the require_auth method provided by the eosio.cdt. This method accepts an name type argument and asserts that the account executing the transaction equals the provided value and has the proper permissions to do so.
Previously, a multi_index table was configured, and declared as address_index. To instantiate a table, two parameters are required:
The first parameter "code", which specifies the owner of this table. As the owner, the account will be charged for storage costs. Also, only that account can modify or delete the data in this table unless another payer is specified. Here we use the
get_self()function which will pass the name of this contract.The second parameter "scope" which ensures the uniqueness of the table within this contract. In this case, since we only have one table we can use the value from
get_first_receiver().get_first_receiveris the account name this contract is deployed to.
Note that scopes are used to logically separate tables within a multi-index (see the eosio.token contract multi-index for an example, which scopes the table on the token owner). Scopes were originally intended to separate table state in order to allow for parallel computation on the individual sub-tables. However, currently inter-blockchain communication has been prioritized over parallelism. Because of this, scopes are currently only used to logically separate the tables as in the case of eosio.token.
Next, query the iterator, setting it to a variable since this iterator will be used several times
Security has been established and the table instantiated, great! Next up, write the code for creating or modifying the table.
First, detect whether a particular user already exists in the table. To do this, use table's find method by passing the user parameter. The find method will return an iterator. Use that iterator to test it against the end method. The "end" method is an alias for "null".
Create a record in the table using the multi_index method emplace. This method accepts two arguments, the "payer" of this record who pays the storage usage and a callback function.
The callback function for the emplace method must use a lamba function to create a reference. Inside the body assign the row's values with the ones provided to upsert.
Next, handle the modification, or update, case of the "upsert" function. Use the modify method, passing a few arguments:
The iterator defined earlier, presently set to the user as declared when calling this action.
The "payer", who will pay for the storage cost of this row, in this case, the user.
The callback function that actually modifies the row.
The addressbook contract now has a functional action that will enable a user to create a row in the table if that record does not yet exist, and modify it if it already exists.
But what if the user wants to remove the record entirely?
Step 8: Remove record from the table
Similar to the previous steps, create a public method in the addressbook, making sure to include the ABI declarations and a require_auth that tests against the action's argument user to verify only the owner of a record can modify their account.
Instantiate the table. In addressbook each account has only one record. Set iterator with find
A contract cannot erase a record that doesn't exist, so check that the record indeed exists before proceeding.
Finally, call the erase method, to erase the iterator. Once the row is erased, the storage space will be free up for the original payer.
The contract is now mostly complete. Users can create, modify and erase records. However, the contract is not quite ready to be compiled.
Step 9: Preparing for the ABI
9.1 ABI Action Declarations
cdt includes an ABI Generator, but for it to work will require some declarations.
Above both the upsert and erase functions add the following C++11 declaration:
The above declaration will extract the arguments of the action and create necessary ABI struct descriptions in the generated ABI file.
9.2 ABI Table Declarations
Add an ABI declaration to the table. Modify the following line defined in the private region of your contract:
To this:
The [[eosio.table]] declaration will add the necessary descriptions to the ABI file.
Now our contract is ready to be compiled.
Below is the final state of our addressbook contract:
Step 10 Prepare the Ricardian Clauses [Optional]
Contracts compiled without a Ricardian contract will generate a compiler warning for each action missing an entry in the Ricardian clause.
To define Ricardian contracts for this smart contract, create a new file called addressbook.contracts.md. Notice that the name of the Ricardian contracts must match the name of the smart contract.
Add Ricardian Contract definitions to this file:
Step 11 Prepare the Ricardian Clauses [Optional]
To define Ricardian clauses for this smart contract create and open a new file called addressbook.clauses.md. Notice again that the name of the Ricardian clauses must match the name of the smart contract.
Add Ricardian clause definitions to this file:
Step 12: Compile the Contract
Execute the following command from your terminal.
If you created a Ricardian contract and Ricardian clauses, the definitions will appear in the .abi file. An example for the addressbook.cpp, built including the contract and clause definitions described above is shown below.
Step 13: Deploy the Contract
Create an account for the contract, execute the following shell command
Deploy the addressbook contract
Step 14: Test the Contract
Add a row to the table
Check that alice cannot add records for another user.
As expected, the require_auth in our contract prevented alice from creating/modifying another user's row.
Retrieve alice's record.
Test to see that alice can remove the record.
Check that the record was removed:
Looking good!
Wrapping Up
You've learned how to configure tables, instantiate tables, create new rows, modify existing rows and work with iterators. You've learned how to test against an empty iterator result. Congrats!
What's Next?
Secondary Indices: Learn how to add another index to the
addressbookcontract that you created in the preceding Data Persistence section.
Last updated