Solidity

73: TypeError: ‘send’ 和 ’transfer’ 僅適用於 ‘address paid’ 類型的對象

  • December 31, 2020

這是我遵循教程的簡單程式碼。我們正在建構彩票智能合約。但是,我未能將契約餘額轉給獲勝者。(見契約最後一行。)

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

contract Lottery {
   address public manager;
   address [] public players;

   constructor() {
       manager = msg.sender;
   }
   
   function enter() public payable {
       require(msg.value > .01 ether);

       players.push(msg.sender);
   }
   
   function random() private view returns (uint) {
       return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players)));
   }

   function pickWinner() public {
       uint index = random() % players.length;

       players[index].transfer(address(this).balance);
   }
}

我在混音中收到以下錯誤:

TypeError: "send" and "transfer" are only available for objects of type "address payable"

我理解錯誤並嘗試更改 player 變數的聲明,如下所示:

address payable[] public players;

但這給了我另一個錯誤:

TypeError: Member "push" not found or not visible after argument-dependent lookup in address payable[] storage ref.

有人可以幫我嗎?

你可以使用這個:

address[] public players;
...
players.push(msg.sender);
...
payable(players[index]).transfer(...);

或這個:

address payable[] public players;
...
players.push(payable(msg.sender));
...
players[index].transfer(...);

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