|
| 1 | +import { Interface } from '@ethersproject/abi' |
| 2 | +import invariant from 'tiny-invariant' |
| 3 | +import { abi } from '@uniswap/swap-router-contracts/artifacts/contracts/interfaces/IApproveAndCall.sol/IApproveAndCall.json' |
| 4 | +import { Currency, Token } from '@uniswap/sdk-core' |
| 5 | +import { NonfungiblePositionManager } from '@uniswap/v3-sdk' |
| 6 | + |
| 7 | +export enum ApprovalTypes { |
| 8 | + NOT_REQUIRED = 0, |
| 9 | + MAX = 1, |
| 10 | + MAX_MINUS_ONE = 2, |
| 11 | + ZERO_THEN_MAX = 3, |
| 12 | + ZERO_THEN_MAX_MINUS_ONE = 4, |
| 13 | +} |
| 14 | + |
| 15 | +export abstract class ApproveAndCall { |
| 16 | + public static INTERFACE: Interface = new Interface(abi) |
| 17 | + |
| 18 | + /** |
| 19 | + * Cannot be constructed. |
| 20 | + */ |
| 21 | + private constructor() {} |
| 22 | + |
| 23 | + public static encodeApproveMax(token: Token): string { |
| 24 | + return ApproveAndCall.INTERFACE.encodeFunctionData('approveMax', [token.address]) |
| 25 | + } |
| 26 | + |
| 27 | + public static encodeApproveMaxMinusOne(token: Token): string { |
| 28 | + return ApproveAndCall.INTERFACE.encodeFunctionData('approveMaxMinusOne', [token.address]) |
| 29 | + } |
| 30 | + |
| 31 | + public static encodeApproveZeroThenMax(token: Token): string { |
| 32 | + return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMax', [token.address]) |
| 33 | + } |
| 34 | + |
| 35 | + public static encodeApproveZeroThenMaxMinusOne(token: Token): string { |
| 36 | + return ApproveAndCall.INTERFACE.encodeFunctionData('approveZeroThenMaxMinusOne', [token.address]) |
| 37 | + } |
| 38 | + |
| 39 | + public static encodeCallPositionManager(calldatas: string[]): string { |
| 40 | + invariant(calldatas.length > 0, 'NULL_CALLDATA') |
| 41 | + |
| 42 | + if (calldatas.length == 1) { |
| 43 | + return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', calldatas) |
| 44 | + } else { |
| 45 | + const encodedMulticall = NonfungiblePositionManager.INTERFACE.encodeFunctionData('multicall', [calldatas]) |
| 46 | + return ApproveAndCall.INTERFACE.encodeFunctionData('callPositionManager', [encodedMulticall]) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + public static encodeApprove(token: Currency, approvalType: ApprovalTypes): string { |
| 51 | + switch (approvalType) { |
| 52 | + case ApprovalTypes.MAX: |
| 53 | + return ApproveAndCall.encodeApproveMax(token.wrapped) |
| 54 | + case ApprovalTypes.MAX_MINUS_ONE: |
| 55 | + return ApproveAndCall.encodeApproveMaxMinusOne(token.wrapped) |
| 56 | + case ApprovalTypes.ZERO_THEN_MAX: |
| 57 | + return ApproveAndCall.encodeApproveZeroThenMax(token.wrapped) |
| 58 | + case ApprovalTypes.ZERO_THEN_MAX_MINUS_ONE: |
| 59 | + return ApproveAndCall.encodeApproveZeroThenMaxMinusOne(token.wrapped) |
| 60 | + default: |
| 61 | + throw 'Error: invalid ApprovalType' |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments