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

Clarity智能合约:如何验证函数调用者是否为指定合约?

在Contract2中验证调用者是否为Contract1的实现方案

核心逻辑

要实现这个需求,你需要在Contract2中预先存储Contract1的合法地址,然后在被调用的函数内对比当前调用者地址是否与预存地址一致。

具体实现步骤

1. 在Contract2中定义状态变量存储Contract1地址

添加一个状态变量来保存允许调用的Contract1地址:

pub var allowedContract: Address?

2. 初始化或动态设置Contract1地址

有两种方式完成地址赋值:

  • 部署时直接传入:如果部署Contract2时已经知道Contract1的地址,可在构造函数中初始化:
init(allowedAddr: Address) {
    self.allowedContract = allowedAddr
}

部署Contract2时传入Contract1的地址即可完成初始化。

  • 所有者权限设置:如果需要后续修改允许的合约地址,可添加一个仅所有者可调用的设置函数:
pub fun setAllowedContract(newAddr: Address) {
    // 先验证调用者是合约所有者,防止恶意修改
    asserts!(tx-sender == self.ownerAddress, "Only owner can modify allowed contract")
    self.allowedContract = newAddr
}

3. 在目标函数中添加调用者验证

在Contract2中被Contract1调用的函数里,加入地址校验逻辑:

pub fun yourTargetFunction() {
    // 先确认允许的合约地址已设置
    asserts!(self.allowedContract != nil, "Allowed contract address not configured")
    // 校验调用者是否为Contract1
    asserts!(tx-sender == self.allowedContract!, "ONLY_CONTRACT_ALLOWED")
    
    // 这里写你的业务逻辑
}

关键注意点

  • 确认tx-sender在你使用的合约环境中代表直接调用合约的地址:部分区块链平台中,tx-sender指发起交易的外部账户,而合约间调用的直接调用者需要用caller或类似字段(比如Solidity中的msg.sender),请根据你使用的区块链平台调整字段。
  • 权限控制要严格:设置允许地址的函数必须限制仅所有者可调用,避免被恶意篡改合法调用地址。

内容的提问来源于stack exchange,提问作者Rick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:55:04