通过 javascript 计算 uniswap 对地址
Posted
技术标签:
【中文标题】通过 javascript 计算 uniswap 对地址【英文标题】:Compute uniswap pair address via javascript 【发布时间】:2021-09-30 01:01:59 【问题描述】:我正在尝试按照this Solidity 示例使用 web3js 离线计算 Uniswap 对的地址:
address factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address token0 = 0xCAFE000000000000000000000000000000000000; // change me!
address token1 = 0xF00D000000000000000000000000000000000000; // change me!
address pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
我在js中有以下函数来计算对地址:
function getPair(token0, token1)
const hexadem = '0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f';
const factory = '0xBCfCcbde45cE874adCB698cC183deBcF17952812';
let salt = web3.utils.soliditySha3(token0, token1);
let pair = web3.utils.soliditySha3('0xff', factory, salt, hexadem);
console.log(pair);
return pair
这是上述 Solidity 示例的正确实现吗?当我使用两个令牌地址运行代码时,我得到一个字符串太长而不能成为一对地址。有什么想法吗?
【问题讨论】:
【参考方案1】:这是 pancakeswap 版本,对于 uniswap,您应该只更改 _factory
和 _hexadem
const Web3 = require('web3');
let tokenA = "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c"; // change me!
let tokenB = "0xe9e7cea3dedca5984780bafc599bd69add087d56"; // change me!
let web3 = new Web3("PROVIDER"); // change me!
function getPair(tokenA, tokenB)
let _hexadem = '0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5';
let _factory = "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73";
let [token0, token1] = tokenA < tokenB ? [tokenA, tokenB] : [tokenB, tokenA];
let abiEncoded1 = web3.eth.abi.encodeParameters(['address', 'address'], [token0, token1]);
abiEncoded1 = abiEncoded1.split("0".repeat(24)).join("");
let salt = web3.utils.soliditySha3(abiEncoded1);
let abiEncoded2 = web3.eth.abi.encodeParameters(['address', 'bytes32'], [_factory, salt]);
abiEncoded2 = abiEncoded2.split("0".repeat(24)).join("").substr(2);
let pair = '0x' + Web3.utils.soliditySha3( '0xff' + abiEncoded2, _hexadem ).substr(26);
return pair
console.log( 'PAIR: ', getPair(tokenA, tokenB) )
【讨论】:
以上是关于通过 javascript 计算 uniswap 对地址的主要内容,如果未能解决你的问题,请参考以下文章