|
| 1 | +/* eslint-disable functional/functional-parameters */ |
| 2 | +import { UndefinedOr, 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 | +export const approveIfNeeded = |
| 13 | + (factoryOptions: { |
| 14 | + readonly provider: Provider |
| 15 | + readonly requiredAmount: string |
| 16 | + readonly from: string |
| 17 | + readonly to?: string |
| 18 | + readonly callback: ( |
| 19 | + receipt?: TransactionReceipt |
| 20 | + ) => UndefinedOr<Promise<TransactionResponse>> |
| 21 | + }) => |
| 22 | + async (options: { |
| 23 | + readonly amount?: string |
| 24 | + readonly overrides?: FallbackableOverrides |
| 25 | + }) => { |
| 26 | + const [l1, l2] = await devClients(factoryOptions.provider) |
| 27 | + const client = l1 ?? l2 |
| 28 | + const allowance = await whenDefinedAll( |
| 29 | + [client, factoryOptions.to], |
| 30 | + ([x, to]) => x.allowance(factoryOptions.from, to) |
| 31 | + ) |
| 32 | + const callback = { |
| 33 | + wait: () => factoryOptions.callback(), |
| 34 | + } |
| 35 | + |
| 36 | + return ( |
| 37 | + whenDefinedAll([client, factoryOptions.to], async ([dev, to]) => { |
| 38 | + return BigNumber.from(allowance).lt(factoryOptions.requiredAmount) |
| 39 | + ? ((approve) => ({ |
| 40 | + ...approve, |
| 41 | + wait: async () => { |
| 42 | + const repeipt = await approve.wait() |
| 43 | + return factoryOptions.callback(repeipt) |
| 44 | + }, |
| 45 | + }))( |
| 46 | + await dev.approve( |
| 47 | + to, |
| 48 | + options.amount ?? factoryOptions.requiredAmount, |
| 49 | + options.overrides |
| 50 | + ) |
| 51 | + ) |
| 52 | + : callback |
| 53 | + }) ?? callback |
| 54 | + ) |
| 55 | + } |
0 commit comments