Solidity
在支付功能中需要特定數量的乙太幣
我有一個具有一定邏輯的 payble 函式。我希望僅當收到的金額等於創建契約時指定的金額時才觸發該邏輯。
堅固性 v0.7.6
receive() external payable { require(msg.value == requiredAmount,"Incorrect amount"); logic(); }
問題是當我通過 MetaMask 發送 Ether 時,無論我發送多少 Ether,交易總是失敗。我嘗試檢查
msg.value
固定金額,仍然是同樣的問題:receive() external payable { require(msg.value == 1 ether,"Incorrect amount"); // transaction always fails, even if I send exactly 1ETH. logic(); }
更讓我困惑的是,我知道
requiredAmount
變數設置正確,因為當我使用if/else
程式碼時,程式碼會按預期執行:receive() external payable { if (msg.value != requiredAmount) { // correctly sends back the Ether if the amount isn't equal to the requiredAmount variable (bool success,) = msg.sender.call{value: msg.value}(""); require(success, "Failed to send Ether"); emit MoneyReturned(msg.sender, msg.value); } else { logic(); } }
有誰知道為什麼
require
以我想要的方式使用似乎對我不起作用?
所以我剛剛在 remix 中測試了它,它工作得很好,也許你的函式關鍵字錯誤?
pragma solidity ^0.7.6; contract test { event correctpaymentRecieved(string); function receive() external payable { require(msg.value == 1 ether, "Incorrect amount"); // transaction always fails, even if I send exactly 1ETH. emit correctpaymentRecieved("We got the correct amount of money"); } }
如果我部署該合約,然後在 Remix 中將消息值設置為 1 ether,然後呼叫接收函式檢查 tx 數據,我可以看到發出了正確的paymentRecieved 日誌
這似乎對我有用:
modifier costs(uint _amount){ require(msg.value >= _amount, 'Not enough Ether provided!'); _; } function forceOwnerChange(address _newOwner) public payable costs(200 ether){ owner = _newOwner; }