eos 智能合约执行过程中能获取到的上下文
当前块高
无法获取,注意 tapos_block_num()
函数返回的不是当前块高,而是参考块高的低 16 位。具体见 get current block number in contract #5502。
替代方案是获取当前时间 now()
,eos 区块是每 500 毫秒生成一次,然后根据 now()
反算块高。如果 eos 区块链出现出现停机的话,或者生产块高间隔不是稳定的 500 毫秒,那么时间与块高的映射关系就不是纯粹的线性关系了。
例如,块高为 1
的,其时间戳是 1528877288 s,eos 区块是每 500 毫秒生成一次。那么块高 47539289
的时间戳是 1528877288 + (47539289-1) * 0.5 = 1552646932
,但是实际时间是 1552552909 s。误差还是十分大,差了一天。
当前交易hash
参考如下的代码
#include <eosiolib/types.hpp>
#include <eosiolib/transaction.hpp>
#include <eosiolib/crypto.h>
void getCurrentHash(checksum256* hash) {
auto size = transaction_size();
char buf[size];
uint32_t read = read_transaction(buf, size);
eosio_assert(size == read, "read_transaction failed");
sha256(buf, read, hash);
}
获取 action
获取指定下标的 action
可以通过 get_action
获取。get_action
的函数声明如下:
/**
* Retrieve the indicated action from the active transaction.
* @param type - 0 for context free action, 1 for action
* @param index - the index of the requested action
* @return the indicated action
*/
eosio::action eosio::get_action( uint32_t type, uint32_t index );
type
的取值有 0
和 1
,0
是上下文无关的 action (context free action),上下文无关意味着可以并发执行。1
是普通的 action。
index
是 action
的下标。
不过 eos 合约中无法直接获取到所有的 action
。