Remix

將 ETH 換成代幣並返回 Remix

  • November 4, 2021

我只是想創建一個簡單的智能合約,可以將 eth 換成代幣,然後將這些代幣換回 ETH。

這是我的程式碼:

// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.7;

interface IUniswap {
   function swapExactTokensForETH(
       uint amountIn, 
       uint amountOutMin, 
       address[] calldata path, 
       address to, 
       uint deadline)
   external
   returns (uint[] memory amounts);
   
   function swapExactETHForTokens(
           uint amountOutMin, 
           address[] calldata path, 
           address to, 
           uint deadline)
       external
       payable
   returns (uint[] memory amounts);
   
   function WETH() external pure returns (address);
}

interface IERC20 {
   function transferFrom(
       address sender,
       address recipient,
       uint256 amount
   ) external returns (bool);
   
   function approve(address spender, uint256 amount) external returns (bool);
}

contract EzSwap {
   IUniswap uniswap;
   
   constructor(address _uniswap) {
       uniswap = IUniswap(_uniswap);
   }
   
   function swapExactETHForTokens(
       address token,
       uint amountOutMin, 
       uint deadline) external payable {
           
           address[] memory path = new address[](2);
           path[0] = uniswap.WETH();
           path[1] = token;
           
           uniswap.swapExactETHForTokens{value: msg.value}(
               amountOutMin,
               path,
               msg.sender,
               deadline);
   }
       
   // uniswap address 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
   function swapTokensForETH(
       address token, 
       uint amountIn, 
       uint amountOutMin, 
       uint deadline) external {
           IERC20(token).transferFrom(msg.sender, address(this), amountIn);
           address[] memory path = new address[](2);
           path[0] = token;
           path[1] = uniswap.WETH();
           IERC20(token).approve(address(uniswap), amountIn);
           uniswap.swapExactTokensForETH(amountIn, amountOutMin, path, msg.sender, deadline);
   }
}

當我嘗試執行時swapExactETHForTokens出現錯誤:

false 交易被探勘但執行失敗

編輯:

我正在將此地址用於 UniswapV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)

token = '0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa' //DAI Address
amountOutMin = 1   //Arbirary value that should always pass
Deadline = Math.floor(Date.now() / 1000) + 60 * 10 // calculating deadline from current timestamp
Value = 90 // In ETH

我什麼也沒看到,它應該可以工作,可能是路由器地址不正確 IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),或者交易value不足以購買amountOutMin,或者該代幣沒有礦池或流動性提供者

確保您使用的是正確的 RPC。在視窗中將環境更改為InjectedWeb3Provider 並設置您的 Infura RPC

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