EOS之记事本智能合约
Posted tokenpai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EOS之记事本智能合约相关的知识,希望对你有一定的参考价值。
EOS记事本智能合约
本次分享的内容是一个记事本合约,调用合约中的写入动作可以将文本和作者保存到数据库中,通过记事本合约来学习EOS智能合约数据存储当中的主键自增。
合约动作
- 写入动作
记事本合约必须要有的写入文本action,用来存储记录文本和记录作者。
- 删除动作
记事本中同样需要有删除记录的action,用来删除记录信息。
合约代码
note.cpp
#include <eosiolib/eosio.hpp>
#include <string>
using namespace eosio;
using std::string;
class record : public eosio::contract {
public:
/// @abi table notes i64
struct note {
uint64_t id;
account_name author;
string text;
auto primary_key() const { return id; }
};
typedef multi_index<N(notes), note> notes;
using contract::contract;
/// @abi action
void write(account_name author, string text) {
require_auth(author);
print("Hello, ", name{author});
notes nt( _self, _self );
uint64_t noteId;
nt.emplace(author, [&](auto &n) {
n.id = nt.available_primary_key();// 主键自增
n.author = author;
n.text = text;
noteId = n.id;
});
print("----noteId = ", noteId);
}
void remove(uint64_t id) {
notes nt( _self, _self );
auto it = 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 user
executed transaction: ab59fc4e04342690af46d5bf4dd48c8418d4655e8bcaea81ca3fdc0c99b6fed7 216 bytes 511 us
# note <= note::write {"author":"user","text":"This is my first diary"}
>> Hello, user----noteId = 0
warning: 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 user
Error 3090004: missing required authority
Ensure that you have the related authority inside your transaction!;
If you are currently using ‘cleos push action‘ command, try to add the relevant authority using -p option.
Error Details:
missing authority of miaomiao
正确的授权:
$ cleos push action note remove ‘{"id":2}‘ -p miaomiao
executed transaction: 51eb63f0fdb7d5d01676e898a0f9bc144ee1feda344780042782f359541a578d 192 bytes 442 us
# note <= note::remove {"id":2}
$ 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!"
}
],
"more": false
}
在编写记事本合约时为了找到让主键增加的方法差了很多资料,也走了很多弯路。最后发现其实就是一行代码就能解决的事情。主键自增的使用详见这里。
以上是关于EOS之记事本智能合约的主要内容,如果未能解决你的问题,请参考以下文章