Solana Rust智能合约如何自主获取区块高度或Unix时间
合约内部直接获取时间与区块高度实现方案
以下方案完全不需要前端传递时钟相关参数,也无需在合约的账户声明列表中提前声明clock账户,合约可直接自行读取链上数据:
获取当前Unix时间
原生Solana Rust合约写法
use solana_program::clock::Clock; use solana_program::sysvar::Sysvar; // 直接在业务逻辑中调用即可 let current_unix_time = Clock::get()?.unix_timestamp;
获取到的时间为Unix时间戳,单位为秒。
Anchor框架简化写法
let current_unix_time = anchor_lang::prelude::Clock::get()?.unix_timestamp;
获取区块高度
Solana中的slot值可直接作为区块高度使用,同样支持直接读取:
原生Solana Rust合约写法
use solana_program::clock::Clock; use solana_program::sysvar::Sysvar; let current_block_height = Clock::get()?.slot;
Anchor框架简化写法
let current_block_height = anchor_lang::prelude::Clock::get()?.slot;
如果需要获取当前epoch的起始区块高度,可将.slot替换为.epoch_start_slot即可。
内容的提问来源于stack exchange,提问作者Russo
相关产品推荐
相关产品推荐

