Skip to content

Feat/erc20 paymaster actions #276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,14 @@ export const pmGetPaymasterStubDataParamsSchema = z
return [val[0], val[1], val[2], val[3] ?? null] as const
})

export const pimlicoGetTokenQuotesSchema = z.tuple([
z.object({
tokens: z.array(addressSchema)
}),
addressSchema, // entryPoint
hexNumberSchema
])

export type UserOperationV7 = zodInfer<typeof userOperationSchemaPaymasterV7>
export type UserOperationV6 = zodInfer<typeof userOperationSchemaPaymasterV6>
export type JsonRpcSchema = zodInfer<typeof jsonRpcSchema>
46 changes: 43 additions & 3 deletions packages/permissionless-test/mock-aa-infra/mock-paymaster/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import util from "node:util"
import type { FastifyReply, FastifyRequest } from "fastify"
import {
type Account,
type Address,
BaseError,
type Chain,
type Client,
Expand All @@ -13,12 +14,12 @@ import {
type WalletClient,
concat,
encodeAbiParameters,
getAddress,
toHex
} from "viem"
import {
type BundlerClient,
type UserOperation,
entryPoint06Abi,
entryPoint06Address,
entryPoint07Address
} from "viem/account-abstraction"
Expand All @@ -35,6 +36,7 @@ import {
RpcError,
ValidationErrors,
jsonRpcSchema,
pimlicoGetTokenQuotesSchema,
pmGetPaymasterData,
pmGetPaymasterStubDataParamsSchema,
pmSponsorUserOperationParamsSchema
Expand Down Expand Up @@ -260,7 +262,7 @@ const handleMethod = async (
verifyingPaymasterV06: GetContractReturnType<
typeof VERIFYING_PAYMASTER_V06_ABI
>,
publicClient: PublicClient,
publicClient: PublicClient<Transport, Chain>,
walletClient: WalletClient<Transport, Chain, Account>,
parsedBody: JsonRpcSchema
) => {
Expand Down Expand Up @@ -405,6 +407,44 @@ const handleMethod = async (
]
}

if (parsedBody.method === "pimlico_getTokenQuotes") {
const params = pimlicoGetTokenQuotesSchema.safeParse(parsedBody.params)

if (!params.success) {
throw new RpcError(
fromZodError(params.error).message,
ValidationErrors.InvalidFields
)
}

const [context, entryPoint] = params.data
const { tokens } = context

const quotes = {
[getAddress("0xffffffffffffffffffffffffffffffffffffffff")]: {
exchangeRate: "0x5cc717fbb3450c0000",
postOpGas: "0xc350"
}
}

let paymaster: Address
if (entryPoint === entryPoint07Address) {
paymaster = verifyingPaymasterV07.address
} else {
paymaster = verifyingPaymasterV06.address
}

return {
quotes: tokens
.filter((t) => quotes[t]) // Filter out unrecongized tokens
.map((token) => ({
...quotes[token],
paymaster,
token
}))
}
}

throw new RpcError(
`Attempted to call an unknown method ${parsedBody.method}`,
ValidationErrors.InvalidFields
Expand All @@ -419,7 +459,7 @@ export const createRpcHandler = (
verifyingPaymasterV06: GetContractReturnType<
typeof VERIFYING_PAYMASTER_V06_ABI
>,
publicClient: PublicClient,
publicClient: PublicClient<Transport, Chain>,
walletClient: WalletClient<Transport, Chain, Account>
) => {
return async (request: FastifyRequest, _reply: FastifyReply) => {
Expand Down
7 changes: 1 addition & 6 deletions packages/permissionless-test/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,7 @@ export const getPimlicoClient = <entryPointVersion extends "0.6" | "0.7">({
entryPointVersion: entryPointVersion
altoRpc: string
}) =>
createPimlicoClient<
entryPointVersion extends "0.6"
? typeof entryPoint06Address
: typeof entryPoint07Address,
entryPointVersion
>({
createPimlicoClient({
chain: foundry,
entryPoint: {
address: (entryPointVersion === "0.6"
Expand Down
12 changes: 10 additions & 2 deletions packages/permissionless/actions/pimlico.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
type GetTokenQuotesParameters,
type GetTokenQuotesReturnType,
getTokenQuotes
} from "./pimlico/getTokenQuotes"
import {
type GetUserOperationGasPriceReturnType,
getUserOperationGasPrice
Expand Down Expand Up @@ -35,7 +40,9 @@ export type {
SendCompressedUserOperationParameters,
SponsorUserOperationReturnType,
ValidateSponsorshipPolicies,
ValidateSponsorshipPoliciesParameters
ValidateSponsorshipPoliciesParameters,
GetTokenQuotesParameters,
GetTokenQuotesReturnType
}

export {
Expand All @@ -44,5 +51,6 @@ export {
pimlicoActions,
sendCompressedUserOperation,
sponsorUserOperation,
validateSponsorshipPolicies
validateSponsorshipPolicies,
getTokenQuotes
}
36 changes: 36 additions & 0 deletions packages/permissionless/actions/pimlico/getTokenQuotes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { getAddress, isAddress } from "viem"
import { entryPoint07Address } from "viem/account-abstraction"
import { foundry } from "viem/chains"
import { describe, expect } from "vitest"
import { testWithRpc } from "../../../permissionless-test/src/testWithRpc"
import { getPimlicoClient } from "../../../permissionless-test/src/utils"
import { getTokenQuotes } from "./getTokenQuotes"

describe("getTokenQuotes", () => {
testWithRpc("getTokenQuotes", async ({ rpc }) => {
const pimlicoBundlerClient = getPimlicoClient({
entryPointVersion: "0.7",
altoRpc: rpc.paymasterRpc
})

const token = getAddress("0xffffffffffffffffffffffffffffffffffffffff")

const quotes = await getTokenQuotes(pimlicoBundlerClient, {
tokens: [token],
entryPointAddress: entryPoint07Address,
chain: foundry
})

expect(quotes).toBeTruthy()
expect(Array.isArray(quotes)).toBe(true)
expect(quotes[0].token).toBeTruthy()
expect(isAddress(quotes[0].token))
expect(quotes[0].token).toEqual(token)
expect(quotes[0].paymaster).toBeTruthy()
expect(isAddress(quotes[0].paymaster))
expect(quotes[0].exchangeRate).toBeTruthy()
expect(quotes[0].exchangeRate).toBeGreaterThan(0n)
expect(quotes[0].postOpGas).toBeTruthy()
expect(quotes[0].postOpGas).toBeGreaterThan(0n)
})
})
67 changes: 67 additions & 0 deletions packages/permissionless/actions/pimlico/getTokenQuotes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {
type Account,
type Address,
type Chain,
ChainNotFoundError,
type Client,
type GetChainParameter,
type Transport,
hexToBigInt,
numberToHex
} from "viem"
import type { PimlicoRpcSchema } from "../../types/pimlico"

export type GetTokenQuotesParameters<
TChain extends Chain | undefined,
TChainOverride extends Chain | undefined = Chain | undefined
> = {
tokens: Address[]
entryPointAddress: Address
} & GetChainParameter<TChain, TChainOverride>

export type GetTokenQuotesReturnType = {
paymaster: Address
token: Address
postOpGas: bigint
exchangeRate: bigint
}[]

/**
* Returns all related fields to calculate the potential cost of a userOperation in ERC-20 tokens.
*
* - Docs: https://docs.pimlico.io/permissionless/reference/pimlico-bundler-actions/getTokenQuotes
*
* @param client that you created using viem's createClient whose transport url is pointing to the Pimlico's bundler.
* @returns slow, standard & fast values for maxFeePerGas & maxPriorityFeePerGas
* @returns quotes, see {@link GetTokenQuotesReturnType}
*
*/
export const getTokenQuotes = async <
TChain extends Chain | undefined,
TTransport extends Transport = Transport,
TChainOverride extends Chain | undefined = Chain | undefined
>(
client: Client<TTransport, TChain, Account | undefined, PimlicoRpcSchema>,
args: GetTokenQuotesParameters<TChain, TChainOverride>
): Promise<GetTokenQuotesReturnType> => {
const chainId = args.chain?.id ?? client.chain?.id

if (!chainId) {
throw new ChainNotFoundError()
}

const res = await client.request({
method: "pimlico_getTokenQuotes",
params: [
{ tokens: args.tokens },
args.entryPointAddress,
numberToHex(chainId)
]
})

return res.quotes.map((quote) => ({
...quote,
postOpGas: hexToBigInt(quote.postOpGas),
exchangeRate: hexToBigInt(quote.exchangeRate)
}))
}
29 changes: 27 additions & 2 deletions packages/permissionless/clients/decorators/pimlico.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import type { Address, Client, Hash, Prettify } from "viem"
import type { Address, Chain, Client, Hash, Prettify, Transport } from "viem"
import {
type GetTokenQuotesParameters,
type GetTokenQuotesReturnType,
type SendCompressedUserOperationParameters,
type ValidateSponsorshipPolicies,
type ValidateSponsorshipPoliciesParameters,
getTokenQuotes,
sendCompressedUserOperation,
validateSponsorshipPolicies
} from "../../actions/pimlico"
Expand All @@ -22,6 +25,7 @@ import {
} from "../../actions/pimlico/sponsorUserOperation"

export type PimlicoActions<
TChain extends Chain | undefined,
entryPointVersion extends "0.6" | "0.7" = "0.6" | "0.7"
> = {
/**
Expand Down Expand Up @@ -111,6 +115,16 @@ export type PimlicoActions<
Omit<ValidateSponsorshipPoliciesParameters, "entryPoint">
>
) => Promise<Prettify<ValidateSponsorshipPolicies>[]>
getTokenQuotes: <
TChainOverride extends Chain | undefined = Chain | undefined
>(
args: Prettify<
Omit<
GetTokenQuotesParameters<TChain, TChainOverride>,
"entryPointAddress"
>
>
) => Promise<Prettify<GetTokenQuotesReturnType>>
}

export const pimlicoActions =
Expand All @@ -119,7 +133,12 @@ export const pimlicoActions =
}: {
entryPoint: { address: Address; version: entryPointVersion }
}) =>
(client: Client): PimlicoActions<entryPointVersion> => ({
<
TTransport extends Transport,
TChain extends Chain | undefined = Chain | undefined
>(
client: Client<TTransport, TChain>
): PimlicoActions<TChain, entryPointVersion> => ({
getUserOperationGasPrice: async () => getUserOperationGasPrice(client),
getUserOperationStatus: async (
args: GetUserOperationStatusParameters
Expand All @@ -140,5 +159,11 @@ export const pimlicoActions =
validateSponsorshipPolicies(client, {
...args,
entryPointAddress: entryPoint.address
}),
getTokenQuotes: async (args) =>
getTokenQuotes(client, {
...args,
chain: args.chain,
entryPointAddress: entryPoint.address
})
})
2 changes: 1 addition & 1 deletion packages/permissionless/clients/pimlico.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export type PimlicoClient<
: [...BundlerRpcSchema, ...PimlicoRpcSchema],
BundlerActions<account> &
PaymasterActions &
PimlicoActions<entryPointVersion>
PimlicoActions<chain, entryPointVersion>
>
>

Expand Down
14 changes: 14 additions & 0 deletions packages/permissionless/types/pimlico.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ export type PimlicoUserOperationStatus = {
transactionHash: Hash | null
}

type GetTokenQuotesWithBigIntAsHex = {
quotes: {
paymaster: Address
token: Address
postOpGas: Hex
exchangeRate: Hex
}[]
}

export type PimlicoRpcSchema<
entryPointVersion extends "0.6" | "0.7" = "0.6" | "0.7"
> = [
Expand Down Expand Up @@ -116,5 +125,10 @@ export type PimlicoRpcSchema<
description: string | null
}
}[]
},
{
Method: "pimlico_getTokenQuotes"
Parameters: [{ tokens: Address[] }, entryPoint: Address, chainId: Hex]
ReturnType: GetTokenQuotesWithBigIntAsHex
}
]
Loading