Web3js
如何在 JavaScript web3/ethers 中將 uint256 和地址類型發送到智能合約?
我試圖向 Pancakeswap 的路由器函式 getAmoutsOut 發送查詢,這裡是使用 ethers ABI 導入合約的程式碼:
const router = new ethers.Contract('0x10ED43C718714eb63d5aA57B78B54704E256024E', [ 'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)', 'function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts)' ], account);
正如您已經知道的那樣,參數位於 uint256 和地址類型對像數組中。Ami 應該如何向合約發送有效的參數類型。我已經嘗試了幾個內置的 ethers 實用程序功能,但到目前為止還沒有運氣。我 90% 確定錯誤來自 BNB 金額。
另外請注意,只要您使用 BSC 節點,乙太幣就可以與 BSC 一起正常工作。很像web3。無論如何,這是契約部署的程式碼。
desiredCoin = 'coin contract address example'; bnb = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c'; const amountIn = 1000000000000000000 // 1 bnb const pairAddress = [ethers.utils.getAddress(bnb), ethers.utils.getAddress(desiredCoin)]; amounts = await router.getAmountsOut( ethers.utils.getAddress('0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73'), //this is the factory address. amountIn, pairAddress); amountOutMin = amounts.sub(amounts[1].div(slippage) //(Ik that if we were to work with hex this wouldnt be valid :/) );
您似乎正在嘗試使用錯誤的 getAmountsOut 函式:
// performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'PancakeLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } }
此函式被標記為內部函式,因此只能在此合約或派生自 PancakeRouter 合約的任何合約內部呼叫。正確呼叫的函式是這個也位於 PancakeRouter 合約中的函式:
function getAmountsOut(uint amountIn, address[] memory path) public pure virtual override returns (uint[] memory amounts) { return PancakeLibrary.getAmountsOut(factory, amountIn, path); }
–
給你一個關於如何在 Javascript 中使用它的例子:
const router = new ethers.Contract('0x10ED43C718714eb63d5aA57B78B54704E256024E', [ 'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)', 'function getAmountsOut(uint amountIn, address[] memory path) public pure virtual override returns (uint[] memory amounts)' ], account); const amountIn = 1 const fromTokenAddress = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c' //BNB const toTokenAddress = '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56' //BUSD let amountOuts = await router.getAmountsOut(amountIn, [fromTokenAddress, toTokenAddress])
-> amountOuts 的第一個數組元素將是您發送的 amountIn
編輯: 可以使用 wei 單位表示發送十進制值。只需將您要發送的值與 10 ** 18 相乘,如下例所示:
22.5 BNB -> 22.5 * 10 ** 18 = 22500000000000000000
有許多有用的庫可以幫助您處理這些數字並提供計算功能。例如ethers.js包含這樣的實現,它可以很容易地使用,只是要注意你正在使用的版本,因為在 ethers.js 中 BigNumbers 的使用在版本上是不同的。