import Web3 from "web3" import BigNumber from "bignumber.js" import { IUniswapV2Pair, newIUniswapV2Pair } from "../../types/web3-v1-contracts/IUniswapV2Pair" import { Address } from "../pair" import { address as pairUniswapV2Address } from "../../tools/deployed/mainnet.PairUniswapV2.addr.json" import { selectAddress } from "../utils" import { PairXYeqK } from "./pair-xyeqk" export class PairUniswapV2 extends PairXYeqK { allowRepeats = false private pair: IUniswapV2Pair private feeKData: string constructor( chainId: number, web3: Web3, private pairAddr: Address, private fixedFee: BigNumber = new BigNumber(0.997), private initData?: {tokenA: Address, tokenB: Address}, ) { super(web3, selectAddress(chainId, { mainnet: pairUniswapV2Address })) this.pair = newIUniswapV2Pair(web3, pairAddr) const feeKInv = new BigNumber(10000).minus(this.fixedFee.multipliedBy(10000)) if (!feeKInv.isInteger() || !feeKInv.gt(0) || !feeKInv.lt(256)) { // feeKInv must fit into uint8 throw new Error(`Invalid fixedFee: ${this.fixedFee}!`) } this.feeKData = feeKInv.toString(16).padStart(2, "0") } protected async _init() { if (this.initData) { return { pairKey: this.pairAddr, tokenA: this.initData.tokenA, tokenB: this.initData.tokenB, } } const [tokenA, tokenB] = await Promise.all([ this.pair.methods.token0().call(), this.pair.methods.token1().call(), ]) return { pairKey: this.pairAddr, tokenA, tokenB, } } public async refresh(): Promise { if (!this.pair) { throw new Error(`not initialized!`) } const reserves = await this.pair.methods.getReserves().call() this.refreshBuckets(this.fixedFee, new BigNumber(reserves[0]), new BigNumber(reserves[1])) } protected swapExtraData() { return `${this.pair!.options.address}${this.feeKData}` } }