3
uniswap v2 swap path
source link: https://learnblockchain.cn/article/3201
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
uniswap v2 swap path
uniswap v2 swap path
Uniswap v2
什么是 best route
下图中用 matic 去 swap bnb, 红框中的swap 路径即为 best route
- 可以设置一个主流币列表然后用主流币作为中转去遍历
- 使用 uniswap sdk 提供的api besttradeexactin 来计算
以 quickswap sdk 为例,其实和uniswap代码都一样只是包名不同
const {
Fetcher,
WETH,
Route,
Trade,
TokenAmount,
TradeType,
ChainId,
} = require("quickswap-sdk");
const ethers = require("ethers");
// 可以替换为自己的url
const url = "http://127.0.0.1:8545";
const customHttpProvider = new ethers.providers.JsonRpcProvider(url);
const chainId = 1337;
const usdt_address = "0xc2132D05D31c914a87C6611C10748AEb04B58e8F";
const aave_address = "0xD6DF932A45C0f255f85145f286eA0b292B21C90B";
const weth_address = "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619";
const dai_address = "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063";
const init = async () => {
const usdt = await Fetcher.fetchTokenData(
chainId,
usdt_address,
customHttpProvider
);
const aave = await Fetcher.fetchTokenData(
chainId,
aave_address,
customHttpProvider
);
const weth = await Fetcher.fetchTokenData(
chainId,
weth_address,
customHttpProvider
);
const dai = await Fetcher.fetchTokenData(
chainId,
dai_address,
customHttpProvider
);
// 需要获取protocol的所有token并组合pair ,但是这样效率太低 所以准备几个主流币作为中间转换币应该没什么问题
const pairs = await Fetcher.fetchPairData(aave, usdt, customHttpProvider);
const epairs = await Fetcher.fetchPairData(aave, weth, customHttpProvider);
const epairs2 = await Fetcher.fetchPairData(weth, usdt, customHttpProvider);
const epairs3 = await Fetcher.fetchPairData(aave, dai, customHttpProvider);
const epairs4 = await Fetcher.fetchPairData(dai, usdt, customHttpProvider);
const route = new Route([pairs], aave);
// const trade = new Trade(
// route,
// new TokenAmount(aave, "1000000000000000000"),
// TradeType.EXACT_INPUT
// );
// console.log(route.path);
console.log("Mid Price aave --> usdt:", route.midPrice.toSignificant(6));
const amountIn = new TokenAmount(aave, "1000000000000000000");
const best = Trade.bestTradeExactIn(
[pairs, epairs3, epairs4, epairs, epairs2],
amountIn,
usdt
// new TokenAmount(usdt, 1000000)
);
// 打印最佳路径
console.log(best[0].route.path);
};
init();
Uniswap v3
v3 版本的 swap path已经是一个中心化服务来提供查询了
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。
- 发表于 17小时前
- 阅读 ( 41 )
- 学分 ( 5 )
- 分类:Uniswap
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK