Solidity

轉移僅適用於“應付地址”類型的對象,不適用於“地址”

  • January 7, 2022

我正在閱讀由 Packt Publishing 出版的 Jitendra Chittoda所著的**Mastering Blockchain Programming With Solidity。**在第 129 頁,它有一個使用 Remix IDE 和 MetaMask 部署的範例合約。部署範例.sol

我已經修改了這段程式碼以克服一些錯誤,但現在我被卡住了:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";

/**
* @title Contract Deployment Example
*/
contract DeploymentExample is Ownable {
   using SafeMath for uint;

   mapping(address  => uint) public balances;
   uint public totalDeposited;

   event Deposited(address indexed who, uint amount);
   event Withdrawn(address indexed who, uint amount);

   /**
    * @dev The fallback function to receive ether.
    */
   receive() external payable {
       depositEther();
   }

   /**
    * @dev Deposits Ether to the contract
    */
   function depositEther() public payable {
       require(msg.value > 0);
       balances[msg.sender] = balances[msg.sender].add(msg.value);
       totalDeposited = totalDeposited.add(msg.value);
       emit Deposited(msg.sender, msg.value);
   }

   /**
    * @dev Withdraw the deposit ether balance.
    * @param _amount Amount to withdraw.
    */
   function withdraw(uint _amount) public  {
       require(balances[msg.sender] >= _amount);
       balances[msg.sender] = balances[msg.sender].sub(_amount);
       totalDeposited = totalDeposited.sub(_amount);
       msg.sender.transfer(_amount);
       emit Withdrawn(msg.sender, _amount);
   }

   /**
    * @dev Destroy the contract and send all ether balance to owner.
    */
   function kill() public onlyOwner {
       //Convert from `address` to `address payable`
       address payable payableOwner = address(uint160(owner()));
       selfdestruct(payableOwner);
   }
}

在第 45 行,程式碼msg.sender.transfer(_amount);給了我錯誤TypeError: “send” 和 “transfer” 僅適用於 “address paid” 類型的對象,而不是 “address”

部分問題似乎是我必須更改編譯器版本才能使用導入的 OpenZeppelin 合約。

msg.sender從 Solidity 0.8.x 開始不再是支付地址。您可以使用 將其顯式轉換為應付賬款payable(msg.sender)。那應該可以解決錯誤。

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