Overview
This how-to demonstrates how to define and use a Key-Value Table
(kv table
) in a smart contract.
To accomplish this task, define the user type which will be stored in the kv table
, and extend the eosio::kv::table
template class with a specialized definition based on the user defined type.
Before you begin
Make sure you have the following prerequisites in place:
- An EOSIO development environment, for details consult the Get Started Guide.
- A smart contract named
smrtcontract
- A user defined type,
struct
orclass
, which defines the data stored in the map, namedperson
Refer to the following reference implementation for your starting point:
smartcontract.hpp file
struct person {
eosio::name account_name;
std::string first_name;
std::string last_name;
std::string street;
std::string city;
std::string state;
std::string country;
std::string personal_id;
};
class [[eosio::contract]] smrtcontract : public contract {
public:
using contract::contract;
};
Procedure
Complete the following steps to define the address_table
type, based on the eosio::kv::table
, which stores objects of type person
:
- Define the structure or class
address_table
in the scope of your smart contract class, for the abi generation to find it and place it into the abi file. - Derive
address_table
fromeosio::
kv::tableclass template. Pass the
personuser defined type as the type parameter for
eosio::kv::table
base class and the name of thekv table
, let’s saykvaddrbook
. - Annotate
address_table
type with[[eosio::table]]
, and make sure it is placed after thestruct
keyword but before the name of the type. - Define a primary index
first_name_idx
based on the data memberperson::first_name
. Everykv table
requires a primary index to be defined on a data member that stores unique values. -
In the
address_table
constructor, call theinit(...)
base class method with the two parameters:- The first parameter, of type
eosio::name
, is the contract that owns the table. - The second parameter is the
account_name_uidx
primary index.
- The first parameter, of type
Refer below for a possible implementation of the above described steps:
smartcontract.hpp file
class [[eosio::contract]] smrtcontract : public contract {
struct [[eosio::table]] address_table : eosio::kv::table<person, "kvaddrbook"_n> {
index<name> account_name_uidx {
name{"accname"_n},
&person::account_name };
address_table(name contract_name) {
init(contract_name, account_name_uidx)
}
};
public:
using contract::contract;
};
Summary
In conclusion, the above instructions show how to define and use a Key-Value Table
(kv table
) in a smart contract.
Next Steps
- You can create one or more unique indexes using the
KV_NAMED_INDEX
macro or theeosio::kv::table::index
template class. - You can create one or more non-unique indexes using the
KV_NAMED_INDEX
macro or theeosio::kv::table::index
template class. -
You can access the defined
kv table
and perform operations on it and its defined indexes: