|
| 1 | +/* eslint-disable functional/functional-parameters */ |
| 2 | +import { whenDefinedAll } from '@devprotocol/util-ts' |
| 3 | +import { |
| 4 | + TransactionResponse, |
| 5 | + TransactionReceipt, |
| 6 | +} from '@ethersproject/abstract-provider' |
| 7 | +import { Provider } from '@ethersproject/abstract-provider' |
| 8 | +import { BigNumber } from 'ethers' |
| 9 | +import { FallbackableOverrides } from '../../common/utils/execute' |
| 10 | +import { devClients } from './clients/devClients' |
| 11 | + |
| 12 | +type ApproveIfNeeded = (factoryOptions: { |
| 13 | + readonly provider: Provider |
| 14 | + readonly requiredAmount: string |
| 15 | + readonly from: string |
| 16 | + readonly to?: string |
| 17 | + readonly callback: ( |
| 18 | + receipt?: TransactionReceipt |
| 19 | + ) => Promise<TransactionResponse> |
| 20 | +}) => (options: { |
| 21 | + readonly amount?: string |
| 22 | + readonly overrides?: FallbackableOverrides |
| 23 | +}) => Promise<{ |
| 24 | + readonly waitOrSkip: () => Promise<TransactionResponse> |
| 25 | +}> |
| 26 | + |
| 27 | +export const approveIfNeeded: ApproveIfNeeded = |
| 28 | + (factoryOptions) => async (options) => { |
| 29 | + const [l1, l2] = await devClients(factoryOptions.provider) |
| 30 | + const client = l1 ?? l2 |
| 31 | + const allowance = await whenDefinedAll( |
| 32 | + [client, factoryOptions.to], |
| 33 | + ([x, to]) => x.allowance(factoryOptions.from, to) |
| 34 | + ) |
| 35 | + const callback = { |
| 36 | + waitOrSkip: () => factoryOptions.callback(), |
| 37 | + } as const |
| 38 | + |
| 39 | + return ( |
| 40 | + whenDefinedAll([client, factoryOptions.to], async ([dev, to]) => { |
| 41 | + return BigNumber.from(allowance).lt(factoryOptions.requiredAmount) |
| 42 | + ? ((approve) => |
| 43 | + ({ |
| 44 | + ...approve, |
| 45 | + waitOrSkip: async () => { |
| 46 | + const repeipt = await approve.wait() |
| 47 | + return factoryOptions.callback(repeipt) |
| 48 | + }, |
| 49 | + } as const))( |
| 50 | + await dev.approve( |
| 51 | + to, |
| 52 | + options.amount ?? factoryOptions.requiredAmount, |
| 53 | + options.overrides |
| 54 | + ) |
| 55 | + ) |
| 56 | + : callback |
| 57 | + }) ?? callback |
| 58 | + ) |
| 59 | + } |
0 commit comments