How-To Use Key-Value Map

Summary

This how-to procedure demonstrates how to define and use a Key-Value Map (kv map) in your smart contract.

To accomplish this task use eosio::kv::map template class, specify the name for the map object instantiated, the type of the key, and the type for the values stored for each key. The types used for the key and the values can be any standard type, or a user defined type.

Prerequisites

  • The EOSIO development environment, for details consult the Get Started Guide.
  • A smart contract named smrtcontract.
  • A user defined type named person, which defines the data stored in the map.

Refer to the following possible implementation of your starting point.

smartcontract.hpp file

struct person {
  eosio::name account_name;
  std::string first_name;
  std::string last_name;
};

class [[eosio::contract]] smartcontract : public eosio::contract {
   public:
      using contract::contract;
      smartcontract(eosio::name receiver, eosio::name code, eosio::datastream<const char*> ds)
         : contract(receiver, code, ds) {}
};

Procedure

Complete the following steps to define the my_map_t type, based on the eosio::kv::map, which stores objects of type person with unique keys of type int and instantiate a map object of type my_map_t:

  • Define the my_map_t type based on eosio::kv::map.
  • Specify "kvmap"_n, which is an eosio::name, as the first parameter, to name for the map object.
  • Specify int as the second parameter to give the type of the unique keys.
  • Specify person as the third parameter to give the type of the values stored in the map with each key.
  • Declare and instantiate, as a private data member, an instance of the type my_map_t, and name it my_map.

Refer below for a possible implementation of the above described steps:

smartcontract.hpp file

class [[eosio::contract]] smartcontract : public eosio::contract {

   using my_map_t = eosio::kv::map<"kvmap"_n, int, person>;

   public:
      using contract::contract;
      smartcontract(eosio::name receiver, eosio::name code, eosio::datastream<const char*> ds)
         : contract(receiver, code, ds) {}

   private:
      my_map_t my_map{};
};

Next Steps

The following option is available when you complete the procedure: