找回密码
 立即注册
搜索
热搜: GTokenTool
查看: 114|回复: 1

合约内如何判断调用者是否为合约创建者

[复制链接]

212

主题

211

回帖

1228

积分

管理员

积分
1228
发表于 2025-7-23 18:59:24 | 显示全部楼层 |阅读模式
合约内如何判断调用者是否为合约创建者

212

主题

211

回帖

1228

积分

管理员

积分
1228
 楼主| 发表于 2025-7-23 19:03:31 | 显示全部楼层
在Solidity智能合约中,判断调用者是否为合约创建者(部署者)有几种常见方法:
方法1:在构造函数中存储创建者地址solidity





address public owner;constructor() {    owner = msg.sender; // 在部署时将创建者地址存储到owner变量}function isOwner() public view returns (bool) {    return msg.sender == owner;}

方法2:使用修饰器solidity





address public owner;constructor() {    owner = msg.sender;}modifier onlyOwner() {    require(msg.sender == owner, "Caller is not the owner");    _;}function restrictedFunction() public onlyOwner {    // 只有创建者可以调用此函数}

方法3:直接比较msg.sendersolidity





function checkIfCreator() public view returns (bool) {    return msg.sender == owner;}

注意事项
  • msg.sender 是当前函数调用者的地址
  • 合约创建者是在合约构造函数中通过 msg.sender 捕获的
  • 如果需要转移所有权,可以添加一个函数:

solidity





function transferOwnership(address newOwner) public onlyOwner {    require(newOwner != address(0), "Invalid address");    owner = newOwner;}

  • 在较新版本的Solidity中,考虑使用 Ownable 合约(OpenZeppelin库提供)

这些方法都能有效判断调用者是否为合约创建者,最常用的是第一种方法,即在构造函数中存储创建者地址。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Telegram|手机版|小黑屋|GTokenTool

GMT+8, 2025-9-11 04:06 , Processed in 0.021145 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表