Web3js
為什麼我的 for 循環沒有獲取多個令牌數據?
我有點菜鳥,所以請耐心等待,但我非常喜歡區塊鏈,這就是我在這裡的原因,所以請聽我說/幫助我。我正在為 Uniswap 建構價格掃描器,所以我有這個程序來檢查 Uniswap 上執行良好的 DAI/WETH 的價格:
const { ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent } = require('@uniswap/sdk'); const ethers=require('ethers'); const chainId = ChainId.MAINNET; const daiAddress = '0x6b175474e89094c44da98b954eedeac495271d0f'; const init = async () => { const dai = await Fetcher.fetchTokenData(chainId, daiAddress); const weth = WETH[chainId]; const pair = await Fetcher.fetchPairData(dai, weth); const route = new Route([pair], weth); const trade = new Trade(route, new TokenAmount(weth, '100000000000000000'), TradeType.EXACT_INPUT); console.log(route.midPrice.toSignificant(6));
但是,如果我想在檢查多個令牌的價格時創建一個 for 循環,我會在 for 循環中添加另一個令牌,但是 node.js 會拋出一個錯誤:(node:8368) UnhandledPromiseRejectionWarning: Error: Invariant failed: CHAIN_ID
這是程式碼:
const { ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent } = require('@uniswap/sdk'); const ethers=require('ethers'); const chainId = ChainId.MAINNET; const daiAddress = '0x6b175474e89094c44da98b954eedeac495271d0f'; const sushiAddress = '0x6b3595068778dd592e39a122f4f5a5cf09c90fe2'; const init = async () => { const dai = await Fetcher.fetchTokenData(chainId, daiAddress); const sushi = await Fetcher.fetchTokenData(chainId, sushiAddress) tokens = [dai, sushi]; const weth = WETH[chainId]; for (token in tokens) { const pair = await Fetcher.fetchPairData(token, weth); } const route = new Route([pair], weth); const trade = new Trade(route, new TokenAmount(weth, '100000000000000000'), TradeType.EXACT_INPUT); console.log(route.midPrice.toSignificant(6));
如何創建一個正確的 for 循環來檢查我輸入的標記?
如果你能幫助一個 n00b 走向輝煌的 web3 矩陣 <3,那就太愛了
改變這個:
for (token in tokens)
對此:
for (token of tokens)
這是 Javascript 中的一個常見錯誤(順便說一句,這與乙太坊無關)。