Solidity

通過函式呼叫將合約 ETH 轉換為 WETH

  • March 5, 2022

我正在嘗試編寫一個簡單的solidity合約,它可以:

  • 接收 ETH
  • 將 ETH 轉換為 WETH
  • 顯示 ETH 餘額
  • 顯示 WETH 餘額

ETH 操作似乎按預期工作,但是每當我嘗試呼叫任何 WETH 函式時,我都會收到錯誤並且交易被還原。

我嘗試實例化 WETH 令牌或與 WETH 令牌互動的方式有問題嗎?

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

interface IERC20 {
   event Approval(address indexed owner, address indexed spender, uint value);
   event Transfer(address indexed from, address indexed to, uint value);

   function name() external view returns (string memory);
   function symbol() external view returns (string memory);
   function decimals() external view returns (uint8);
   function totalSupply() external view returns (uint);
   function balanceOf(address owner) external view returns (uint);
   function allowance(address owner, address spender) external view returns (uint);

   function approve(address spender, uint value) external returns (bool);
   function transfer(address to, uint value) external returns (bool);
   function transferFrom(address from, address to, uint value) external returns (bool);
}

interface IWETH is IERC20 {
   function deposit() external payable;
   function withdraw(uint) external;
}

contract Scrath {

   address private weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

   function sendEth() external payable {
       if(msg.value < 1000) {
           revert();
       }
   }

   function ethBalance() public view returns(uint256 _balance) {
       _balance =  address(this).balance;
       return _balance;
   }

   function convertToWeth() external payable {
       uint256 eth = ethBalance();
       IWETH(weth).deposit{value: eth}();
   }

   function wethBalance() external view returns(uint256 _balance) {
       _balance = IWETH(weth).balanceOf(address(this));
       return _balance;
   }

}

嘗試在 Ropsten、Rinkeby 或 Goerli 等乙太坊測試網中註入程式碼。根據測試網的選擇,您必須使用測試網的 WETH 智能合約地址更改這行程式碼:

address private weth = [ADDRESS_WETH_SMART_CONTRACT];

範例:如果我決定在 Rinkeby 測試網中分發我的智能合約,我將weth variable使用 WETH 智能合約的地址進行更改。

對於 Rinkeby,地址 WETH 是:0xc778417E063141139Fce010982780140Aa0cD5Ab (查看此連結了解更多資訊)。

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