Solidity

無法使用 IUniswapV2Factory 創建對

  • December 4, 2021

我正在編寫一份 BEP20 合約,交易費用固定,該合約被交換並發送到團隊錢包。為了使整個工作正常,我可以成功地在契約中初始化一個IUniswapV2Router02IUniswapV2Factory對象,constructor但是當我在 Remix 中部署契約(環境:JavaScript VM)時,我得到一個VM error: revert. 當我嘗試傳遞_factory.createPair(address(this), _router.WETH())addPair函式時,我可以調查程式碼崩潰。不幸的是,我對此不太熟悉,但我認為該addPair功能很好,問題在於我試圖通過的論點。據我所知,它應該返回一個address而不是產生這個錯誤。如果有人看到我做錯了什麼或知道創建token-eth(bnb)配對的更好解決方案,我很樂意看到解決方案。

pragma solidity ^0.8.7;

import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";

interface IBEP20 {
  //...
}

contract BEP20Token is Context, IBEP20, Ownable {
   using SafeMath for uint256;

   mapping (address => uint256) private _balances;
   mapping (address => mapping (address => uint256)) private _allowances;
   
   mapping(address => bool) private _pair;
   
   string private _symbol;
   string private _name;
   uint256 private _totalSupply;
   uint8   private _decimals;
   uint256 private _developmentTax = 3;

   address private constant _factoryAddress = 0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73;
   address private constant _routerAddress = 0x10ED43C718714eb63d5aA57B78B54704E256024E;
   address private constant _deadAddress = 0x000000000000000000000000000000000000dEaD;
   address private _pairAddress;

   IUniswapV2Factory private _factory;
   IUniswapV2Router02 private _router;

 constructor()  {
   _name = "My Token";
   _symbol = "TKN";
   _decimals = 18;
   _totalSupply = 1000 * 10 ** 18;
   _balances[_msgSender()] = _totalSupply;
   _maxTransferLimit = _totalSupply;

   _router = IUniswapV2Router02(_routerAddress);
   _factory = IUniswapV2Factory(_factoryAddress);   
   // it crashes in this line:
   addPair(_factory.createPair(address(this), _router.WETH()));
   
   emit Transfer(address(0), msg.sender, _totalSupply);

 }

   function addPair(address pairAddress) public onlyOwner {
       _pair[pairAddress] = true;
       _pairAddress = pairAddress;
       emit AddPair(pairAddress);
   }


}

這是錯誤消息

創建 BEP20Token 錯誤:VM 錯誤:還原。

revert 事務已恢復到初始狀態。注意:如果您發送值並且您發送的值應該小於您目前的餘額,則呼叫的函式應該是應付的。調試事務以獲取更多資訊。

您試圖從建構子中呼叫一個函式,它甚至不應該編譯(即“addPair() 此時不(或尚不)可見。”)。

要麼將函式的邏輯複製到建構子中,要麼在部署後呼叫此函式。

我相信這個連結會解決它為什麼不起作用的問題。

總結一下:“您不能在正在建構的合約上呼叫外部函式(例如 this.foo();在建構子內部將恢復合約創建交易)”

將其應用於您的程式碼: _factory.createPair() & _router.WETH() 我相信正在呼叫外部函式。

對我的回答持保留態度。我還在學習自己,很可能是錯的。

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