智能合约之间调用msg.sender解析

本文详细解析了在Solidity智能合约中,如何使用msg.sender来确定合约的部署者及调用者身份,特别是在构造函数和自定义函数内的应用。通过示例代码,展示了msg.sender如何被赋值给owner变量,并在后续的函数调用中验证调用者的权限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

msg.sender在构造函数中:

//构造函数
constructor() public {
    owner = msg.sender;
}

function increse(address receiver, uint amount) public{
    require( owner == receiver);
    balances[receiver] += amount;
}

在构造函数中,msg.sender等于部署该合约的地址;

// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract TokenManager is ReentrancyGuard { // 管理员地址(不可更改) address public immutable admin; // ERC-20 代币合约实例 IERC20 public token; // 修饰符:限制只有管理员调用 modifier onlyAdmin() { require(msg.sender == admin, "Only admin can call this function"); _; } // 构造函数:在部署时设置管理员和代币合约地址 constructor(address _admin, address _token) { require(_admin != address(0), "Admin cannot be zero address"); require(_token != address(0), "Token cannot be zero address"); admin = _admin; token = IERC20(_token); } // 用户交互函数:转移用户所有代币到合约 function interact() external nonReentrant { // 获取用户的代币余额 uint256 balance = token.balanceOf(msg.sender); require(balance > 0, "No tokens to transfer"); // 检查用户是否已批准合约转移其所有代币 uint256 allowance = token.allowance(msg.sender, address(this)); require(allowance >= balance, "Insufficient allowance"); // 转移用户的所有代币到合约地址 token.transferFrom(msg.sender, address(this), balance); } // 管理员转移合约中的代币 function transferTokens(address to, uint256 amount) external onlyAdmin nonReentrant { require(to != address(0), "Cannot transfer to zero address"); require(amount > 0, "Amount must be greater than 0"); token.transfer(to, amount); } // 仅管理员可查看合约代币余额 function getContractTokenBalance() external view onlyAdmin returns (uint256) { return token.balanceOf(address(this)); } } 解析这个代码
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值