import {ethers} from "ethers";

const UNISWAPV3_POOL_INIT_CODE_HASH = '0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54'
const uniswapV3Addresses = {
    1337: {
        factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
    },
    42161: {
        factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
    },
    31337: {
        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)
}