EOS智能合约授权限制和数据存储
EOS智能合約授權限制和數(shù)據(jù)存儲
在EOS合約中,調(diào)用合約需要來自賬戶的授權,同時還要指定需要調(diào)用的動作。當然,有的合約并不是所有賬戶都可以調(diào)用的,這就需要用到授權限制。接下來我們就來看看如何限制合約的授權賬戶。
合約案例
為了更好的演示,寫了一個下課和吃飯的智能合約小例子。這個合約有兩個動作,下課和吃飯。教師賬戶可以調(diào)用下課動作,學生賬戶可以調(diào)用吃飯動作。教師調(diào)用下課動作后,學生才能調(diào)用吃飯動作。接下來我們來看代碼:
teacher.hpp
頭文件teacher.hpp定義了兩個動作,over是class over 下課動作,eat是吃飯動作。
#include <eosiolib/eosio.hpp> #include <eosiolib/print.hpp>using namespace eosio;class teacher_stu : public eosio::contract{using contract::contract;public:teacher_stu( account_name self ) :contract( self ) {}void over(account_name teacher);void eat(account_name student);private:static uint64_t id;// @abi tablestruct mshare {uint64_t id;uint64_t start = 0;uint64_t primary_key() const { return id; }};typedef multi_index<N(mshare), mshare> mshares;};EOSIO_ABI( teacher_stu, (over)(eat))teacher.cpp
teacher.cpp中主要是over和eat動作的實現(xiàn)。
#include "teacher.hpp"uint64_t teacher_stu::id = 1; uint64_t start = 0;void teacher_stu::over(account_name teacher) {require_auth(teacher);print("teache:Class over!");mshares mshare_table(_self, _self);start = 1;//存儲動作調(diào)用狀態(tài)mshare_table.emplace( teacher, [&]( auto& mshare ) {mshare.id = id;mshare.start = start;}); }void teacher_stu::eat(account_name student) {require_auth(student);mshares mshare_table(_self, _self);auto it = mshare_table.find( id );if (it->start == 1) {print("student:Class over, go to eat!");mshare_table.erase( it );}elseprint("teacher:Class time, you can't eat"); }仔細觀察這段代碼就會發(fā)現(xiàn),over和eat動作中都有個"require_auth()"語句。在over動作中,"requir_auth(teacher)"的作用是限制只有"teacher"賬戶才可以調(diào)用over動作。在eat動作中則是限制只有"student"賬戶才可調(diào)用eat動作。
合約數(shù)據(jù)存儲
此合約設計為下課后才可以吃飯,所以當教師賬戶調(diào)用合約的over動作后,需要存儲一個合約調(diào)用狀態(tài)值。EOS合約的數(shù)據(jù)存儲需要用數(shù)據(jù)庫,把數(shù)據(jù)存到一張表中,這是令人很難受的。
teacher.hpp
在teacher.hpp中創(chuàng)建一個結構體。下段代碼中的"//@abi table"注釋非常重要,必須要寫的,如果不寫數(shù)據(jù)將無法存儲。
static uint64_t id;// @abi tablestruct mshare {uint64_t id;uint64_t start = 0;uint64_t primary_key() const { return id; }};typedef multi_index<N(mshare), mshare> mshares;DAWN 3.0 使用eosio::multi_index作為容器,我們可以使用emplace來插入數(shù)據(jù),使用modify來修改數(shù)據(jù),使用erase刪除數(shù)據(jù)。
teacher.cpp
mshares mshare_table(_self, _self);start = 1;mshare_table.emplace( teacher, [&]( auto& mshare ) {mshare.id = id;mshare.start = start;});在over動作中創(chuàng)建數(shù)據(jù),學生調(diào)用eat動作后再修改或刪除數(shù)據(jù)即可
mshares mshare_table(_self, _self);auto it = mshare_table.find( id );if (it->start == 1) {print("student:Class over, go to eat!");mshare_table.erase( it );}合約調(diào)用效果展示
- 授權限制
- 學生沒下課就吃飯
- 正常下課吃飯
- 查看表中數(shù)據(jù)
整個合約寫下來調(diào)通也是費了我很多腦細胞,數(shù)據(jù)存儲也比較坑爹啊。現(xiàn)在把我的一點經(jīng)驗分享出來,希望大家在學習EOS的路上少踩一些坑。
歡迎添加微信(id:pdj107)
轉(zhuǎn)載于:https://www.cnblogs.com/tokenpai/p/9175959.html
總結
以上是生活随笔為你收集整理的EOS智能合约授权限制和数据存储的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过JS如何获取IP地址
- 下一篇: Vagrant挂载目录失败mount: