39 lines
1.5 KiB
JavaScript
39 lines
1.5 KiB
JavaScript
import {ethers, FixedNumber} from "ethers";
|
|
|
|
const UNISWAPV3_POOL_INIT_CODE_HASH = '0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54'
|
|
const uniswapV3Addresses = {
|
|
31337: { // Mockchain
|
|
factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
|
|
},
|
|
1337: { // Dexorder Alpha
|
|
factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
|
|
},
|
|
421614: { // Arbitrum Sepolia
|
|
factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
|
|
},
|
|
42161: { // Arbitrum
|
|
factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
|
|
},
|
|
}
|
|
|
|
export function uniswapV3PoolAddress(chainId, tokenAddrA, tokenAddrB, fee) {
|
|
const [addr0, addr1] = tokenAddrA < tokenAddrB ? [tokenAddrA, tokenAddrB] : [tokenAddrB, tokenAddrA]
|
|
const encoded = ethers.AbiCoder.defaultAbiCoder().encode(['address', 'address', 'uint24'], [addr0, addr1, fee]);
|
|
const salt = ethers.keccak256(encoded)
|
|
const factory = uniswapV3Addresses[chainId]?.factory
|
|
if (!factory) {
|
|
console.log('no uniswap factory for chain', chainId)
|
|
return null
|
|
}
|
|
return ethers.getCreate2Address(factory, salt, UNISWAPV3_POOL_INIT_CODE_HASH)
|
|
}
|
|
|
|
|
|
export function uniswapV3AveragePrice(amountIn, amountOut, fee) {
|
|
if (amountIn === 0n || amountOut === 0n) return null
|
|
const fmtX18 = {decimals: 18, width: 512, signed: false};
|
|
let result = FixedNumber.fromValue(amountOut, 0, fmtX18)
|
|
.div(FixedNumber.fromValue(amountIn, 0, fmtX18)).toUnsafeFloat()
|
|
result /= (1 - fee / 1_000_000) // adjust for pool fee
|
|
return result
|
|
} |