Solidity

將乙太幣從一份合約轉發到另一份合約

  • January 24, 2022

我目前正在嘗試編寫兩個智能合約。這是第一個:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Token {
   mapping(address => uint) public userBalances;

   function buy() public payable {
       require(msg.value > 0, "Not enough coins sent");
       userBalances[msg.sender] += msg.value;
   }

   function withdrawBalance() public {
       uint amountToWithdraw = userBalances[msg.sender];
       // contains reentrancy attack vector here
       (bool success, ) = msg.sender.call{value: amountToWithdraw}("");
       require(success);
       userBalances[msg.sender] = 0;
   }
}

這是第二個:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

import "./Token.sol";

contract Attacker {
   Token public tokenContract;

   constructor(Token tokenContract) {
       tokenContract = tokenContract;
   }

   function buy() public payable {
       tokenContract.buy{ value: msg.value }();
   }
}

攻擊者合約應該轉發乙太幣以購買一些代幣。然而,我在呼叫攻擊者合約的購買函式時遇到了問題。

這是我在混音中得到的錯誤資訊。

transact to Attacker.buy errored: VM error: revert.

revert
   The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.

我不確定這裡有什麼問題。有人知道嗎?

我告訴你出了什麼問題:螢幕前的開發人員(facepalm)

攻擊者合約的建構子中的參數使用 tokenContract 作為名稱。這會影響狀態變數,從而導致問題。這裡更正的程式碼:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

import "./Token.sol";

contract Attacker {
   Token public tokenContract;

   constructor(Token _token) {
       tokenContract = _token;
   }

   function buy() public payable {
       tokenContract.buy{ value: msg.value }();
   }
}

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