EOS记事本合约

本次分享的内容是一个记事本合约,调用合约中的写入动作可以将文本和作者保存到数据库中,通过记事本合约来学习EOS智能合约数据存储当中的主键自增。

合约动作

写入动作

记事本合约必须要有的写入文本action,用来存储记录文本和记录作者。

删除动作

记事本中同样需要有删除记录的action,用来删除记录信息。

合约代码

note.cpp

#include#includeusingnamespaceeosio;usingstd::string;classrecord:publiceosio::contract {public:/// @abi table notes i64structnote{uint64_tid;        account_name    author;stringtext;autoprimary_key()const{returnid; }    };typedefmulti_index notes;usingcontract::contract;/// @abi actionvoidwrite(account_name author,stringtext){        require_auth(author);        print("Hello, ", name{author});notesnt( _self, _self );uint64_tnoteId;        nt.emplace(author, [&](auto&n) {            n.id = nt.available_primary_key();// 主键自增n.author = author;            n.text = text;            noteId = n.id;        });        print("----noteId = ", noteId);    }voidremove(uint64_tid){notesnt( _self, _self );autoit = nt.find( id );        eosio_assert( it != nt.end(),"the id not found");        require_auth(it->author);        nt.erase( it );    }};EOSIO_ABI(record, (write)(remove))

合约涉及数据库操作部分

在表中增加记录:emplace

删除一条数据:erase

查询记录:find

主键自增:available_primary_key

其中主键自增非常重要,不写主键自增会导致无法存入多条记录。

合约调用演示

调用write动作

$cleos push action note write'{"author":"user","text":"This is my first diary"}'-p userexecuted transaction: ab59fc4e04342690af46d5bf4dd48c8418d4655e8bcaea81ca3fdc0c99b6fed7  216 bytes  511 us#note <= note::write                  {"author":"user","text":"This is my first diary"}>> Hello, user----noteId = 0warning: transaction executed locally, but may not be confirmed by the network yet

调用成功会返回信息,其中noteId是记录的id,在删除记录的时候需要用到。

cleos get table 查询表

$ cleos get table note note notes{"rows": [{"id":0,"author":"user","text":"This is my first diary"},{"id":1,"author":"student","text":"my name is student!"},{"id":2,"author":"miaomiao","text":"my name is miaomiao"}  ],"more":false}

调用remove动作

删除时进行了授权限制,每个账户只能删除自己的记录,无法删除其他账户的记录

错误的授权:

$ cleos push action note remove'{"id":2}' -p userError3090004: missing required authorityEnsure that you have the related authority inside your transaction!;Ifyou are currentlyusing'cleos push action' command, try to add the relevant authority using -p option.ErrorDetails:missing authorityofmiaomiao

正确的授权:

$ cleos push action noteremove'{"id":2}'-p miaomiaoexecuted transaction:51eb63f0fdb7d5d01676e898a0f9bc144ee1feda344780042782f359541a578d192bytes442us#          note <= note::remove{"id":2}$ cleos gettablenote note notes{"rows": [{"id":0,"author":"user","text":"This is my first diary"},{"id":1,"author":"student","text":"my name is student!"}  ],"more":false}

在编写记事本合约时为了找到让主键增加的方法差了很多资料,也走了很多弯路。最后发现其实就是一行代码就能解决的事情。

你可能感兴趣的:(EOS记事本合约)