Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute uniswap pair address via javascript

I'm trying to compute the address of a Uniswap pair offline with web3js as per this Solidity example:

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'
))));

I have the following function in js to compute the pair address:

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
}

Is this the correct implementation of the above Solidity example? When I run the code with two token addresses I get a string which is too long to be a pair address. Any ideas?

like image 382
revazsurg Avatar asked May 15 '26 11:05

revazsurg


1 Answers

This is the pancakeswap version, for uniswap you should change only the _factory and _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) )
like image 91
Mat.C Avatar answered May 18 '26 18:05

Mat.C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!