You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 10:42:01