Solidity

轉移到其他帳戶時出現此錯誤:RuntimeError: VM Exception while processing transaction

  • December 1, 2021

我正在使用truffleganache開發智能合約。

我遇到的問題是無法呼叫transfer方法。transfer呼叫內部sendCoin方法時出現以下異常。

data: {
   '0xaf712055f3c88fa2d8f7ed037aee02fadb379a99452a7ca95f39b846748a0753': { error: 'revert', program_counter: 738, return: '0x' },
   stack: 'RuntimeError: VM Exception while processing transaction: revert\n' +
     '    at Function.RuntimeError.fromResults (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/utils/runtimeerror.js:94:13)\n' +
     '    at BlockchainDouble.processBlock (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/blockchain_double.js:627:24)\n' +
     '    at runMicrotasks (<anonymous>)\n' +
     '    at processTicksAndRejections (internal/process/task_queues.js:93:5)',
   name: 'RuntimeError'
 },

這是我在松露控制台中執行的步驟:

truffle(development)> let ledger = await Ledger.deployed()
truffle(development)> let accounts = await web3.eth.getAccounts()
truffle(development)> (await ledger.getBalance(accounts[0])).toNumber()
9990
truffle(development)> await ledger.sendCoin(accounts[1], 10) // this line throws the error above

有誰知道我做錯了什麼?

以下是完整程式碼:

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.4;
pragma experimental ABIEncoderV2;

contract Ledger {
   struct TransferRequest {
       string title;
       uint256 amount;
       string bsb;
       string accountName;
       string accountNumber;
   }

   mapping(address => uint256) balances;

   address payable owner;

   event Transfered(address _from, address _to, uint256 amount);

   constructor() payable {
       owner = payable(msg.sender);
       balances[tx.origin] = 10000;
   }

   function sendCoin(address payable receiver, uint256 amount)
       payable public
       returns (bool sufficient)
   {
       require(msg.sender == owner);
       if (balances[msg.sender] < amount) return false;
       balances[msg.sender] -= amount;
       balances[receiver] += amount;
       receiver.transfer(amount);
       emit Transfered(msg.sender, receiver, amount);
       return true;
   }

   function getBalance(address addr) public view returns (uint256) {
       return balances[addr];
   }

}

receiver.transfer(amount);無法正常工作,因為您的契約餘額少於您嘗試發送的金額。

首先,您需要將一些資金轉移到 Ledger 合約,以便能夠將其轉移到另一個帳戶。

為了使其工作,您需要發送一些 Ether 以及方法呼叫,因為 sendCoin 是支付功能。


> let ledger = await Ledger.deployed()
> await ledger.sendCoin(accounts[1], 10, {value: 10})

您如何做到這一點的另一種方法是支付契約,這可能會讓您更清楚地了解契約的資金來源和轉移方式。

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.1;
pragma experimental ABIEncoderV2;

contract Ledger {
   ...

   receive() external payable {}
}

發送一些資金來簽約,然後sendCoinaccounts[1]


> let ledger = await Ledger.deployed()
> ledger.sendTransaction({from: accounts[0], to: ledger.address, value: 10})
> await ledger.sendCoin(accounts[1], 10)

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