如何在Solidity合约测试中指定执行操作的用户账户身份
问题结论确认
你的推测完全正确,Truffle、Remix 等常用的 Solidity JavaScript 测试环境中,合约方法调用默认的交易发起方(即合约内可读取的msg.sender)就是测试上下文accounts数组的首个元素accounts[0]。
显式指定调用账户的方法
你可以直接在合约方法调用的参数列表末尾,追加一个交易配置对象,通过from字段指定交易发起的账户地址即可,该语法为 web3.js 合约调用的标准规则,在 Truffle、Remix 测试环境中通用。
示例代码如下:
const instance = await MyCoin.deployed() const accountTwo = accounts[1] const amount = 100 // 显式指定从 accounts[2] 账户发起转账操作到 accountTwo await instance.transfer(accountTwo, amount, { from: accounts[2] })
拓展说明
这个交易配置对象还支持传入其他常用交易参数,比如:
value:调用方法时向合约转账的 ETH 数量(单位为 wei)gas:本次交易分配的 gas 上限gasPrice:本次交易的 gas 单价
示例如下:
// 从 accounts[1] 调用 mint 方法,同时向合约转入 0.1 ETH await instance.mint({ from: accounts[1], value: web3.utils.toWei("0.1", "ether"), gas: 300000 })
内容的提问来源于stack exchange,提问作者Sam Joseph
相关产品推荐
相关产品推荐

