【发布时间】:2021-12-09 22:06:04
【问题描述】:
我目前正在开发一个与 uniswap 交互的应用程序,并且我已经开发了一个 Wrapper 类来包含我需要的关于某对(例如 DAI/WETH)的信息和变量。
由于其中一些值是异步的,我编写了一个 build() 异步函数来在调用构造函数之前获取这些值,以便我可以存储它们。我想将这个构建函数的结果(我定义的类的一个实例)存储在一个变量中以供以后使用,但我需要知道该构建函数返回的 Promise 在使用它之前是否已解决,所以我怎样才能做到?
这是类的代码:
'use strict'
const { ChainId, Fetcher, WETH, Route, Trade, TokenAmoun, TradeType, TokenAmount } = require('@uniswap/sdk')
const { toChecksumAddress } = require('ethereum-checksum-address')
const Web3 = require('web3')
const web3 = new Web3()
const chainId = ChainId.MAINNET;
let tok1;
let tok2;
let pair;
let route;
let trade;
class UniswapTokenPriceFetcher
{
constructor(async_params)
{
async_params.forEach((element) => {
if (element === 'undefined')
{
throw new Error('All parameters must be defined')
}
});
this.trade = async_params[0];
this.route = async_params[1];
this.pair = async_params[2];
this.tok1 = async_params[3];
this.tok2 = async_params[4];
}
static async build(token1, token2)
{
var tok1 = await Fetcher.fetchTokenData(chainId, toChecksumAddress(token1))
var tok2 = await Fetcher.fetchTokenData(chainId, toChecksumAddress(token2))
var pair = await Fetcher.fetchPairData(tok1, tok2)
var route = new Route([pair], tok2)
var trade = new Trade(route, new TokenAmount(tok2, web3.utils.toWei('1', 'Ether')), TradeType.EXACT_INPUT)
return new UniswapTokenPriceFetcher([trade, route, pair, tok1, tok2])
}
getExecutionPrice6d = () =>
{
return this.trade.executionPrice.toSignificant(6);
}
getNextMidPrice6d = () =>
{
return this.trade.nextMidPrice.toSignificant(6);
}
}
module.exports = UniswapTokenPriceFetcher
谢谢大家!
编辑:我知道 Uniswap 只与 WETH 配对,所以我的令牌变量之一是不必要的,但问题仍然存在!另外请记住,我想存储此类的一个实例以供以后在另一个文件中使用。
【问题讨论】:
-
您能告诉我们您在调用构建静态方法时遇到的错误吗?或者用您尝试过的任何尝试更新您的答案?
标签: node.js blockchain ethereum