|
| 1 | +import type { BaseError, Chain, Client, Transport } from 'viem'; |
| 2 | +import { |
| 3 | + formatUserOperationReceipt, |
| 4 | + formatUserOperationRequest, |
| 5 | + getUserOperationError, |
| 6 | + type PrepareUserOperationParameters, |
| 7 | + type SendUserOperationParameters, |
| 8 | + type SmartAccount, |
| 9 | + type UserOperation, |
| 10 | + type UserOperationReceipt |
| 11 | +} from 'viem/account-abstraction'; |
| 12 | +import { parseAccount } from 'viem/accounts'; |
| 13 | +import type { CapabilitiesByChain } from '../../relayer/evm/actions/index.js'; |
| 14 | +import { AccountNotFoundError, type Payment } from '../../types/index.js'; |
| 15 | +import { prepareUserOperation } from './prepareUserOperation.js'; |
| 16 | + |
| 17 | +export type SendUserOperationSyncParameters = SendUserOperationParameters & { |
| 18 | + timeout: number; |
| 19 | +}; |
| 20 | + |
| 21 | +export const sendUserOperationSync = async <account extends SmartAccount | undefined>( |
| 22 | + client: Client<Transport, Chain | undefined, account>, |
| 23 | + parameters: SendUserOperationSyncParameters, |
| 24 | + capabilities: CapabilitiesByChain, |
| 25 | + payment?: Payment |
| 26 | +): Promise<UserOperationReceipt> => { |
| 27 | + const { account: account_ = client.account, entryPointAddress, timeout } = parameters; |
| 28 | + |
| 29 | + if (!account_ && !parameters.sender) throw new AccountNotFoundError(); |
| 30 | + const account = account_ ? parseAccount(account_) : undefined; |
| 31 | + |
| 32 | + const request = account |
| 33 | + ? await prepareUserOperation( |
| 34 | + client, |
| 35 | + parameters as unknown as PrepareUserOperationParameters, |
| 36 | + capabilities, |
| 37 | + payment, |
| 38 | + true |
| 39 | + ) |
| 40 | + : parameters; |
| 41 | + |
| 42 | + // biome-ignore lint/style/noNonNullAssertion: copied from viem |
| 43 | + const signature = (parameters.signature || |
| 44 | + (await account?.signUserOperation?.(request as UserOperation)))!; |
| 45 | + |
| 46 | + const rpcParameters = formatUserOperationRequest({ |
| 47 | + ...request, |
| 48 | + signature |
| 49 | + } as UserOperation); |
| 50 | + |
| 51 | + try { |
| 52 | + const receipt = await client.request( |
| 53 | + { |
| 54 | + method: 'eth_sendUserOperationSync', |
| 55 | + // biome-ignore lint/style/noNonNullAssertion: copied from viem |
| 56 | + params: [rpcParameters, (entryPointAddress ?? account?.entryPoint?.address)!, { timeout }] |
| 57 | + } as never, |
| 58 | + { retryCount: 0 } |
| 59 | + ); |
| 60 | + |
| 61 | + return formatUserOperationReceipt(receipt); |
| 62 | + } catch (error) { |
| 63 | + // biome-ignore lint/suspicious/noExplicitAny: copied from viem |
| 64 | + const calls = (parameters as any).calls; |
| 65 | + throw getUserOperationError(error as BaseError, { |
| 66 | + ...(request as UserOperation), |
| 67 | + ...(calls ? { calls } : {}), |
| 68 | + signature |
| 69 | + }); |
| 70 | + } |
| 71 | +}; |
0 commit comments