合约的执行结果和历史的数据结构 / 学习智能合约#57

4개월 전

在执行智能合约时如何确定合约的正确执行结果呢?在得到正确的结果后再执行一系列的操作。比如现实中,只有你已确定付款后才能拿走商品一样,智能合约只能得到正确的结果才能进行下一步。

要起得到确定的结果,一般有两种办法:一种是轮询事件,另一种是直接分析得到的结果 。例如:let res = await instance.methods.transfer(to, amount), 第一种:可以轮询事件,直到查到想要的事件为目,事件(history)数据结构如下:

address: '0x4369bAD2aBb80a234f38xxxxxx',
blockNumber: 25102441,
transactionHash: '0x10468cdc4dfbea5f03bd26f4b6ecxxxx',
transactionIndex: 42,
blockHash: '0x5a7690d19e935cdfdf72axxx',
logIndex: 200,
removed: false,
id: 'log_d9709891',
returnValues: Result {
  '0': '0x4870fd1f34xxxxxxxxxxxxxx',
  '1': '0x4870fd1f34EdD28800D92c3A3F7Eb179095284aB',
  '2': '11500000000000000000',
  from: '0x4870fd1f34xxxxxxxxxxxxxx',
  to: '0x4870fd1f34EdD28800D9xxxxxxx',
  amount: '11500000000000000000'
},
event: 'Transfer',
signature: '0x417646ecea3e1b1950ce7xxxxx',
raw: {
  data: '0x00000000000xxxxxx',
  topics: [Array]
}
},

通过检查returnValues中的数据可以确保是否得到正确的结果。

另一种是另一种是直接分析得到的结果,从res中分析数据,如下所示:

blockHash: "0xaa02b1e9ea4fd46c1c5039a59820cxxxx"
blockNumber: 25109634
contractAddress: null
cumulativeGasUsed: 7898685
effectiveGasPrice: 35108799999
events: {0: {…}, Transfer: {…}}
from: "0x4870fd1f34edd28800d92c3xxxx"
gasUsed: 36598
logsBloom: "0x000000000001100220"
status: true
to: "0x4369bad2abb80a234f38757xxxx"
transactionHash: "0xb70ca889e155a4ee21b754d0fxxxxx"
transactionIndex: 71
type: "0x2"
[[Prototype]]: Object

可以从status= true来判断是否得到正确结果。这种方法也都是ok的。

至于采用哪一种方法,要看应用场景的需求,灵活应用。

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
STEEMKR.COM IS SPONSORED BY
ADVERTISEMENT