定义table
struct [[eosio::table("sellheros"), eosio::contract("xxx.game")]] sellhero{
capi_checksum256 tx_hash;
....
auto primary_key() const { return *(uint64_t*)&tx_hash; }
};
创建table
typedef eosio::multi_index<"sellheros"_n, sellhero> sellhero_tables;
查询
taskhash_tables taskhash_table(_self, account);
auto itr_task = taskhash_table.find(*(uint64_t*)&client_random_hash);
eosio_assert(itr_task != taskhash_table.end(), "random hash is not exist" );
hash 生成
capi_checksum256 bcskill_contract::tx_hash(){
size_t tx_size = transaction_size();
char buff[tx_size];
size_t read = read_transaction(buff, tx_size);
capi_checksum256 h;
sha256(buff, read, &h);
return h;
}
添加数据
capi_checksum256 hash = tx_hash();
sellhero_tables sellhero_table(_self, _self.value);
sellhero_table.emplace( _self, [&]( auto& h ) {
h.tx_hash = hash;
...
});
新增索引方法
using eosio::fixed_bytes;
#define SHA_TO_HASH_FUNC static fixed_bytes<32> checksum256_to_sha256(const capi_checksum256 &hash) \
{ \
const uint64_t *p64 = reinterpret_cast<const uint64_t *>(&hash); \
return fixed_bytes<32>::make_from_word_sequence<uint64_t>(p64[0], p64[1], p64[2], p64[3]); \
}
#define SHA_TO_HASH(hash) checksum256_to_sha256(hash)
struct [[eosio::table, eosio::contract("bcskillsurou")]] tokeninfotb {
uint64_t id; // id
capi_checksum256 transaction_id; // 交易id
uint64_t primary_key() const { return id; }
fixed_bytes<32> second_key() const { return SHA_TO_HASH(transaction_id); }
SHA_TO_HASH_FUNC
EOSLIB_SERIALIZE(tokeninfotb, (id)(transaction_id))
};
typedef eosio::multi_index<"tokeninfotb"_n, tokeninfotb, eosio::indexed_by<"bysubkey"_n, eosio::const_mem_fun<tokeninfotb, fixed_bytes<32>, &tokeninfotb::second_key>>> tokeninfo_table;
参考
https://eosio.stackexchange.com/questions/3219/how-to-properly-use-cleos-get-table-with-key-type-sha256-secondary-index-fa