|
| 1 | +import { Abi } from 'abitype' |
| 2 | + |
| 3 | +import type { Chain, Formatter } from '../../chains' |
| 4 | +import type { PublicClient } from '../../clients' |
| 5 | +import type { |
| 6 | + Address, |
| 7 | + ExtractArgsFromAbi, |
| 8 | + ExtractResultFromAbi, |
| 9 | + ExtractFunctionNameFromAbi, |
| 10 | + GetValue, |
| 11 | +} from '../../types' |
| 12 | +import { |
| 13 | + EncodeFunctionDataArgs, |
| 14 | + decodeFunctionResult, |
| 15 | + encodeFunctionData, |
| 16 | + getContractError, |
| 17 | +} from '../../utils' |
| 18 | +import { call, CallArgs, FormattedCall } from './call' |
| 19 | + |
| 20 | +export type FormattedCallContract< |
| 21 | + TFormatter extends Formatter | undefined = Formatter, |
| 22 | +> = FormattedCall<TFormatter> |
| 23 | + |
| 24 | +export type CallContractArgs< |
| 25 | + TChain extends Chain = Chain, |
| 26 | + TAbi extends Abi | readonly unknown[] = Abi, |
| 27 | + TFunctionName extends string = any, |
| 28 | +> = Omit<CallArgs<TChain>, 'from' | 'to' | 'data' | 'value'> & { |
| 29 | + address: Address |
| 30 | + abi: TAbi |
| 31 | + from?: Address |
| 32 | + functionName: ExtractFunctionNameFromAbi<TAbi, TFunctionName> |
| 33 | + value?: GetValue<TAbi, TFunctionName, CallArgs<TChain>['value']> |
| 34 | +} & ExtractArgsFromAbi<TAbi, TFunctionName> |
| 35 | + |
| 36 | +export type CallContractResponse< |
| 37 | + TAbi extends Abi | readonly unknown[] = Abi, |
| 38 | + TFunctionName extends string = string, |
| 39 | +> = ExtractResultFromAbi<TAbi, TFunctionName> |
| 40 | + |
| 41 | +export async function callContract< |
| 42 | + TChain extends Chain, |
| 43 | + TAbi extends Abi = Abi, |
| 44 | + TFunctionName extends string = any, |
| 45 | +>( |
| 46 | + client: PublicClient, |
| 47 | + { |
| 48 | + abi, |
| 49 | + address, |
| 50 | + args, |
| 51 | + functionName, |
| 52 | + ...callRequest |
| 53 | + }: CallContractArgs<TChain, TAbi, TFunctionName>, |
| 54 | +): Promise<CallContractResponse<TAbi, TFunctionName>> { |
| 55 | + const calldata = encodeFunctionData({ |
| 56 | + abi, |
| 57 | + args, |
| 58 | + functionName, |
| 59 | + } as unknown as EncodeFunctionDataArgs<TAbi, TFunctionName>) |
| 60 | + try { |
| 61 | + const { data } = await call(client, { |
| 62 | + data: calldata, |
| 63 | + to: address, |
| 64 | + ...callRequest, |
| 65 | + } as unknown as CallArgs<TChain>) |
| 66 | + return decodeFunctionResult({ |
| 67 | + abi, |
| 68 | + functionName, |
| 69 | + data: data || '0x', |
| 70 | + }) as CallContractResponse<TAbi, TFunctionName> |
| 71 | + } catch (err) { |
| 72 | + throw getContractError(err, { |
| 73 | + abi, |
| 74 | + address, |
| 75 | + args, |
| 76 | + functionName, |
| 77 | + sender: callRequest.from, |
| 78 | + }) |
| 79 | + } |
| 80 | +} |
0 commit comments