Solidity payable函数交易回退错误:如何正确设置Producer完成账户间交易?
问题原因
你的交易回退核心原因是PurchaseFeature1函数中的require(Producer == msg.sender)校验失败:
- 合约中仅声明了
address payable Producer变量,没有任何赋值逻辑,该变量默认值为0x0000000000000000000000000000000000000000 - 你用Producer账户调用函数时,
msg.sender是你的Producer账户地址,和默认的0地址不匹配,触发校验失败导致交易回退,Remix返回的是通用回退报错信息。
修复方案
1. 新增Producer地址设置函数
在合约中添加仅Supplier可调用的Producer地址配置函数,完整代码如下:
pragma solidity ^0.5.0; contract supply { address payable Supplier; address payable Producer; uint constant payment_unit = 1 ether; uint public price_feature1_wei = 0; string public features_product1; bool public SellSuplier = true; bool public contract_terminated = false; constructor () public payable { Supplier = msg.sender; features_product1 = "product description..."; } // 新增:仅供应商可设置允许采购的生产商地址 function setProducer(address payable _producer) public { require(msg.sender == Supplier, "No permission"); Producer = _producer; } function PriceFeature1 (uint amount) public { require (SellSuplier == true); require (Supplier == msg.sender); price_feature1_wei = amount * payment_unit; } function PurchaseFeature1() public payable { require (price_feature1_wei > 0); require (msg.value == price_feature1_wei); require (SellSuplier == true); require (Producer == msg.sender); require (Supplier.send(msg.value)); SellSuplier = false; } }
2. 调整操作流程
修改后的操作步骤如下:
- 部署合约,Supplier账户调用
PriceFeature1传入1设置商品价格(和原有操作一致) - 保持当前账户为Supplier,调用
setProducer函数,入参填你用来作为Producer的Remix账户地址 - 切换Remix账户为Producer,value字段填1 ether,调用
PurchaseFeature1函数即可完成交易
注意事项
如果后续Supplier地址为合约账户而非普通外部账户,send函数2300gas的限制可能导致转账失败,可将require (Supplier.send(msg.value))替换为Supplier.transfer(msg.value)获得更明确的报错,或升级solidity版本使用call进行转账。
内容的提问来源于stack exchange,提问作者LuCast
相关产品推荐
相关产品推荐

