Solidity

如何在solidity中解決此錯誤“如果您發送值,則應支付建構子。”?

  • August 30, 2021

在這個可靠的程式碼中,finalizeRequest() 給出了一個執行時錯誤。這是錯誤:

Campaign.finalizeRequest(uint256) 0x692...77b3a

transact to Campaign.finalizeRequest errored: VM error: revert.
revert  The transaction has been reverted to the initial state.
Note: The constructor should be payable if you send value.  Debug the transaction to get more information.

這是程式碼:

pragma solidity ^0.5.14;

contract Campaign {
   struct Request {
       string description;
       uint value;
       address payable recipient;
       bool complete;
       uint approvalCount;
       mapping (address => bool) approvals;
   }

   address public manager;
   uint public minimumContribution;
   // address[] public approvers;
   mapping (address => bool) public approvers;
   Request[] public requests;
   uint public approversCount;


   constructor(uint minimum) public {
       manager=msg.sender;
       minimumContribution=minimum;
   }

   function contribute() public payable {
       require(msg.value>minimumContribution);
       // approvers.push(msg.sender);
       approvers[msg.sender]=true;
       approversCount++;
   }

   function createRequest(string memory description,uint value,address payable recipient) public restricted {
       // require (approvers[msg.sender]);    
       Request memory newRequest=Request({description:description,value:value,recipient:recipient,complete:false,approvalCount:0});
       requests.push(newRequest);

   }

   function approveRequest(uint index) public {
       Request storage request=requests[index];

       require(approvers[msg.sender]);
       require(!request.approvals[msg.sender]);
       request.approvals[msg.sender]=true;
       request.approvalCount++;
   } 

   function finalizeRequest(uint index) public restricted payable{
       Request storage request = requests[index];

       require(request.approvalCount>=(approversCount/2));
       require(!request.complete);
       request.recipient.transfer(request.value);
       request.complete=true;

   } 

   modifier restricted() {
       require (msg.sender == manager);
       _;
   }
}

據我調試,當我註釋掉 request.recipient.transfer(request.value); 在 finalizeRequest() 函式中不會引發執行時錯誤。所以錯誤似乎在這行程式碼中,請幫助解決這個問題。

錯誤消息具有誤導性。您可以放心地忽略它,因為您沒有呼叫建構子或發送資金。

有很多程式碼需要遍歷,所以這不會很具體。

你說這似乎是問題:

request.recipient.transfer(request.value);

最可能的原因是契約沒有足夠的資金來實現這一點。它不能transfer乙太它沒有。所以,後退一步,確保contribute正在做你認為的事情。考慮添加:

function contractBalance() public view returns(uint) {
 return address(this).balance;
}

還看request.value. 確保它不超過契約規定的數量。可能是會計錯誤造成了麻煩。

您可以使用較新的編譯器(0.4.17 非常舊)並添加還原原因:

require(true, "How could that not be true? Something seriously haywire.");

這不會擷取transfer協議錯誤的特定錯誤。您可能會考慮註釋掉有問題的語句,並再次記錄事件。

就像是:

// request.recipient.transfer(request.value);
emit LogDebug(request.value, address(this).balance);

希望能幫助到你。

引用自:https://ethereum.stackexchange.com/questions/79206