repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -0,0 +1,42 @@
+import { Hex, concat, toHex } from "viem"
+import { Address, UserOperation } from "./schemas"
+
+// Type that knows how to encode/decode itself
+export class CompressedUserOp {
+ compressedCalldata: Hex
+ inflatedUserOp: UserOperation
+ inflatorAddr: Address
+ bundleBulkerAddr: Address
+ entryPointAddr: Address
+ inflatorId: number // id of targetInflator in PerOpInflator
+ perOpInflatorId: number // id of PerOpInflator in BundleBulker
+
+ // ideally this type should derive id's / addresses by itself instead of taking them in as inputs
+ constructor(
+ compressedCalldata : Hex,
+ inflatedUserOp: UserOperation,
+ bundleBulkerAddr: Address,
+ entryPointAddr: Address,
+ inflatorAddr: Address,
+ inflatorId: number,
+ perOpInflatorId: number
+ ) {
+ this.compressedCalldata = compressedCalldata
+ this.inflatedUserOp = inflatedUserOp
+ this.bundleBulkerAddr = bundleBulkerAddr
+ this.entryPointAddr = entryPointAddr
+ this.inflatorAddr = inflatorAddr
+ this.inflatorId = inflatorId
+ this.perOpInflatorId = perOpInflatorId
+ }
+
+ // generates calldata that wraps compressedCalldata for forwarding to BundleBulker
+ public bundleBulkerCalldata(): Hex { | yeah should these two functions really live here inside this class? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -10,6 +10,34 @@ export interface ReferencedCodeHashes {
hash: string
}
+export interface MempoolUserOp {
+ getUserOperation(): UserOperation
+}
+
+export class NormalMempoolUserOp implements MempoolUserOp { | should it be called `Normal`? it kinda makes it seem like the other one is not Normal, no? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -3,70 +3,47 @@ import {
} from "@alto/types"
import { Client, getContract } from "viem"
-type PerOpInflator = {
- address: Address,
- bundleBulkerIdRegistry: Record<Address, number> // id of this PerOpInflator in each BundleBulkers
-}
-
export class CompressionHandler {
- whiteListedInflators: Address[]
- entryPointToBundleBulker: Record<Address, Address>
- perOpInflator: PerOpInflator | null
+ perOpInflatorAddress: Address
+ perOpInflatorId: number
+ bundleBulkerAddress: Address
private constructor() {
- this.whiteListedInflators = []
- this.entryPointToBundleBulker = {}
- this.perOpInflator = null
+ this.perOpInflatorAddress = "0x00" | can we do without setting these values as defaults? seems like an antipattern |
alto | github_2023 | others | 78 | pimlicolabs | kristofgazso | @@ -27,6 +27,7 @@
"@alto/types": "*",
"@alto/utils": "*",
"@alto/mempool": "*",
+ "@alto/rpc": "*", | this would create a circular dependency, no?
can we do without importing @alto/rpc here? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -10,20 +10,29 @@ export interface ReferencedCodeHashes {
hash: string
}
+export const deriveUserOperation = (op: MempoolUserOperation): UserOperation => {
+ return isCompressedType(op) ? (op as CompressedUserOperation).inflatedOp : (op as UserOperation)
+}
+
+export const isCompressedType = (op: MempoolUserOperation): boolean => {
+ return "compressedCalldata" in op
+}
+
+export type MempoolUserOperation = UserOperation | CompressedUserOperation
+
export type TransactionInfo = {
+ transactionType: "default" | "compressed"
transactionHash: HexData32
previousTransactionHashes: HexData32[]
- transactionRequest: WriteContractParameters<
- Abi | readonly unknown[],
- string,
- Chain,
- Account,
- Chain
- > & {
+ transactionRequest: { | why can't we use the WriteContractParameters type as before? that way we inherit all of viem's good typing |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -46,7 +46,7 @@ import {
import { debug_traceCall } from "./tracer"
import { tracerResultParser } from "./TracerResultParser"
import { IValidator } from "@alto/types"
-import { SenderManager } from "@alto/executor"
+import { SenderManager } from "../../../executor/src" | @alto/executor |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -910,4 +816,175 @@ export class RpcHandler implements IRpcEndpoint {
}
}
}
+
+ // check if we want to bundle userOperation. If yes, add to mempool
+ async addToMempoolIfValid(op: MempoolUserOperation, entryPoint: Address) {
+ const userOperation = deriveUserOperation(op)
+ if (this.entryPoint !== entryPoint) {
+ throw new RpcError(
+ `EntryPoint ${entryPoint} not supported, supported EntryPoints: ${this.entryPoint}`
+ )
+ }
+
+ if (
+ this.chainId === chains.celoAlfajores.id ||
+ this.chainId === chains.celo.id
+ ) {
+ if (
+ userOperation.maxFeePerGas !==
+ userOperation.maxPriorityFeePerGas
+ ) {
+ throw new RpcError(
+ "maxPriorityFeePerGas must equal maxFeePerGas on Celo chains"
+ )
+ }
+ }
+
+ if (this.minimumGasPricePercent !== 0) {
+ const gasPrice = await getGasPrice(
+ this.chainId,
+ this.publicClient,
+ this.logger
+ )
+ const minMaxFeePerGas =
+ (gasPrice.maxFeePerGas * BigInt(this.minimumGasPricePercent)) /
+ 100n
+ if (userOperation.maxFeePerGas < minMaxFeePerGas) {
+ throw new RpcError(
+ `maxFeePerGas must be at least ${minMaxFeePerGas} (current maxFeePerGas: ${gasPrice.maxFeePerGas}) - use pimlico_getUserOperationGasPrice to get the current gas price`
+ )
+ }
+
+ if (userOperation.maxPriorityFeePerGas < minMaxFeePerGas) {
+ throw new RpcError(
+ `maxPriorityFeePerGas must be at least ${minMaxFeePerGas} (current maxPriorityFeePerGas: ${gasPrice.maxPriorityFeePerGas}) - use pimlico_getUserOperationGasPrice to get the current gas price`
+ )
+ }
+ }
+
+ if (userOperation.verificationGasLimit < 10000n) {
+ throw new RpcError("verificationGasLimit must be at least 10000")
+ }
+
+ this.logger.trace({ userOperation, entryPoint }, "beginning validation")
+ this.metrics.userOperationsReceived.inc()
+
+ if (
+ userOperation.preVerificationGas === 0n ||
+ userOperation.verificationGasLimit === 0n ||
+ userOperation.callGasLimit === 0n
+ ) {
+ throw new RpcError(
+ "user operation gas limits must be larger than 0"
+ )
+ }
+
+ const entryPointContract = getContract({
+ address: this.entryPoint,
+ abi: EntryPointAbi,
+ publicClient: this.publicClient
+ })
+
+ const [nonceKey, userOperationNonceValue] = getNonceKeyAndValue(
+ userOperation.nonce
+ )
+
+ const getNonceResult = await entryPointContract.read.getNonce(
+ [userOperation.sender, nonceKey],
+ {
+ blockTag: "latest"
+ }
+ )
+
+ const [_, currentNonceValue] = getNonceKeyAndValue(getNonceResult)
+
+ if (userOperationNonceValue < currentNonceValue) {
+ throw new RpcError(
+ "UserOperation reverted during simulation with reason: AA25 invalid account nonce",
+ ValidationErrors.SimulateValidation
+ )
+ }
+ if (userOperationNonceValue > currentNonceValue + 10n) {
+ throw new RpcError(
+ "UserOperation reverted during simulation with reason: AA25 invalid account nonce",
+ ValidationErrors.SimulateValidation
+ )
+ }
+ if (userOperationNonceValue === currentNonceValue) {
+ const validationResult =
+ await this.validator.validateUserOperation(userOperation)
+ await this.reputationManager.checkReputation(
+ userOperation,
+ validationResult
+ )
+ await this.mempool.checkEntityMultipleRoleViolation(userOperation)
+ const success = this.mempool.add(
+ userOperation, | this only adds the uncompressed version, no? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -62,6 +65,8 @@ import {
estimateVerificationGasLimit
} from "./gasEstimation"
import { NonceQueuer } from "./nonceQueuer"
+import { InflatorAbi } from "@alto/types/src/contracts/Inflator" | should just be importing from @alto/types |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -78,30 +106,43 @@ export async function filterOpsAndEstimateGas(
while (simulatedOps.filter((op) => op.reason === undefined).length > 0) {
try {
- gasLimit = await ep.estimateGas.handleOps(
- [
- simulatedOps
- .filter((op) => op.reason === undefined)
- .map((op) => op.op.userOperation),
- wallet.address
- ],
- onlyPre1559
- ? {
- account: wallet,
- gasPrice: maxFeePerGas,
- gas: customGasLimitForEstimation,
- nonce: nonce,
- blockTag
- }
- : {
- account: wallet,
- maxFeePerGas: maxFeePerGas,
- maxPriorityFeePerGas: maxPriorityFeePerGas,
- gas: customGasLimitForEstimation,
- nonce: nonce,
- blockTag
- }
- )
+ const gasOptions = onlyPre1559 ? { gasPrice: maxFeePerGas } : { maxFeePerGas, maxPriorityFeePerGas }
+
+ if (callContext.type === "default") {
+ const ep = (callContext as DefaultFilterOpsAndEstimateGasParams).ep | you shouldn't need to cast this... right? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -78,30 +106,43 @@ export async function filterOpsAndEstimateGas(
while (simulatedOps.filter((op) => op.reason === undefined).length > 0) {
try {
- gasLimit = await ep.estimateGas.handleOps(
- [
- simulatedOps
- .filter((op) => op.reason === undefined)
- .map((op) => op.op.userOperation),
- wallet.address
- ],
- onlyPre1559
- ? {
- account: wallet,
- gasPrice: maxFeePerGas,
- gas: customGasLimitForEstimation,
- nonce: nonce,
- blockTag
- }
- : {
- account: wallet,
- maxFeePerGas: maxFeePerGas,
- maxPriorityFeePerGas: maxPriorityFeePerGas,
- gas: customGasLimitForEstimation,
- nonce: nonce,
- blockTag
- }
- )
+ const gasOptions = onlyPre1559 ? { gasPrice: maxFeePerGas } : { maxFeePerGas, maxPriorityFeePerGas }
+
+ if (callContext.type === "default") {
+ const ep = (callContext as DefaultFilterOpsAndEstimateGasParams).ep
+ const opsToSend = simulatedOps
+ .filter((op) => op.reason === undefined)
+ .map((op) => (op.op.userOperation as UserOperation))
+
+ gasLimit = await ep.estimateGas.handleOps(
+ [
+ opsToSend,
+ wallet.address
+ ],
+ {
+ account: wallet,
+ gas: customGasLimitForEstimation,
+ nonce: nonce,
+ blockTag,
+ ...gasOptions
+ }
+ )
+ } else {
+ const { publicClient, bundleBulker, perOpInflatorId } = (callContext as CompressedFilterOpsAndEstimateGasParams) | shouldn't need to cast this either |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -17,6 +18,8 @@ import {
} from "viem"
import { Logger, Metrics, transactionIncluded } from "@alto/utils"
import { getGasPrice } from "@alto/utils"
+import { UserOperation, deriveUserOperation } from "@alto/types/src" | just @alto/types |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -32,88 +32,8 @@ import {
} from "@alto/utils"
import { MemoryStore } from "./store"
import { IReputationManager, ReputationStatuses } from "./reputationManager"
-
-export interface Mempool {
- add(op: UserOperation, referencedContracts?: ReferencedCodeHashes): boolean
- checkEntityMultipleRoleViolation(_op: UserOperation): Promise<void>
-
- /**
- * Takes an array of user operations from the mempool, also marking them as submitted.
- *
- * @param gasLimit The maximum gas limit of user operations to take.
- * @param minOps The minimum number of user operations to take.
- * @returns An array of user operations to submit.
- */
- process(gasLimit: bigint, minOps?: number): Promise<UserOperation[]>
-
- replaceSubmitted(
- userOperation: UserOperationInfo,
- transactionInfo: TransactionInfo
- ): void
-
- markSubmitted(userOpHash: HexData32, transactionInfo: TransactionInfo): void
-
- /**
- * Removes a user operation from the mempool.
- *
- * @param userOpHash The hash of the user operation to remove.
- */
- removeSubmitted(userOpHash: HexData32): void
- removeProcessing(userOpHash: HexData32): void
-
- /**
- * Gets all user operation from the mempool.
- *
- * @returns An array of user operations.
- */
- dumpSubmittedOps(): SubmittedUserOperation[]
-
- dumpOutstanding(): UserOperationInfo[]
-
- dumpProcessing(): UserOperationInfo[]
-
- clear(): void
-}
-
-export class NullMempool implements Mempool {
- clear(): void {
- throw new Error("Method not implemented.")
- }
- dumpOutstanding(): UserOperationInfo[] {
- throw new Error("Method not implemented.")
- }
- removeProcessing(_: `0x${string}`): void {
- throw new Error("Method not implemented.")
- }
- replaceSubmitted(_: UserOperationInfo, __: TransactionInfo): void {
- throw new Error("Method not implemented.")
- }
- markSubmitted(_: `0x${string}`, __: TransactionInfo): void {
- throw new Error("Method not implemented.")
- }
- dumpSubmittedOps(): SubmittedUserOperation[] {
- throw new Error("Method not implemented.")
- }
- dumpProcessing(): UserOperationInfo[] {
- throw new Error("Method not implemented.")
- }
- removeSubmitted(_: `0x${string}`): void {
- throw new Error("Method not implemented.")
- }
- add(
- _op: UserOperation,
- _referencedContracts?: ReferencedCodeHashes
- ): boolean {
- return false
- }
- async checkEntityMultipleRoleViolation(_op: UserOperation): Promise<void> {
- return
- }
-
- async process(_: bigint, __?: number): Promise<UserOperation[]> {
- return []
- }
-}
+import { Mempool } from "./types"
+import { MempoolUserOperation, deriveUserOperation } from "@alto/types/src" | just @alto/types |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -23,7 +25,7 @@ export interface IReputationManager {
userOperation: UserOperation,
accountDeployed: boolean
): void
- crashedHandleOps(userOperation: UserOperation, reason: string): void
+ crashedHandleOps(userOperation: MempoolUserOperation, reason: string): void | should this not stay `UserOperation`? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -549,6 +590,161 @@ export class BasicExecutor implements IExecutor {
this.metrics.bundlesSubmitted.inc()
+ return userOperationResults
+ }
+
+async bundleCompressed(entryPoint: Address, compressedOps: CompressedUserOperation[]): Promise<BundleResult[]> {
+ const wallet = await this.senderManager.getWallet()
+
+ const childLogger = this.logger.child({
+ compressedUserOperations: compressedOps,
+ entryPoint: this.entryPoint
+ })
+ childLogger.debug("bundling compressed user operation")
+
+ const gasPriceParameters = await getGasPrice(this.walletClient.chain.id, this.publicClient, this.logger)
+ childLogger.debug({ gasPriceParameters }, "got gas price")
+
+ const nonce = await this.publicClient.getTransactionCount({
+ address: wallet.address,
+ blockTag: "pending"
+ })
+ childLogger.trace({ nonce }, "got nonce")
+
+ let opsToBundle: UserOperationWithHash[] = []
+
+ const callContext: CompressedFilterOpsAndEstimateGasParams = {
+ publicClient: this.publicClient,
+ bundleBulker: this.compressionHandler.bundleBulkerAddress,
+ perOpInflatorId: this.compressionHandler.perOpInflatorId,
+ type: "compressed"
+ }
+
+ const { gasLimit, simulatedOps } = await filterOpsAndEstimateGas(
+ callContext,
+ wallet,
+ compressedOps.map((op) => {
+ return {
+ userOperation: op,
+ userOperationHash: getUserOperationHash(op.inflatedOp, entryPoint, this.walletClient.chain.id)
+ }
+ }),
+ nonce,
+ gasPriceParameters.maxFeePerGas,
+ gasPriceParameters.maxPriorityFeePerGas,
+ "pending",
+ this.noEip1559Support,
+ this.customGasLimitForEstimation,
+ this.reputationManager,
+ childLogger
+ )
+
+ if (simulatedOps.length === 0) {
+ childLogger.warn("no ops to bundle")
+ this.markWalletProcessed(wallet)
+ return compressedOps.map((op) => {
+ return {
+ success: false,
+ error: {
+ userOpHash: getUserOperationHash(op.inflatedOp, entryPoint, this.walletClient.chain.id),
+ reason: "INTERNAL FAILURE"
+ }
+ }
+ })
+ }
+
+ // if not all succeeded, return error
+ if (simulatedOps.some((op) => op.reason !== undefined)) {
+ childLogger.warn("some ops failed simulation")
+ this.markWalletProcessed(wallet)
+ return simulatedOps.map((op) => {
+ return {
+ success: false,
+ error: {
+ userOpHash: op.op.userOperationHash,
+ reason: op.reason as string
+ }
+ }
+ })
+ }
+
+ opsToBundle = simulatedOps.filter((op) => op.reason === undefined).map((op) => op.op)
+
+ let txHash: HexData32
+ try {
+ const gasOptions = this.noEip1559Support
+ ? {
+ gasPrice: gasPriceParameters.maxFeePerGas,
+ }
+ : {
+ maxFeePerGas: gasPriceParameters.maxFeePerGas,
+ maxPriorityFeePerGas: gasPriceParameters.maxPriorityFeePerGas,
+ };
+
+ // need to use sendTransction to target BundleBulker's fallback
+ txHash = await this.walletClient.sendTransaction({
+ account: wallet,
+ to: this.compressionHandler.bundleBulkerAddress,
+ data: createCompressedCalldata(compressedOps, this.compressionHandler.perOpInflatorId),
+ gas: gasLimit,
+ nonce: nonce,
+ ...gasOptions
+ })
+ } catch (err: unknown) {
+ sentry.captureException(err)
+ childLogger.error({ error: JSON.stringify(err) }, "error submitting bundle transaction")
+ this.markWalletProcessed(wallet)
+ return []
+ }
+
+ const userOperationInfos = opsToBundle.map((op) => {
+ this.metrics.userOperationsSubmitted.inc()
+
+ return {
+ mempoolUserOperation: op.userOperation,
+ userOperationHash: op.userOperationHash,
+ lastReplaced: Date.now(),
+ firstSubmitted: Date.now()
+ }
+ })
+
+ const bb = getContract({ | do we really need to create a contract instance here if we just need its address? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -463,22 +501,22 @@ export class BasicExecutor implements IExecutor {
let txHash: HexData32
try {
txHash = await ep.write.handleOps(
- [opsToBundle.map((op) => op.userOperation), wallet.address],
+ [opsToBundle.map((op) => (op.userOperation as UserOperation)), wallet.address], | why do we need to cast this? we shouldn't have to, right? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -255,16 +288,16 @@ export class BasicExecutor implements IExecutor {
"replacing transaction"
)
- const txHash = await this.walletClient.writeContract(
+ const txHash = await this.walletClient.sendTransaction( | why sendTransaction instead of writeContract? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -227,19 +250,29 @@ export class BasicExecutor implements IExecutor {
newRequest.gas = this.useUserOperationGasLimitsForSubmission
? opsToBundle.reduce(
- (acc, op) =>
- acc +
- op.userOperation.preVerificationGas +
- 3n * op.userOperation.verificationGasLimit +
- op.userOperation.callGasLimit,
- 0n
- ) * 1n
+ (acc, op) =>
+ acc +
+ deriveUserOperation(op.mempoolUserOperation).preVerificationGas + | why not derivate just once right above this instead of 3 times? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -227,19 +250,29 @@ export class BasicExecutor implements IExecutor {
newRequest.gas = this.useUserOperationGasLimitsForSubmission
? opsToBundle.reduce(
- (acc, op) =>
- acc +
- op.userOperation.preVerificationGas +
- 3n * op.userOperation.verificationGasLimit +
- op.userOperation.callGasLimit,
- 0n
- ) * 1n
+ (acc, op) =>
+ acc +
+ deriveUserOperation(op.mempoolUserOperation).preVerificationGas +
+ 3n * deriveUserOperation(op.mempoolUserOperation).verificationGasLimit +
+ deriveUserOperation(op.mempoolUserOperation).callGasLimit,
+ 0n
+ ) * 1n
: result.gasLimit
- newRequest.args = [
- opsToBundle.map((owh) => owh.userOperation),
- transactionInfo.executor.address
- ]
+ // update calldata to include only ops that pass simulation
+ if (transactionInfo.transactionType === "default") {
+ newRequest.calldata = encodeFunctionData({ | the calldata doesn't change, why re-encode it? can't we reuse it? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -24,16 +27,21 @@ import {
PublicClient,
Transport,
WalletClient,
- getContract
+ encodeFunctionData,
+ getContract,
} from "viem"
import { SenderManager } from "./senderManager"
import { IReputationManager } from "@alto/mempool"
import {
+ CompressedFilterOpsAndEstimateGasParams,
+ createCompressedCalldata,
+ DefaultFilterOpsAndEstimateGasParams,
filterOpsAndEstimateGas,
flushStuckTransaction,
simulatedOpsToResults
} from "./utils"
import * as sentry from "@sentry/node"
+import { BundleBulkerAbi, deriveUserOperation } from "@alto/types/src" | just @alto/types |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -13,6 +15,7 @@ import {
getUserOperationHash,
parseViemError
} from "@alto/utils"
+import { CompressionHandler } from "../../rpc/src/compressionHandler" // TODO: fix this | yep plz fix haha |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -215,8 +135,9 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- async checkEntityMultipleRoleViolation(op: UserOperation): Promise<void> {
- if (!this.safeMode) return
+ // biome-ignore lint/nursery/useAwait: keep async to adhere to interface
+ async checkEntityMultipleRoleViolation(op: UserOperation): Promise<void> {
+ if (!this.safeMode) { return Promise.resolve() } | wait can't we just return? why do we need to return Promise.resolve() |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -248,6 +169,8 @@ export class MemoryMempool implements Mempool {
ValidationErrors.OpcodeValidation
)
}
+
+ return Promise.resolve() | same here |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -910,4 +816,183 @@ export class RpcHandler implements IRpcEndpoint {
}
}
}
+
+ // check if we want to bundle userOperation. If yes, add to mempool
+ async addToMempoolIfValid(op: MempoolUserOperation, entryPoint: Address) {
+ const userOperation = deriveUserOperation(op)
+ if (this.entryPoint !== entryPoint) {
+ throw new RpcError(
+ `EntryPoint ${entryPoint} not supported, supported EntryPoints: ${this.entryPoint}`
+ )
+ }
+
+ if (
+ this.chainId === chains.celoAlfajores.id ||
+ this.chainId === chains.celo.id
+ ) {
+ if (
+ userOperation.maxFeePerGas !==
+ userOperation.maxPriorityFeePerGas
+ ) {
+ throw new RpcError(
+ "maxPriorityFeePerGas must equal maxFeePerGas on Celo chains"
+ )
+ }
+ }
+
+ if (this.minimumGasPricePercent !== 0) {
+ const gasPrice = await getGasPrice(
+ this.chainId,
+ this.publicClient,
+ this.logger
+ )
+ const minMaxFeePerGas =
+ (gasPrice.maxFeePerGas * BigInt(this.minimumGasPricePercent)) /
+ 100n
+ if (userOperation.maxFeePerGas < minMaxFeePerGas) {
+ throw new RpcError(
+ `maxFeePerGas must be at least ${minMaxFeePerGas} (current maxFeePerGas: ${gasPrice.maxFeePerGas}) - use pimlico_getUserOperationGasPrice to get the current gas price`
+ )
+ }
+
+ if (userOperation.maxPriorityFeePerGas < minMaxFeePerGas) {
+ throw new RpcError(
+ `maxPriorityFeePerGas must be at least ${minMaxFeePerGas} (current maxPriorityFeePerGas: ${gasPrice.maxPriorityFeePerGas}) - use pimlico_getUserOperationGasPrice to get the current gas price`
+ )
+ }
+ }
+
+ if (userOperation.verificationGasLimit < 10000n) {
+ throw new RpcError("verificationGasLimit must be at least 10000")
+ }
+
+ this.logger.trace({ userOperation, entryPoint }, "beginning validation")
+ this.metrics.userOperationsReceived.inc()
+
+ if (
+ userOperation.preVerificationGas === 0n ||
+ userOperation.verificationGasLimit === 0n ||
+ userOperation.callGasLimit === 0n
+ ) {
+ throw new RpcError(
+ "user operation gas limits must be larger than 0"
+ )
+ }
+
+ const entryPointContract = getContract({
+ address: this.entryPoint,
+ abi: EntryPointAbi,
+ publicClient: this.publicClient
+ })
+
+ const [nonceKey, userOperationNonceValue] = getNonceKeyAndValue(
+ userOperation.nonce
+ )
+
+ const getNonceResult = await entryPointContract.read.getNonce(
+ [userOperation.sender, nonceKey],
+ {
+ blockTag: "latest"
+ }
+ )
+
+ const [_, currentNonceValue] = getNonceKeyAndValue(getNonceResult)
+
+ if (userOperationNonceValue < currentNonceValue) {
+ throw new RpcError(
+ "UserOperation reverted during simulation with reason: AA25 invalid account nonce",
+ ValidationErrors.SimulateValidation
+ )
+ }
+ if (userOperationNonceValue > currentNonceValue + 10n) {
+ throw new RpcError(
+ "UserOperation reverted during simulation with reason: AA25 invalid account nonce",
+ ValidationErrors.SimulateValidation
+ )
+ }
+ if (userOperationNonceValue === currentNonceValue) {
+ const validationResult =
+ await this.validator.validateUserOperation(userOperation)
+ await this.reputationManager.checkReputation(
+ userOperation,
+ validationResult
+ )
+ await this.mempool.checkEntityMultipleRoleViolation(userOperation)
+ const success = this.mempool.add(
+ op,
+ validationResult.referencedContracts
+ )
+ if (!success) {
+ throw new RpcError(
+ "UserOperation reverted during simulation with reason: AA25 invalid account nonce",
+ ValidationErrors.SimulateValidation
+ )
+ }
+ } else {
+ this.nonceQueuer.add(userOperation)
+ }
+ }
+
+ async pimlico_sendCompressedUserOperation(
+ compressedCalldata: Hex,
+ entryPoint: Address, | hmm could we make the inflatorAddress second, and the entryPoint last here?
since sendUserOperation also has the entryPoint last |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -34,28 +42,49 @@ export function simulatedOpsToResults(
success: true,
value: {
userOperation: {
- userOperation: sop.op.userOperation,
- userOperationHash: sop.op.userOperationHash,
+ mempoolUserOperation: sop.owh.mempoolUserOperation,
+ userOperationHash: sop.owh.userOperationHash,
lastReplaced: Date.now(),
firstSubmitted: Date.now()
},
transactionInfo
}
}
- } else {
- return {
- success: false,
- error: {
- userOpHash: sop.op.userOperationHash,
- reason: sop.reason as string
- }
+ }
+ return {
+ success: false,
+ error: {
+ userOpHash: sop.owh.userOperationHash,
+ reason: sop.reason as string
}
}
})
}
-export async function filterOpsAndEstimateGas(
+export type DefaultFilterOpsAndEstimateGasParams = {
ep: GetContractReturnType<typeof EntryPointAbi, PublicClient, WalletClient>,
+ type: "default"
+}
+
+export type CompressedFilterOpsAndEstimateGasParams = {
+ publicClient: PublicClient,
+ bundleBulker: Address,
+ perOpInflatorId: number,
+ type: "compressed"
+}
+
+export function createCompressedCalldata(compressedOps: CompressedUserOperation[], perOpInflatorId: number): Hex {
+ let calldata = new Uint8Array([])
+ for (const op of compressedOps) { | maybe cleaner if we use `reduce`? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -34,28 +42,49 @@ export function simulatedOpsToResults(
success: true,
value: {
userOperation: {
- userOperation: sop.op.userOperation,
- userOperationHash: sop.op.userOperationHash,
+ mempoolUserOperation: sop.owh.mempoolUserOperation,
+ userOperationHash: sop.owh.userOperationHash,
lastReplaced: Date.now(),
firstSubmitted: Date.now()
},
transactionInfo
}
}
- } else {
- return {
- success: false,
- error: {
- userOpHash: sop.op.userOperationHash,
- reason: sop.reason as string
- }
+ }
+ return {
+ success: false,
+ error: {
+ userOpHash: sop.owh.userOperationHash,
+ reason: sop.reason as string
}
}
})
}
-export async function filterOpsAndEstimateGas(
+export type DefaultFilterOpsAndEstimateGasParams = {
ep: GetContractReturnType<typeof EntryPointAbi, PublicClient, WalletClient>,
+ type: "default"
+}
+
+export type CompressedFilterOpsAndEstimateGasParams = {
+ publicClient: PublicClient,
+ bundleBulker: Address,
+ perOpInflatorId: number,
+ type: "compressed"
+}
+
+export function createCompressedCalldata(compressedOps: CompressedUserOperation[], perOpInflatorId: number): Hex {
+ let calldata = new Uint8Array([]) | you can just concat hex strings, you don't need uint8arrays |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -320,6 +315,12 @@ export const bundlerHandler = async (
metrics
)
+ const compressionHandler = new CompressionHandler(
+ parsedArgs.bundleBulkerAddress,
+ parsedArgs.perOpInflatorAddress
+ )
+ await compressionHandler.fetchPerOpInflatorId(client) | could we call this `initialize` or something? |
alto | github_2023 | typescript | 78 | pimlicolabs | kristofgazso | @@ -74,13 +73,16 @@ export type CompressedFilterOpsAndEstimateGasParams = {
}
export function createCompressedCalldata(compressedOps: CompressedUserOperation[], perOpInflatorId: number): Hex {
- let calldata = new Uint8Array([])
- for (const op of compressedOps) {
- const encodedOp = concat([numberToBytes(op.inflatorId), hexToBytes(op.compressedCalldata)])
- calldata = concat([encodedOp, calldata])
- }
- calldata = concat([numberToBytes(perOpInflatorId), calldata])
- return toHex(calldata)
+ const callData: Hex = compressedOps.reduce((currentCallData, op) => {
+ const nextCallData = concat([
+ numberToHex(op.inflatorId),
+ op.compressedCalldata
+ ]);
+
+ return concat([nextCallData, currentCallData])
+ }, toHex("")); | why not `toHex("")` -> `numerToHex(perOpInflatorId)` |
alto | github_2023 | typescript | 90 | pimlicolabs | kristofgazso | @@ -172,6 +172,12 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
description: "Max block range for rpc calls",
type: "number",
require: false,
+ },
+ flushStuckTransactionsDuringStartUp: {
+ description: "Should the bundler try to flush out all stuck pending transactions on startup",
+ type: "bool",
+ default: false,
+ require: false, | require true |
alto | github_2023 | typescript | 90 | pimlicolabs | kristofgazso | @@ -172,6 +172,12 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
description: "Max block range for rpc calls",
type: "number",
require: false,
+ },
+ flushStuckTransactionsDuringStartUp: { | StartUp->Startup |
alto | github_2023 | typescript | 90 | pimlicolabs | kristofgazso | @@ -172,6 +172,11 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
description: "Max block range for rpc calls",
type: "number",
require: false,
+ },
+ flushStuckTransactionsDuringStartup: {
+ description: "Should the bundler try to flush out all stuck pending transactions on startup",
+ type: "boolean",
+ require: true, | oh i'd keep default false |
alto | github_2023 | others | 84 | pimlicolabs | plusminushalf | @@ -12,28 +12,29 @@
"start": "node packages/cli/lib/alto.js run",
"dev": "node --inspect packages/cli/lib/alto.js run",
"test": "pnpm -r --workspace-concurrency 1 test --verbose=true",
- "test:spec": "./test/run-spec-tests.sh",
+ "test:spec": "./test/spec-tests/run-spec-tests.sh",
"lint": "rome check ./",
"lint:fix": "rome check ./ --apply",
"format": "biome format . --write"
},
"devDependencies": {
- "@biomejs/biome": "^1.5.0",
- "@swc/core": "^1.3.56",
- "@types/mocha": "^10.0.1",
+ "@biomejs/biome": "^1.5.1",
+ "@swc/core": "^1.3.102", | not for you but I don't know why do we have this dependency, we don't use it anywhere. |
alto | github_2023 | others | 84 | pimlicolabs | nikmel2803 | @@ -0,0 +1,25 @@
+name: Run E2E Tests
+
+on:
+ push:
+ branches:
+ - main
+ pull_request:
+ branches:
+ - main
+
+jobs:
+ docker:
+ timeout-minutes: 10
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v1 | ```suggestion
uses: actions/checkout@v4
``` |
alto | github_2023 | others | 84 | pimlicolabs | nikmel2803 | @@ -0,0 +1,6 @@
+FROM ghcr.io/foundry-rs/foundry | why do we need this Dockerfile? you can run this image directly with docker compose |
alto | github_2023 | others | 84 | pimlicolabs | nikmel2803 | @@ -0,0 +1,26 @@
+version: "2.2" | ```suggestion
version: "3.8"
``` |
alto | github_2023 | others | 84 | pimlicolabs | nikmel2803 | @@ -0,0 +1,26 @@
+version: "2.2"
+
+services:
+ anvil:
+ container_name: anvil | is there any specific reason to specify it? i think we can omit it |
alto | github_2023 | typescript | 82 | pimlicolabs | kristofgazso | @@ -203,6 +208,27 @@ export class UnsafeValidator implements IValidator {
this.usingTenderly
) as Promise<ExecutionResult>
}
+
+ if (this.balanceStateOverrideAllowed) {
+ const error = await simulateHandleOp(
+ userOperation,
+ this.entryPoint,
+ this.publicClient,
+ false,
+ zeroAddress,
+ "0x"
+ )
+
+ if (error.result === "failed") {
+ throw new RpcError(
+ `UserOperation reverted during simulation with reason: ${error.data}`,
+ ExecutionErrors.UserOperationReverted
+ )
+ }
+
+ return error.data | uh... does this have the correct return type? |
alto | github_2023 | typescript | 82 | pimlicolabs | kristofgazso | @@ -133,6 +133,12 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
require: true,
default: false
},
+ balanceStateOverrideAllowed: { | isn't it just `balanceOverride` as opposed to `balanceStateOverride`? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -151,6 +151,18 @@ export const bundlerOptions: CliCommandOptions<IBundlerArgsInput> = {
customGasLimitForEstimation: {
description: "Custom gas limit for estimation",
type: "string"
+ },
+ bundleMode: {
+ description: "set if the bundler should auto bundle or not.", | Grammar / Spelling |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -47,9 +49,62 @@ export class ExecutorManager {
this.logger = logger
this.metrics = metrics
- setInterval(async () => {
- await this.bundle()
- }, 1000)
+ if (bundleMode === "auto") { | Use Enum here? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -47,9 +49,62 @@ export class ExecutorManager {
this.logger = logger
this.metrics = metrics
- setInterval(async () => {
- await this.bundle()
- }, 1000)
+ if (bundleMode === "auto") {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, 1000) | Should also prob make this bundle frequency configurable |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -47,9 +49,62 @@ export class ExecutorManager {
this.logger = logger
this.metrics = metrics
- setInterval(async () => {
- await this.bundle()
- }, 1000)
+ if (bundleMode === "auto") {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, 1000)
+ }
+ }
+
+ setBundlingMode(bundleMode: BundlingMode): void {
+ if (bundleMode === "auto" && !this.timer) {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, 1000)
+ } else if (bundleMode === "manual" && this.timer) {
+ clearInterval(this.timer)
+ this.timer = undefined
+ }
+ }
+
+ async bundleNow(): Promise<Hash> { | hmm can't this function be sort of merged with the original `bundle` func? seems like there is some overlap |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -134,16 +148,34 @@ export class MemoryMempool implements Mempool {
...this.store.dumpProcessing(),
...this.store.dumpSubmitted().map((sop) => sop.userOperation)
]
- if (allOps.find((uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce)) {
- return false
+ const oldUserOp = allOps.find(
+ (uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce | is this tested? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -134,16 +148,34 @@ export class MemoryMempool implements Mempool {
...this.store.dumpProcessing(),
...this.store.dumpSubmitted().map((sop) => sop.userOperation)
]
- if (allOps.find((uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce)) {
- return false
+ const oldUserOp = allOps.find(
+ (uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce
+ )
+ if (oldUserOp) {
+ const oldMaxPriorityFeePerGas = oldUserOp.userOperation.maxPriorityFeePerGas
+ const newMaxPriorityFeePerGas = op.maxPriorityFeePerGas
+ const oldMaxFeePerGas = oldUserOp.userOperation.maxFeePerGas
+ const newMaxFeePerGas = op.maxFeePerGas
+
+ const incrementMaxPriorityFeePerGas = (oldMaxPriorityFeePerGas * BigInt(10)) / BigInt(100)
+ const incrementMaxFeePerGas = (oldMaxFeePerGas * BigInt(10)) / BigInt(100)
+
+ if (
+ newMaxPriorityFeePerGas < oldMaxPriorityFeePerGas + incrementMaxPriorityFeePerGas ||
+ newMaxFeePerGas < oldMaxFeePerGas + incrementMaxFeePerGas
+ ) {
+ return false
+ }
+
+ this.store.removeOutstanding(oldUserOp.userOperationHash)
}
const hash = getUserOperationHash(op, this.entryPointAddress, this.publicClient.chain.id)
this.store.addOutstanding({
userOperation: op,
userOperationHash: hash,
- firstSubmitted: Date.now(),
+ firstSubmitted: oldUserOp ? oldUserOp.firstSubmitted : Date.now(),
lastReplaced: Date.now()
})
this.monitor.setUserOperationStatus(hash, { status: "not_submitted", transactionHash: null }) | hmm should we not come up with a new status like `replaced` if it's replaced with another op with the same nonce? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -586,19 +596,36 @@ export class RpcHandler implements IRpcEndpoint {
}
async debug_bundler_clearState(): Promise<BundlerClearStateResponseResult> {
- throw new Error("Method not implemented.")
+ if (this.environment !== "development") {
+ throw new RpcError("debug_bundler_clearState is only available in development environment")
+ }
+ this.mempool.clear()
+ return "ok"
}
- async debug_bundler_dumpMempool(_entryPoint: Address): Promise<BundlerDumpMempoolResponseResult> {
- throw new Error("Method not implemented.")
+ async debug_bundler_dumpMempool(entryPoint: Address): Promise<BundlerDumpMempoolResponseResult> {
+ if (this.environment !== "development") {
+ throw new RpcError("debug_bundler_dumpMempool is only available in development environment")
+ }
+ if (this.entryPoint !== entryPoint) {
+ throw new RpcError(`EntryPoint ${entryPoint} not supported, supported EntryPoints: ${this.entryPoint}`)
+ }
+ return this.mempool.dumpOutstanding().map((userOpInfo) => userOpInfo.userOperation)
}
async debug_bundler_sendBundleNow(): Promise<BundlerSendBundleNowResponseResult> {
- throw new Error("Method not implemented.")
+ if (this.environment !== "development") {
+ throw new RpcError("debug_bundler_sendBundleNow is only available in development environment")
+ }
+ return this.executorManager.bundleNow()
}
async debug_bundler_setBundlingMode(_bundlingMode: BundlingMode): Promise<BundlerSetBundlingModeResponseResult> { | hmm we don't use _ naming anywhere else |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,365 @@
+// javascript code of tracer function
+// NOTE: we process this locally for hardhat, but send to geth for remote tracing.
+// should NOT "require" anything, or use logs.
+// see LogTrace for valid types (but alas, this one must be javascript, not typescript).
+
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+
+import { Hex } from "viem"
+import { LogCallFrame, LogContext, LogDb, LogFrameResult, LogStep, LogTracer } from "./tracer"
+
+// functions available in a context of geth tracer
+declare function toHex(a: any): Hex
+
+declare function toWord(a: any): string
+
+declare function toAddress(a: any): string
+
+/**
+ * return type of our BundlerCollectorTracer.
+ * collect access and opcodes, split into "levels" based on NUMBER opcode
+ * keccak, calls and logs are collected globally, since the levels are unimportant for them.
+ */
+export interface BundlerTracerResult {
+ /**
+ * storage and opcode info, collected on top-level calls from EntryPoint
+ */
+ callsFromEntryPoint: TopLevelCallInfo[]
+
+ /**
+ * values passed into KECCAK opcode
+ */
+ keccak: string[]
+ calls: Array<ExitInfo | MethodInfo>
+ logs: LogInfo[]
+ debug: any[]
+}
+
+export interface MethodInfo {
+ type: string
+ from: string
+ to: string
+ method: string
+ value: any
+ gas: number
+}
+
+export interface ExitInfo {
+ type: "REVERT" | "RETURN"
+ gasUsed: number
+ data: Hex
+}
+
+export interface TopLevelCallInfo {
+ topLevelMethodSig: string
+ topLevelTargetAddress: string | use `Address` type? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,365 @@
+// javascript code of tracer function
+// NOTE: we process this locally for hardhat, but send to geth for remote tracing.
+// should NOT "require" anything, or use logs.
+// see LogTrace for valid types (but alas, this one must be javascript, not typescript).
+
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+
+import { Hex } from "viem"
+import { LogCallFrame, LogContext, LogDb, LogFrameResult, LogStep, LogTracer } from "./tracer"
+
+// functions available in a context of geth tracer
+declare function toHex(a: any): Hex
+
+declare function toWord(a: any): string
+
+declare function toAddress(a: any): string
+
+/**
+ * return type of our BundlerCollectorTracer.
+ * collect access and opcodes, split into "levels" based on NUMBER opcode
+ * keccak, calls and logs are collected globally, since the levels are unimportant for them.
+ */
+export interface BundlerTracerResult {
+ /**
+ * storage and opcode info, collected on top-level calls from EntryPoint
+ */
+ callsFromEntryPoint: TopLevelCallInfo[]
+
+ /**
+ * values passed into KECCAK opcode
+ */
+ keccak: string[]
+ calls: Array<ExitInfo | MethodInfo>
+ logs: LogInfo[]
+ debug: any[]
+}
+
+export interface MethodInfo {
+ type: string
+ from: string
+ to: string
+ method: string
+ value: any | `bigint`? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,365 @@
+// javascript code of tracer function
+// NOTE: we process this locally for hardhat, but send to geth for remote tracing.
+// should NOT "require" anything, or use logs.
+// see LogTrace for valid types (but alas, this one must be javascript, not typescript).
+
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+
+import { Hex } from "viem"
+import { LogCallFrame, LogContext, LogDb, LogFrameResult, LogStep, LogTracer } from "./tracer"
+
+// functions available in a context of geth tracer
+declare function toHex(a: any): Hex
+
+declare function toWord(a: any): string
+
+declare function toAddress(a: any): string
+
+/**
+ * return type of our BundlerCollectorTracer.
+ * collect access and opcodes, split into "levels" based on NUMBER opcode
+ * keccak, calls and logs are collected globally, since the levels are unimportant for them.
+ */
+export interface BundlerTracerResult {
+ /**
+ * storage and opcode info, collected on top-level calls from EntryPoint
+ */
+ callsFromEntryPoint: TopLevelCallInfo[]
+
+ /**
+ * values passed into KECCAK opcode
+ */
+ keccak: string[]
+ calls: Array<ExitInfo | MethodInfo>
+ logs: LogInfo[]
+ debug: any[]
+}
+
+export interface MethodInfo {
+ type: string
+ from: string
+ to: string | `Address` types here? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,365 @@
+// javascript code of tracer function
+// NOTE: we process this locally for hardhat, but send to geth for remote tracing.
+// should NOT "require" anything, or use logs.
+// see LogTrace for valid types (but alas, this one must be javascript, not typescript).
+
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+
+import { Hex } from "viem"
+import { LogCallFrame, LogContext, LogDb, LogFrameResult, LogStep, LogTracer } from "./tracer"
+
+// functions available in a context of geth tracer
+declare function toHex(a: any): Hex
+
+declare function toWord(a: any): string
+
+declare function toAddress(a: any): string
+
+/**
+ * return type of our BundlerCollectorTracer.
+ * collect access and opcodes, split into "levels" based on NUMBER opcode
+ * keccak, calls and logs are collected globally, since the levels are unimportant for them.
+ */
+export interface BundlerTracerResult {
+ /**
+ * storage and opcode info, collected on top-level calls from EntryPoint
+ */
+ callsFromEntryPoint: TopLevelCallInfo[]
+
+ /**
+ * values passed into KECCAK opcode
+ */
+ keccak: string[]
+ calls: Array<ExitInfo | MethodInfo>
+ logs: LogInfo[]
+ debug: any[]
+}
+
+export interface MethodInfo {
+ type: string
+ from: string
+ to: string
+ method: string
+ value: any
+ gas: number
+}
+
+export interface ExitInfo {
+ type: "REVERT" | "RETURN"
+ gasUsed: number
+ data: Hex
+}
+
+export interface TopLevelCallInfo {
+ topLevelMethodSig: string
+ topLevelTargetAddress: string
+ opcodes: { [opcode: string]: number }
+ access: { [address: string]: AccessInfo }
+ contractSize: { [addr: string]: ContractSizeInfo }
+ extCodeAccessInfo: { [addr: string]: string }
+ oog?: boolean
+}
+
+/**
+ * It is illegal to access contracts with no code in validation even if it gets deployed later.
+ * This means we need to store the {@link contractSize} of accessed addresses at the time of access.
+ */
+export interface ContractSizeInfo {
+ opcode: string
+ contractSize: number
+}
+
+export interface AccessInfo {
+ // slot value, just prior this operation
+ reads: { [slot: string]: string }
+ // count of writes.
+ writes: { [slot: string]: number }
+}
+
+export interface LogInfo {
+ topics: string[]
+ data: string
+}
+
+interface RelevantStepData {
+ opcode: string
+ stackTop3: any[]
+}
+
+/**
+ * type-safe local storage of our collector. contains all return-value properties.
+ * (also defines all "trace-local" variables and functions)
+ */
+interface BundlerCollectorTracer extends LogTracer, BundlerTracerResult {
+ lastOp: string
+ lastThreeOpcodes: RelevantStepData[]
+ stopCollectingTopic: string
+ stopCollecting: boolean
+ currentLevel: TopLevelCallInfo
+ topLevelCallCounter: number
+ countSlot: (list: { [key: string]: number | undefined }, key: any) => void
+}
+
+/**
+ * tracer to collect data for opcode banning.
+ * this method is passed as the "tracer" for eth_traceCall (note, the function itself)
+ *
+ * returned data:
+ * numberLevels: opcodes and memory access, split on execution of "number" opcode.
+ * keccak: input data of keccak opcode.
+ * calls: for each call, an array of [type, from, to, value]
+ * slots: accessed slots (on any address)
+ */
+export function bundlerCollectorTracer(): BundlerCollectorTracer {
+ return {
+ callsFromEntryPoint: [],
+ currentLevel: null as any,
+ keccak: [],
+ calls: [],
+ logs: [],
+ debug: [],
+ lastOp: "",
+ lastThreeOpcodes: [],
+ // event sent after all validations are done: keccak("BeforeExecution()")
+ stopCollectingTopic: "bb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f972",
+ stopCollecting: false,
+ topLevelCallCounter: 0,
+
+ fault(log: LogStep, _db: LogDb): void {
+ this.debug.push(
+ "fault depth=",
+ log.getDepth(),
+ " gas=",
+ log.getGas(),
+ " cost=",
+ log.getCost(),
+ " err=",
+ log.getError()
+ )
+ }, | is there no better way to log this? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,365 @@
+// javascript code of tracer function
+// NOTE: we process this locally for hardhat, but send to geth for remote tracing.
+// should NOT "require" anything, or use logs.
+// see LogTrace for valid types (but alas, this one must be javascript, not typescript).
+
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+
+import { Hex } from "viem"
+import { LogCallFrame, LogContext, LogDb, LogFrameResult, LogStep, LogTracer } from "./tracer"
+
+// functions available in a context of geth tracer
+declare function toHex(a: any): Hex
+
+declare function toWord(a: any): string
+
+declare function toAddress(a: any): string
+
+/**
+ * return type of our BundlerCollectorTracer.
+ * collect access and opcodes, split into "levels" based on NUMBER opcode
+ * keccak, calls and logs are collected globally, since the levels are unimportant for them.
+ */
+export interface BundlerTracerResult {
+ /**
+ * storage and opcode info, collected on top-level calls from EntryPoint
+ */
+ callsFromEntryPoint: TopLevelCallInfo[]
+
+ /**
+ * values passed into KECCAK opcode
+ */
+ keccak: string[]
+ calls: Array<ExitInfo | MethodInfo>
+ logs: LogInfo[]
+ debug: any[]
+}
+
+export interface MethodInfo {
+ type: string
+ from: string
+ to: string
+ method: string
+ value: any
+ gas: number
+}
+
+export interface ExitInfo {
+ type: "REVERT" | "RETURN"
+ gasUsed: number
+ data: Hex
+}
+
+export interface TopLevelCallInfo {
+ topLevelMethodSig: string
+ topLevelTargetAddress: string
+ opcodes: { [opcode: string]: number }
+ access: { [address: string]: AccessInfo }
+ contractSize: { [addr: string]: ContractSizeInfo }
+ extCodeAccessInfo: { [addr: string]: string }
+ oog?: boolean
+}
+
+/**
+ * It is illegal to access contracts with no code in validation even if it gets deployed later.
+ * This means we need to store the {@link contractSize} of accessed addresses at the time of access.
+ */
+export interface ContractSizeInfo {
+ opcode: string
+ contractSize: number
+}
+
+export interface AccessInfo {
+ // slot value, just prior this operation
+ reads: { [slot: string]: string }
+ // count of writes.
+ writes: { [slot: string]: number }
+}
+
+export interface LogInfo {
+ topics: string[]
+ data: string
+}
+
+interface RelevantStepData {
+ opcode: string
+ stackTop3: any[]
+}
+
+/**
+ * type-safe local storage of our collector. contains all return-value properties.
+ * (also defines all "trace-local" variables and functions)
+ */
+interface BundlerCollectorTracer extends LogTracer, BundlerTracerResult {
+ lastOp: string
+ lastThreeOpcodes: RelevantStepData[]
+ stopCollectingTopic: string
+ stopCollecting: boolean
+ currentLevel: TopLevelCallInfo
+ topLevelCallCounter: number
+ countSlot: (list: { [key: string]: number | undefined }, key: any) => void
+}
+
+/**
+ * tracer to collect data for opcode banning.
+ * this method is passed as the "tracer" for eth_traceCall (note, the function itself)
+ *
+ * returned data:
+ * numberLevels: opcodes and memory access, split on execution of "number" opcode.
+ * keccak: input data of keccak opcode.
+ * calls: for each call, an array of [type, from, to, value]
+ * slots: accessed slots (on any address)
+ */
+export function bundlerCollectorTracer(): BundlerCollectorTracer {
+ return {
+ callsFromEntryPoint: [],
+ currentLevel: null as any,
+ keccak: [],
+ calls: [],
+ logs: [],
+ debug: [],
+ lastOp: "",
+ lastThreeOpcodes: [],
+ // event sent after all validations are done: keccak("BeforeExecution()")
+ stopCollectingTopic: "bb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f972",
+ stopCollecting: false,
+ topLevelCallCounter: 0,
+
+ fault(log: LogStep, _db: LogDb): void {
+ this.debug.push(
+ "fault depth=",
+ log.getDepth(),
+ " gas=",
+ log.getGas(),
+ " cost=",
+ log.getCost(),
+ " err=",
+ log.getError()
+ )
+ },
+
+ result(_ctx: LogContext, _db: LogDb): BundlerTracerResult {
+ return {
+ callsFromEntryPoint: this.callsFromEntryPoint,
+ keccak: this.keccak,
+ logs: this.logs,
+ calls: this.calls,
+ debug: this.debug // for internal debugging.
+ }
+ },
+
+ enter(frame: LogCallFrame): void {
+ if (this.stopCollecting) {
+ return
+ }
+ // this.debug.push('enter gas=', frame.getGas(), ' type=', frame.getType(), ' to=', toHex(frame.getTo()), ' in=', toHex(frame.getInput()).slice(0, 500))
+ this.calls.push({
+ type: frame.getType(),
+ from: toHex(frame.getFrom()),
+ to: toHex(frame.getTo()),
+ method: toHex(frame.getInput()).slice(0, 10),
+ gas: frame.getGas(),
+ value: frame.getValue()
+ })
+ },
+ exit(frame: LogFrameResult): void {
+ if (this.stopCollecting) {
+ return
+ }
+ this.calls.push({
+ type: frame.getError() != null ? "REVERT" : "RETURN",
+ gasUsed: frame.getGasUsed(),
+ data: toHex(frame.getOutput()).slice(0, 4000) as Hex
+ })
+ },
+
+ // increment the "key" in the list. if the key is not defined yet, then set it to "1"
+ countSlot(list: { [key: string]: number | undefined }, key: any) {
+ if (list[key]) {
+ // @ts-ignore
+ list[key] += 1
+ } else {
+ list[key] = 1
+ }
+ },
+ step(log: LogStep, db: LogDb): any {
+ if (this.stopCollecting) {
+ return
+ }
+ const opcode = log.op.toString()
+
+ const stackSize = log.stack.length()
+ const stackTop3 = []
+ for (let i = 0; i < 3 && i < stackSize; i++) {
+ stackTop3.push(log.stack.peek(i))
+ }
+ this.lastThreeOpcodes.push({ opcode, stackTop3 })
+ if (this.lastThreeOpcodes.length > 3) {
+ this.lastThreeOpcodes.shift()
+ }
+ // this.debug.push(this.lastOp + '-' + opcode + '-' + log.getDepth() + '-' + log.getGas() + '-' + log.getCost())
+ if (
+ log.getGas() < log.getCost() ||
+ // special rule for SSTORE with gas metering
+ (opcode === "SSTORE" && log.getGas() < 2300)
+ ) {
+ this.currentLevel.oog = true
+ }
+
+ if (opcode === "REVERT" || opcode === "RETURN") {
+ if (log.getDepth() === 1) {
+ // exit() is not called on top-level return/revent, so we reconstruct it
+ // from opcode
+ const ofs = parseInt(log.stack.peek(0).toString())
+ const len = parseInt(log.stack.peek(1).toString())
+ const data = toHex(log.memory.slice(ofs, ofs + len)).slice(0, 4000) as Hex
+ // this.debug.push(opcode + ' ' + data)
+ this.calls.push({
+ type: opcode,
+ gasUsed: 0,
+ data
+ })
+ }
+ // NOTE: flushing all history after RETURN
+ this.lastThreeOpcodes = []
+ }
+
+ if (log.getDepth() === 1) {
+ if (opcode === "CALL" || opcode === "STATICCALL") {
+ // stack.peek(0) - gas
+ const addr = toAddress(log.stack.peek(1).toString(16))
+ const topLevelTargetAddress = toHex(addr)
+ // stack.peek(2) - value
+ const ofs = parseInt(log.stack.peek(3).toString())
+ // stack.peek(4) - len
+ const topLevelMethodSig = toHex(log.memory.slice(ofs, ofs + 4))
+
+ this.currentLevel = this.callsFromEntryPoint[this.topLevelCallCounter] = {
+ topLevelMethodSig,
+ topLevelTargetAddress,
+ access: {},
+ opcodes: {},
+ extCodeAccessInfo: {},
+ contractSize: {}
+ }
+ this.topLevelCallCounter++
+ } else if (opcode === "LOG1") {
+ // ignore log data ofs, len
+ const topic = log.stack.peek(2).toString(16)
+ if (topic === this.stopCollectingTopic) {
+ this.stopCollecting = true
+ }
+ }
+ this.lastOp = ""
+ return
+ }
+
+ const lastOpInfo = this.lastThreeOpcodes[this.lastThreeOpcodes.length - 2]
+ // store all addresses touched by EXTCODE* opcodes
+ if (lastOpInfo && lastOpInfo.opcode && lastOpInfo.opcode.match(/^(EXT.*)$/) != null) {
+ const addr = toAddress(lastOpInfo.stackTop3[0].toString(16))
+ const addrHex = toHex(addr)
+ const last3opcodesString = this.lastThreeOpcodes.map((x) => x.opcode).join(" ") | why do we convert this to a string and use regex logic instead of just working with the array? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,365 @@
+// javascript code of tracer function
+// NOTE: we process this locally for hardhat, but send to geth for remote tracing.
+// should NOT "require" anything, or use logs.
+// see LogTrace for valid types (but alas, this one must be javascript, not typescript).
+
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+
+import { Hex } from "viem"
+import { LogCallFrame, LogContext, LogDb, LogFrameResult, LogStep, LogTracer } from "./tracer"
+
+// functions available in a context of geth tracer
+declare function toHex(a: any): Hex
+
+declare function toWord(a: any): string
+
+declare function toAddress(a: any): string
+
+/**
+ * return type of our BundlerCollectorTracer.
+ * collect access and opcodes, split into "levels" based on NUMBER opcode
+ * keccak, calls and logs are collected globally, since the levels are unimportant for them.
+ */
+export interface BundlerTracerResult {
+ /**
+ * storage and opcode info, collected on top-level calls from EntryPoint
+ */
+ callsFromEntryPoint: TopLevelCallInfo[]
+
+ /**
+ * values passed into KECCAK opcode
+ */
+ keccak: string[]
+ calls: Array<ExitInfo | MethodInfo>
+ logs: LogInfo[]
+ debug: any[]
+}
+
+export interface MethodInfo {
+ type: string
+ from: string
+ to: string
+ method: string
+ value: any
+ gas: number
+}
+
+export interface ExitInfo {
+ type: "REVERT" | "RETURN"
+ gasUsed: number
+ data: Hex
+}
+
+export interface TopLevelCallInfo {
+ topLevelMethodSig: string
+ topLevelTargetAddress: string
+ opcodes: { [opcode: string]: number }
+ access: { [address: string]: AccessInfo }
+ contractSize: { [addr: string]: ContractSizeInfo }
+ extCodeAccessInfo: { [addr: string]: string }
+ oog?: boolean
+}
+
+/**
+ * It is illegal to access contracts with no code in validation even if it gets deployed later.
+ * This means we need to store the {@link contractSize} of accessed addresses at the time of access.
+ */
+export interface ContractSizeInfo {
+ opcode: string
+ contractSize: number
+}
+
+export interface AccessInfo {
+ // slot value, just prior this operation
+ reads: { [slot: string]: string }
+ // count of writes.
+ writes: { [slot: string]: number }
+}
+
+export interface LogInfo {
+ topics: string[]
+ data: string
+}
+
+interface RelevantStepData {
+ opcode: string
+ stackTop3: any[]
+}
+
+/**
+ * type-safe local storage of our collector. contains all return-value properties.
+ * (also defines all "trace-local" variables and functions)
+ */
+interface BundlerCollectorTracer extends LogTracer, BundlerTracerResult {
+ lastOp: string
+ lastThreeOpcodes: RelevantStepData[]
+ stopCollectingTopic: string
+ stopCollecting: boolean
+ currentLevel: TopLevelCallInfo
+ topLevelCallCounter: number
+ countSlot: (list: { [key: string]: number | undefined }, key: any) => void
+}
+
+/**
+ * tracer to collect data for opcode banning.
+ * this method is passed as the "tracer" for eth_traceCall (note, the function itself)
+ *
+ * returned data:
+ * numberLevels: opcodes and memory access, split on execution of "number" opcode.
+ * keccak: input data of keccak opcode.
+ * calls: for each call, an array of [type, from, to, value]
+ * slots: accessed slots (on any address)
+ */
+export function bundlerCollectorTracer(): BundlerCollectorTracer {
+ return {
+ callsFromEntryPoint: [],
+ currentLevel: null as any,
+ keccak: [],
+ calls: [],
+ logs: [],
+ debug: [],
+ lastOp: "",
+ lastThreeOpcodes: [],
+ // event sent after all validations are done: keccak("BeforeExecution()")
+ stopCollectingTopic: "bb47ee3e183a558b1a2ff0874b079f3fc5478b7454eacf2bfc5af2ff5878f972",
+ stopCollecting: false,
+ topLevelCallCounter: 0,
+
+ fault(log: LogStep, _db: LogDb): void {
+ this.debug.push(
+ "fault depth=",
+ log.getDepth(),
+ " gas=",
+ log.getGas(),
+ " cost=",
+ log.getCost(),
+ " err=",
+ log.getError()
+ )
+ },
+
+ result(_ctx: LogContext, _db: LogDb): BundlerTracerResult {
+ return {
+ callsFromEntryPoint: this.callsFromEntryPoint,
+ keccak: this.keccak,
+ logs: this.logs,
+ calls: this.calls,
+ debug: this.debug // for internal debugging.
+ }
+ },
+
+ enter(frame: LogCallFrame): void {
+ if (this.stopCollecting) {
+ return
+ }
+ // this.debug.push('enter gas=', frame.getGas(), ' type=', frame.getType(), ' to=', toHex(frame.getTo()), ' in=', toHex(frame.getInput()).slice(0, 500))
+ this.calls.push({
+ type: frame.getType(),
+ from: toHex(frame.getFrom()),
+ to: toHex(frame.getTo()),
+ method: toHex(frame.getInput()).slice(0, 10),
+ gas: frame.getGas(),
+ value: frame.getValue()
+ })
+ },
+ exit(frame: LogFrameResult): void {
+ if (this.stopCollecting) {
+ return
+ }
+ this.calls.push({
+ type: frame.getError() != null ? "REVERT" : "RETURN",
+ gasUsed: frame.getGasUsed(),
+ data: toHex(frame.getOutput()).slice(0, 4000) as Hex
+ })
+ },
+
+ // increment the "key" in the list. if the key is not defined yet, then set it to "1"
+ countSlot(list: { [key: string]: number | undefined }, key: any) {
+ if (list[key]) {
+ // @ts-ignore
+ list[key] += 1
+ } else {
+ list[key] = 1
+ }
+ },
+ step(log: LogStep, db: LogDb): any {
+ if (this.stopCollecting) {
+ return
+ }
+ const opcode = log.op.toString()
+
+ const stackSize = log.stack.length()
+ const stackTop3 = []
+ for (let i = 0; i < 3 && i < stackSize; i++) {
+ stackTop3.push(log.stack.peek(i))
+ }
+ this.lastThreeOpcodes.push({ opcode, stackTop3 })
+ if (this.lastThreeOpcodes.length > 3) {
+ this.lastThreeOpcodes.shift()
+ }
+ // this.debug.push(this.lastOp + '-' + opcode + '-' + log.getDepth() + '-' + log.getGas() + '-' + log.getCost())
+ if (
+ log.getGas() < log.getCost() ||
+ // special rule for SSTORE with gas metering
+ (opcode === "SSTORE" && log.getGas() < 2300)
+ ) {
+ this.currentLevel.oog = true
+ }
+
+ if (opcode === "REVERT" || opcode === "RETURN") {
+ if (log.getDepth() === 1) {
+ // exit() is not called on top-level return/revent, so we reconstruct it
+ // from opcode
+ const ofs = parseInt(log.stack.peek(0).toString())
+ const len = parseInt(log.stack.peek(1).toString())
+ const data = toHex(log.memory.slice(ofs, ofs + len)).slice(0, 4000) as Hex
+ // this.debug.push(opcode + ' ' + data)
+ this.calls.push({
+ type: opcode,
+ gasUsed: 0,
+ data
+ })
+ }
+ // NOTE: flushing all history after RETURN
+ this.lastThreeOpcodes = []
+ }
+
+ if (log.getDepth() === 1) {
+ if (opcode === "CALL" || opcode === "STATICCALL") {
+ // stack.peek(0) - gas
+ const addr = toAddress(log.stack.peek(1).toString(16))
+ const topLevelTargetAddress = toHex(addr)
+ // stack.peek(2) - value
+ const ofs = parseInt(log.stack.peek(3).toString())
+ // stack.peek(4) - len
+ const topLevelMethodSig = toHex(log.memory.slice(ofs, ofs + 4))
+
+ this.currentLevel = this.callsFromEntryPoint[this.topLevelCallCounter] = {
+ topLevelMethodSig,
+ topLevelTargetAddress,
+ access: {},
+ opcodes: {},
+ extCodeAccessInfo: {},
+ contractSize: {}
+ }
+ this.topLevelCallCounter++
+ } else if (opcode === "LOG1") {
+ // ignore log data ofs, len
+ const topic = log.stack.peek(2).toString(16)
+ if (topic === this.stopCollectingTopic) {
+ this.stopCollecting = true
+ }
+ }
+ this.lastOp = ""
+ return
+ }
+
+ const lastOpInfo = this.lastThreeOpcodes[this.lastThreeOpcodes.length - 2]
+ // store all addresses touched by EXTCODE* opcodes
+ if (lastOpInfo && lastOpInfo.opcode && lastOpInfo.opcode.match(/^(EXT.*)$/) != null) {
+ const addr = toAddress(lastOpInfo.stackTop3[0].toString(16))
+ const addrHex = toHex(addr)
+ const last3opcodesString = this.lastThreeOpcodes.map((x) => x.opcode).join(" ")
+ // only store the last EXTCODE* opcode per address - could even be a boolean for our current use-case
+ // [OP-051]
+ if (last3opcodesString.match(/^(\w+) EXTCODESIZE ISZERO$/) == null) {
+ this.currentLevel.extCodeAccessInfo[addrHex] = opcode
+ // this.debug.push(`potentially illegal EXTCODESIZE without ISZERO for ${addrHex}`)
+ } else {
+ // this.debug.push(`safe EXTCODESIZE with ISZERO for ${addrHex}`)
+ }
+ }
+
+ // not using 'isPrecompiled' to only allow the ones defined by the ERC-4337 as stateless precompiles
+ // [OP-062]
+ const isAllowedPrecompiled: (address: any) => boolean = (address) => {
+ const addrHex = toHex(address)
+ const addressInt = parseInt(addrHex)
+ // this.debug.push(`isPrecompiled address=${addrHex} addressInt=${addressInt}`)
+ return addressInt > 0 && addressInt < 10
+ }
+ // [OP-041]
+ if (opcode.match(/^(EXT.*|CALL|CALLCODE|DELEGATECALL|STATICCALL)$/) != null) {
+ const idx = opcode.startsWith("EXT") ? 0 : 1
+ const addr = toAddress(log.stack.peek(idx).toString(16))
+ const addrHex = toHex(addr)
+ // this.debug.push('op=' + opcode + ' last=' + this.lastOp + ' stacksize=' + log.stack.length() + ' addr=' + addrHex)
+ if (this.currentLevel.contractSize[addrHex] == null && !isAllowedPrecompiled(addr)) {
+ this.currentLevel.contractSize[addrHex] = {
+ contractSize: db.getCode(addr).length,
+ opcode
+ }
+ }
+ }
+
+ // [OP-012] | I love how we mention the specific rule that is being checked — great for reference! Could we do this in other places too? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -181,17 +237,159 @@ export class UnsafeValidator implements IValidator {
// @ts-ignore
return getSimulationResult(errorResult, this.logger, "validation", this.usingTenderly)
- } else {
- const errorResult = await entryPointContract.simulate.simulateValidation([userOperation]).catch((e) => {
- if (e instanceof Error) {
- return e
- } else {
- throw e
- }
+ }
+
+ if (this.supportTracer) {
+ const [res, tracerResult] = await this.getValidationResultWithTracer(userOperation)
+
+ // const [contractAddresses, storageMap] =
+ tracerResultParser(userOperation, tracerResult, res, this.entryPoint.toLowerCase() as Address)
+
+ // const [contractAddresses, storageMap] = tracerResultParser(userOp, tracerResult, res, this.entryPoint)
+
+ if ((res as any) === "0x") {
+ throw new Error("simulateValidation reverted with no revert string!")
+ }
+ return res
+ }
+
+ const errorResult = await entryPointContract.simulate.simulateValidation([userOperation]).catch((e) => {
+ if (e instanceof Error) {
+ return e
+ }
+ throw e
+ })
+
+ // @ts-ignore
+ return getSimulationResult(errorResult, this.logger, "validation", this.usingTenderly)
+ }
+
+ _parseErrorResult(
+ userOp: UserOperation,
+ errorResult: { errorName: string; errorArgs: any }
+ ): ValidationResult | ValidationResultWithAggregation {
+ if (!errorResult?.errorName?.startsWith("ValidationResult")) {
+ // parse it as FailedOp
+ // if its FailedOp, then we have the paymaster param... otherwise its an Error(string)
+ let paymaster = errorResult.errorArgs.paymaster
+ if (paymaster === zeroAddress) {
+ paymaster = undefined
+ }
+
+ // eslint-disable-next-line
+ const msg: string = errorResult.errorArgs[1] ?? errorResult.toString()
+
+ if (paymaster == null) {
+ throw new RpcError(`account validation failed: ${msg}`, ValidationErrors.SimulateValidation)
+ }
+ throw new RpcError(`paymaster validation failed: ${msg}`, ValidationErrors.SimulatePaymasterValidation, {
+ paymaster
+ })
+ }
+
+ const [
+ returnInfo,
+ senderInfo,
+ factoryInfo,
+ paymasterInfo,
+ aggregatorInfo // may be missing (exists only SimulationResultWithAggregator | ) in comment |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -94,9 +95,9 @@ export const validationResultSchema = z
.regex(hexPattern)
.transform((val) => val as HexData)
}),
- stakeInfoSchema,
- stakeInfoSchema,
- stakeInfoSchema
+ stakeInfoSchema.optional(), | is it actually optional? i thought it's always there |
alto | github_2023 | others | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,46 @@
+{
+ "$schema": "./node_modules/rome/configuration_schema.json", | rome? |
alto | github_2023 | others | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,46 @@
+{
+ "$schema": "./node_modules/rome/configuration_schema.json",
+ "files": {
+ "ignore": [
+ "node_modules",
+ "**/node_modules",
+ "CHANGELOG.md",
+ "cache",
+ "coverage",
+ "dist",
+ "tsconfig.json",
+ "tsconfig.*.json",
+ "generated.ts",
+ "pnpm-lock.yaml",
+ "**/**/lib",
+ ".nyc_output",
+ "spec-tests"
+ ]
+ },
+ "organizeImports": {
+ "enabled": true
+ },
+ "linter": {
+ "ignore": ["**/**/*.test.ts"],
+ "enabled": true,
+ "rules": {
+ "all": true,
+ "suspicious": {
+ "noExplicitAny": "warn"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": true,
+ "lineWidth": 80, | bruh gimme some more line width |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -46,6 +46,11 @@ export const bundlerArgsSchema = z.object({
logLevel: z.enum(["trace", "debug", "info", "warn", "error", "fatal"]),
logEnvironment: z.enum(["production", "development"]),
+ bundleMode: z.enum(["auto", "manual"]),
+ bundleFequencey: z.number().int().min(0), | typo |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -47,16 +67,82 @@ export class ExecutorManager {
this.logger = logger
this.metrics = metrics
- setInterval(async () => {
- await this.bundle()
- }, 1000)
+ if (bundleMode === "auto") {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, bundleFequencey)
+ }
+ }
+
+ setBundlingMode(bundleMode: BundlingMode): void {
+ if (bundleMode === "auto" && !this.timer) {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, 1000) | shouldn't this be using the bundling frequency defined in the config? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -47,16 +67,82 @@ export class ExecutorManager {
this.logger = logger
this.metrics = metrics
- setInterval(async () => {
- await this.bundle()
- }, 1000)
+ if (bundleMode === "auto") {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, bundleFequencey)
+ }
+ }
+
+ setBundlingMode(bundleMode: BundlingMode): void {
+ if (bundleMode === "auto" && !this.timer) {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, 1000)
+ } else if (bundleMode === "manual" && this.timer) {
+ clearInterval(this.timer)
+ this.timer = undefined
+ }
+ }
+
+ async bundleNow(): Promise<Hash> {
+ const ops = await this.mempool.process(5_000_000n, 1)
+ if (ops.length === 0) {
+ throw new Error("no ops to bundle") | why throw an error here? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -47,16 +67,82 @@ export class ExecutorManager {
this.logger = logger
this.metrics = metrics
- setInterval(async () => {
- await this.bundle()
- }, 1000)
+ if (bundleMode === "auto") {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, bundleFequencey)
+ }
+ }
+
+ setBundlingMode(bundleMode: BundlingMode): void {
+ if (bundleMode === "auto" && !this.timer) {
+ this.timer = setInterval(async () => {
+ await this.bundle()
+ }, 1000)
+ } else if (bundleMode === "manual" && this.timer) {
+ clearInterval(this.timer)
+ this.timer = undefined
+ }
+ }
+
+ async bundleNow(): Promise<Hash> {
+ const ops = await this.mempool.process(5_000_000n, 1) | what if the total amount of gas for all pending ops is more than 5m, wouldn't we want to send multiple bundles then? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -38,29 +63,48 @@ export interface Mempool {
* @returns An array of user operations.
*/
dumpSubmittedOps(): SubmittedUserOperation[]
+
+ dumpOutstanding(): UserOperationInfo[] | dumpOutstandingOps, no? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -128,69 +205,455 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- add(op: UserOperation) {
- const allOps = [
- ...this.store.dumpOutstanding(),
+ async checkReputationAndMultipleRolesViolation(
+ op: UserOperation,
+ validationResult: ValidationResult
+ ): Promise<void> {
+ if (!this.safeMode) return
+ await this.reputationManager.checkReputation(op, validationResult)
+
+ const knownEntities = this.getKnownEntities()
+
+ if (
+ knownEntities.paymasters.has(op.sender.toLowerCase() as Address) ||
+ knownEntities.facotries.has(op.sender.toLowerCase() as Address)
+ ) {
+ throw new RpcError( | but we should allow multiple ops per sender & paymaster, no? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -128,69 +205,455 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- add(op: UserOperation) {
- const allOps = [
- ...this.store.dumpOutstanding(),
+ async checkReputationAndMultipleRolesViolation( | weird name |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -128,69 +205,455 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- add(op: UserOperation) {
- const allOps = [
- ...this.store.dumpOutstanding(),
+ async checkReputationAndMultipleRolesViolation(
+ op: UserOperation,
+ validationResult: ValidationResult
+ ): Promise<void> {
+ if (!this.safeMode) return
+ await this.reputationManager.checkReputation(op, validationResult)
+
+ const knownEntities = this.getKnownEntities()
+
+ if (
+ knownEntities.paymasters.has(op.sender.toLowerCase() as Address) || | can we always just use the checksummed versions? when we parse using Zod we use getAddress so if it's validated it should be checksummed. I don't really like relying on lowerCase() |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -128,69 +205,455 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- add(op: UserOperation) {
- const allOps = [
- ...this.store.dumpOutstanding(),
+ async checkReputationAndMultipleRolesViolation(
+ op: UserOperation,
+ validationResult: ValidationResult
+ ): Promise<void> {
+ if (!this.safeMode) return
+ await this.reputationManager.checkReputation(op, validationResult)
+
+ const knownEntities = this.getKnownEntities()
+
+ if (
+ knownEntities.paymasters.has(op.sender.toLowerCase() as Address) ||
+ knownEntities.facotries.has(op.sender.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `The sender address "${op.sender}" is used as a different entity in another UserOperation currently in mempool`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.paymasterAndData
+ )
+
+ if (
+ paymaster &&
+ knownEntities.sender.has(paymaster.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Paymaster at ${paymaster} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const factory = getAddressFromInitCodeOrPaymasterAndData(op.initCode)
+
+ if (
+ factory &&
+ knownEntities.sender.has(factory.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Factory at ${factory} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+ }
+
+ getKnownEntities(): {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } {
+ const allOps = [...this.store.dumpOutstanding()]
+
+ const entities: {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } = {
+ sender: new Set(),
+ paymasters: new Set(),
+ facotries: new Set()
+ }
+
+ for (const op of allOps) {
+ entities.sender.add(
+ op.userOperation.sender.toLowerCase() as Address
+ )
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.paymasterAndData
+ )
+ if (paymaster) {
+ entities.paymasters.add(paymaster.toLowerCase() as Address)
+ }
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.initCode
+ )
+ if (factory) {
+ entities.facotries.add(factory.toLowerCase() as Address)
+ }
+ }
+
+ return entities
+ }
+
+ add(op: UserOperation, referencedContracts?: ReferencedCodeHashes) {
+ const outstandingOps = [...this.store.dumpOutstanding()]
+
+ const processedOrSubmittedOps = [
...this.store.dumpProcessing(),
...this.store.dumpSubmitted().map((sop) => sop.userOperation)
]
- if (allOps.find((uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce)) {
+
+ if (
+ processedOrSubmittedOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ ) {
return false
}
- const hash = getUserOperationHash(op, this.entryPointAddress, this.publicClient.chain.id)
+ this.reputationManager.updateUserOperationSeenStatus(op)
+ const oldUserOp = outstandingOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ if (oldUserOp) {
+ const oldMaxPriorityFeePerGas =
+ oldUserOp.userOperation.maxPriorityFeePerGas
+ const newMaxPriorityFeePerGas = op.maxPriorityFeePerGas
+ const oldMaxFeePerGas = oldUserOp.userOperation.maxFeePerGas
+ const newMaxFeePerGas = op.maxFeePerGas
+
+ const incrementMaxPriorityFeePerGas =
+ (oldMaxPriorityFeePerGas * BigInt(10)) / BigInt(100)
+ const incrementMaxFeePerGas =
+ (oldMaxFeePerGas * BigInt(10)) / BigInt(100)
+
+ if (
+ newMaxPriorityFeePerGas <
+ oldMaxPriorityFeePerGas + incrementMaxPriorityFeePerGas ||
+ newMaxFeePerGas < oldMaxFeePerGas + incrementMaxFeePerGas
+ ) {
+ return false
+ }
+
+ this.store.removeOutstanding(oldUserOp.userOperationHash)
+ }
+
+ const hash = getUserOperationHash(
+ op,
+ this.entryPointAddress,
+ this.publicClient.chain.id
+ )
this.store.addOutstanding({
userOperation: op,
userOperationHash: hash,
- firstSubmitted: Date.now(),
- lastReplaced: Date.now()
+ firstSubmitted: oldUserOp ? oldUserOp.firstSubmitted : Date.now(),
+ lastReplaced: Date.now(),
+ referencedContracts
+ })
+ this.monitor.setUserOperationStatus(hash, {
+ status: "not_submitted",
+ transactionHash: null
})
- this.monitor.setUserOperationStatus(hash, { status: "not_submitted", transactionHash: null })
return true
}
- process(maxGasLimit?: bigint, minOps?: number): UserOperation[] {
- const outstandingUserOperations = this.store.dumpOutstanding().slice()
- if (maxGasLimit) {
- let opsTaken = 0
- let gasUsed = 0n
- const result: UserOperation[] = []
- for (const opInfo of outstandingUserOperations) {
- gasUsed +=
- opInfo.userOperation.callGasLimit +
- opInfo.userOperation.verificationGasLimit * 3n +
- opInfo.userOperation.preVerificationGas
- if (gasUsed > maxGasLimit && opsTaken >= (minOps || 0)) {
- break
+ async shouldSkip(
+ opInfo: UserOperationInfo,
+ paymasterDeposit: { [paymaster: string]: bigint },
+ stakedEntityCount: { [addr: string]: number },
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ },
+ senders: Set<string>,
+ storageMap: StorageMap
+ ): Promise<{
+ skip: boolean
+ paymasterDeposit: { [paymaster: string]: bigint }
+ stakedEntityCount: { [addr: string]: number }
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ }
+ senders: Set<string>
+ storageMap: StorageMap
+ }> {
+ if (!this.safeMode) {
+ return {
+ skip: false,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.paymasterAndData
+ )?.toLowerCase() as Address | undefined
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.initCode
+ )?.toLowerCase() as Address | undefined
+ const paymasterStatus = this.reputationManager.getStatus(paymaster)
+ const factoryStatus = this.reputationManager.getStatus(factory)
+
+ if (
+ paymasterStatus === ReputationStatuses.BANNED ||
+ factoryStatus === ReputationStatuses.BANNED
+ ) {
+ this.store.removeOutstanding(opInfo.userOperationHash)
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (
+ paymasterStatus === ReputationStatuses.THROTTLED &&
+ paymaster &&
+ stakedEntityCount[paymaster] >= this.throttledEntityBundleCount
+ ) {
+ this.logger.info( | sounds like it should be a debug or trace log no? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -128,69 +205,455 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- add(op: UserOperation) {
- const allOps = [
- ...this.store.dumpOutstanding(),
+ async checkReputationAndMultipleRolesViolation(
+ op: UserOperation,
+ validationResult: ValidationResult
+ ): Promise<void> {
+ if (!this.safeMode) return
+ await this.reputationManager.checkReputation(op, validationResult)
+
+ const knownEntities = this.getKnownEntities()
+
+ if (
+ knownEntities.paymasters.has(op.sender.toLowerCase() as Address) ||
+ knownEntities.facotries.has(op.sender.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `The sender address "${op.sender}" is used as a different entity in another UserOperation currently in mempool`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.paymasterAndData
+ )
+
+ if (
+ paymaster &&
+ knownEntities.sender.has(paymaster.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Paymaster at ${paymaster} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const factory = getAddressFromInitCodeOrPaymasterAndData(op.initCode)
+
+ if (
+ factory &&
+ knownEntities.sender.has(factory.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Factory at ${factory} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+ }
+
+ getKnownEntities(): {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } {
+ const allOps = [...this.store.dumpOutstanding()]
+
+ const entities: {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } = {
+ sender: new Set(),
+ paymasters: new Set(),
+ facotries: new Set()
+ }
+
+ for (const op of allOps) {
+ entities.sender.add(
+ op.userOperation.sender.toLowerCase() as Address
+ )
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.paymasterAndData
+ )
+ if (paymaster) {
+ entities.paymasters.add(paymaster.toLowerCase() as Address)
+ }
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.initCode
+ )
+ if (factory) {
+ entities.facotries.add(factory.toLowerCase() as Address)
+ }
+ }
+
+ return entities
+ }
+
+ add(op: UserOperation, referencedContracts?: ReferencedCodeHashes) {
+ const outstandingOps = [...this.store.dumpOutstanding()]
+
+ const processedOrSubmittedOps = [
...this.store.dumpProcessing(),
...this.store.dumpSubmitted().map((sop) => sop.userOperation)
]
- if (allOps.find((uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce)) {
+
+ if (
+ processedOrSubmittedOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ ) {
return false
}
- const hash = getUserOperationHash(op, this.entryPointAddress, this.publicClient.chain.id)
+ this.reputationManager.updateUserOperationSeenStatus(op)
+ const oldUserOp = outstandingOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ if (oldUserOp) {
+ const oldMaxPriorityFeePerGas =
+ oldUserOp.userOperation.maxPriorityFeePerGas
+ const newMaxPriorityFeePerGas = op.maxPriorityFeePerGas
+ const oldMaxFeePerGas = oldUserOp.userOperation.maxFeePerGas
+ const newMaxFeePerGas = op.maxFeePerGas
+
+ const incrementMaxPriorityFeePerGas =
+ (oldMaxPriorityFeePerGas * BigInt(10)) / BigInt(100)
+ const incrementMaxFeePerGas =
+ (oldMaxFeePerGas * BigInt(10)) / BigInt(100)
+
+ if (
+ newMaxPriorityFeePerGas <
+ oldMaxPriorityFeePerGas + incrementMaxPriorityFeePerGas ||
+ newMaxFeePerGas < oldMaxFeePerGas + incrementMaxFeePerGas
+ ) {
+ return false
+ }
+
+ this.store.removeOutstanding(oldUserOp.userOperationHash)
+ }
+
+ const hash = getUserOperationHash(
+ op,
+ this.entryPointAddress,
+ this.publicClient.chain.id
+ )
this.store.addOutstanding({
userOperation: op,
userOperationHash: hash,
- firstSubmitted: Date.now(),
- lastReplaced: Date.now()
+ firstSubmitted: oldUserOp ? oldUserOp.firstSubmitted : Date.now(),
+ lastReplaced: Date.now(),
+ referencedContracts
+ })
+ this.monitor.setUserOperationStatus(hash, {
+ status: "not_submitted",
+ transactionHash: null
})
- this.monitor.setUserOperationStatus(hash, { status: "not_submitted", transactionHash: null })
return true
}
- process(maxGasLimit?: bigint, minOps?: number): UserOperation[] {
- const outstandingUserOperations = this.store.dumpOutstanding().slice()
- if (maxGasLimit) {
- let opsTaken = 0
- let gasUsed = 0n
- const result: UserOperation[] = []
- for (const opInfo of outstandingUserOperations) {
- gasUsed +=
- opInfo.userOperation.callGasLimit +
- opInfo.userOperation.verificationGasLimit * 3n +
- opInfo.userOperation.preVerificationGas
- if (gasUsed > maxGasLimit && opsTaken >= (minOps || 0)) {
- break
+ async shouldSkip(
+ opInfo: UserOperationInfo,
+ paymasterDeposit: { [paymaster: string]: bigint },
+ stakedEntityCount: { [addr: string]: number },
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ },
+ senders: Set<string>,
+ storageMap: StorageMap
+ ): Promise<{
+ skip: boolean
+ paymasterDeposit: { [paymaster: string]: bigint }
+ stakedEntityCount: { [addr: string]: number }
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ }
+ senders: Set<string>
+ storageMap: StorageMap
+ }> {
+ if (!this.safeMode) {
+ return {
+ skip: false,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.paymasterAndData
+ )?.toLowerCase() as Address | undefined
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.initCode
+ )?.toLowerCase() as Address | undefined
+ const paymasterStatus = this.reputationManager.getStatus(paymaster)
+ const factoryStatus = this.reputationManager.getStatus(factory)
+
+ if (
+ paymasterStatus === ReputationStatuses.BANNED ||
+ factoryStatus === ReputationStatuses.BANNED
+ ) {
+ this.store.removeOutstanding(opInfo.userOperationHash)
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (
+ paymasterStatus === ReputationStatuses.THROTTLED &&
+ paymaster &&
+ stakedEntityCount[paymaster] >= this.throttledEntityBundleCount
+ ) {
+ this.logger.info(
+ {
+ paymaster,
+ opHash: opInfo.userOperationHash
+ },
+ "Throttled paymaster skipped"
+ )
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (
+ factoryStatus === ReputationStatuses.THROTTLED &&
+ factory &&
+ stakedEntityCount[factory] >= this.throttledEntityBundleCount
+ ) {
+ this.logger.info( | same here |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -128,69 +205,455 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- add(op: UserOperation) {
- const allOps = [
- ...this.store.dumpOutstanding(),
+ async checkReputationAndMultipleRolesViolation(
+ op: UserOperation,
+ validationResult: ValidationResult
+ ): Promise<void> {
+ if (!this.safeMode) return
+ await this.reputationManager.checkReputation(op, validationResult)
+
+ const knownEntities = this.getKnownEntities()
+
+ if (
+ knownEntities.paymasters.has(op.sender.toLowerCase() as Address) ||
+ knownEntities.facotries.has(op.sender.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `The sender address "${op.sender}" is used as a different entity in another UserOperation currently in mempool`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.paymasterAndData
+ )
+
+ if (
+ paymaster &&
+ knownEntities.sender.has(paymaster.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Paymaster at ${paymaster} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const factory = getAddressFromInitCodeOrPaymasterAndData(op.initCode)
+
+ if (
+ factory &&
+ knownEntities.sender.has(factory.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Factory at ${factory} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+ }
+
+ getKnownEntities(): {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } {
+ const allOps = [...this.store.dumpOutstanding()]
+
+ const entities: {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } = {
+ sender: new Set(),
+ paymasters: new Set(),
+ facotries: new Set()
+ }
+
+ for (const op of allOps) {
+ entities.sender.add(
+ op.userOperation.sender.toLowerCase() as Address
+ )
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.paymasterAndData
+ )
+ if (paymaster) {
+ entities.paymasters.add(paymaster.toLowerCase() as Address)
+ }
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.initCode
+ )
+ if (factory) {
+ entities.facotries.add(factory.toLowerCase() as Address)
+ }
+ }
+
+ return entities
+ }
+
+ add(op: UserOperation, referencedContracts?: ReferencedCodeHashes) {
+ const outstandingOps = [...this.store.dumpOutstanding()]
+
+ const processedOrSubmittedOps = [
...this.store.dumpProcessing(),
...this.store.dumpSubmitted().map((sop) => sop.userOperation)
]
- if (allOps.find((uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce)) {
+
+ if (
+ processedOrSubmittedOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ ) {
return false
}
- const hash = getUserOperationHash(op, this.entryPointAddress, this.publicClient.chain.id)
+ this.reputationManager.updateUserOperationSeenStatus(op)
+ const oldUserOp = outstandingOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ if (oldUserOp) {
+ const oldMaxPriorityFeePerGas =
+ oldUserOp.userOperation.maxPriorityFeePerGas
+ const newMaxPriorityFeePerGas = op.maxPriorityFeePerGas
+ const oldMaxFeePerGas = oldUserOp.userOperation.maxFeePerGas
+ const newMaxFeePerGas = op.maxFeePerGas
+
+ const incrementMaxPriorityFeePerGas =
+ (oldMaxPriorityFeePerGas * BigInt(10)) / BigInt(100)
+ const incrementMaxFeePerGas =
+ (oldMaxFeePerGas * BigInt(10)) / BigInt(100)
+
+ if (
+ newMaxPriorityFeePerGas <
+ oldMaxPriorityFeePerGas + incrementMaxPriorityFeePerGas ||
+ newMaxFeePerGas < oldMaxFeePerGas + incrementMaxFeePerGas
+ ) {
+ return false
+ }
+
+ this.store.removeOutstanding(oldUserOp.userOperationHash)
+ }
+
+ const hash = getUserOperationHash(
+ op,
+ this.entryPointAddress,
+ this.publicClient.chain.id
+ )
this.store.addOutstanding({
userOperation: op,
userOperationHash: hash,
- firstSubmitted: Date.now(),
- lastReplaced: Date.now()
+ firstSubmitted: oldUserOp ? oldUserOp.firstSubmitted : Date.now(),
+ lastReplaced: Date.now(),
+ referencedContracts
+ })
+ this.monitor.setUserOperationStatus(hash, {
+ status: "not_submitted",
+ transactionHash: null
})
- this.monitor.setUserOperationStatus(hash, { status: "not_submitted", transactionHash: null })
return true
}
- process(maxGasLimit?: bigint, minOps?: number): UserOperation[] {
- const outstandingUserOperations = this.store.dumpOutstanding().slice()
- if (maxGasLimit) {
- let opsTaken = 0
- let gasUsed = 0n
- const result: UserOperation[] = []
- for (const opInfo of outstandingUserOperations) {
- gasUsed +=
- opInfo.userOperation.callGasLimit +
- opInfo.userOperation.verificationGasLimit * 3n +
- opInfo.userOperation.preVerificationGas
- if (gasUsed > maxGasLimit && opsTaken >= (minOps || 0)) {
- break
+ async shouldSkip(
+ opInfo: UserOperationInfo,
+ paymasterDeposit: { [paymaster: string]: bigint },
+ stakedEntityCount: { [addr: string]: number },
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ },
+ senders: Set<string>,
+ storageMap: StorageMap
+ ): Promise<{
+ skip: boolean
+ paymasterDeposit: { [paymaster: string]: bigint }
+ stakedEntityCount: { [addr: string]: number }
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ }
+ senders: Set<string>
+ storageMap: StorageMap
+ }> {
+ if (!this.safeMode) {
+ return {
+ skip: false,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.paymasterAndData
+ )?.toLowerCase() as Address | undefined
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.initCode
+ )?.toLowerCase() as Address | undefined
+ const paymasterStatus = this.reputationManager.getStatus(paymaster)
+ const factoryStatus = this.reputationManager.getStatus(factory)
+
+ if (
+ paymasterStatus === ReputationStatuses.BANNED ||
+ factoryStatus === ReputationStatuses.BANNED
+ ) {
+ this.store.removeOutstanding(opInfo.userOperationHash)
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (
+ paymasterStatus === ReputationStatuses.THROTTLED &&
+ paymaster &&
+ stakedEntityCount[paymaster] >= this.throttledEntityBundleCount
+ ) {
+ this.logger.info(
+ {
+ paymaster,
+ opHash: opInfo.userOperationHash
+ },
+ "Throttled paymaster skipped"
+ )
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (
+ factoryStatus === ReputationStatuses.THROTTLED &&
+ factory &&
+ stakedEntityCount[factory] >= this.throttledEntityBundleCount
+ ) {
+ this.logger.info(
+ {
+ factory,
+ opHash: opInfo.userOperationHash
+ },
+ "Throttled factory skipped"
+ )
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (senders.has(opInfo.userOperation.sender)) {
+ this.logger.info( | and here |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -128,69 +205,455 @@ export class MemoryMempool implements Mempool {
this.store.removeProcessing(userOpHash)
}
- add(op: UserOperation) {
- const allOps = [
- ...this.store.dumpOutstanding(),
+ async checkReputationAndMultipleRolesViolation(
+ op: UserOperation,
+ validationResult: ValidationResult
+ ): Promise<void> {
+ if (!this.safeMode) return
+ await this.reputationManager.checkReputation(op, validationResult)
+
+ const knownEntities = this.getKnownEntities()
+
+ if (
+ knownEntities.paymasters.has(op.sender.toLowerCase() as Address) ||
+ knownEntities.facotries.has(op.sender.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `The sender address "${op.sender}" is used as a different entity in another UserOperation currently in mempool`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.paymasterAndData
+ )
+
+ if (
+ paymaster &&
+ knownEntities.sender.has(paymaster.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Paymaster at ${paymaster} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const factory = getAddressFromInitCodeOrPaymasterAndData(op.initCode)
+
+ if (
+ factory &&
+ knownEntities.sender.has(factory.toLowerCase() as Address)
+ ) {
+ throw new RpcError(
+ `A Factory at ${factory} in this UserOperation is used as a sender entity in another UserOperation currently in mempool.`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+ }
+
+ getKnownEntities(): {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } {
+ const allOps = [...this.store.dumpOutstanding()]
+
+ const entities: {
+ sender: Set<Address>
+ paymasters: Set<Address>
+ facotries: Set<Address>
+ } = {
+ sender: new Set(),
+ paymasters: new Set(),
+ facotries: new Set()
+ }
+
+ for (const op of allOps) {
+ entities.sender.add(
+ op.userOperation.sender.toLowerCase() as Address
+ )
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.paymasterAndData
+ )
+ if (paymaster) {
+ entities.paymasters.add(paymaster.toLowerCase() as Address)
+ }
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ op.userOperation.initCode
+ )
+ if (factory) {
+ entities.facotries.add(factory.toLowerCase() as Address)
+ }
+ }
+
+ return entities
+ }
+
+ add(op: UserOperation, referencedContracts?: ReferencedCodeHashes) {
+ const outstandingOps = [...this.store.dumpOutstanding()]
+
+ const processedOrSubmittedOps = [
...this.store.dumpProcessing(),
...this.store.dumpSubmitted().map((sop) => sop.userOperation)
]
- if (allOps.find((uo) => uo.userOperation.sender === op.sender && uo.userOperation.nonce === op.nonce)) {
+
+ if (
+ processedOrSubmittedOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ ) {
return false
}
- const hash = getUserOperationHash(op, this.entryPointAddress, this.publicClient.chain.id)
+ this.reputationManager.updateUserOperationSeenStatus(op)
+ const oldUserOp = outstandingOps.find(
+ (uo) =>
+ uo.userOperation.sender === op.sender &&
+ uo.userOperation.nonce === op.nonce
+ )
+ if (oldUserOp) {
+ const oldMaxPriorityFeePerGas =
+ oldUserOp.userOperation.maxPriorityFeePerGas
+ const newMaxPriorityFeePerGas = op.maxPriorityFeePerGas
+ const oldMaxFeePerGas = oldUserOp.userOperation.maxFeePerGas
+ const newMaxFeePerGas = op.maxFeePerGas
+
+ const incrementMaxPriorityFeePerGas =
+ (oldMaxPriorityFeePerGas * BigInt(10)) / BigInt(100)
+ const incrementMaxFeePerGas =
+ (oldMaxFeePerGas * BigInt(10)) / BigInt(100)
+
+ if (
+ newMaxPriorityFeePerGas <
+ oldMaxPriorityFeePerGas + incrementMaxPriorityFeePerGas ||
+ newMaxFeePerGas < oldMaxFeePerGas + incrementMaxFeePerGas
+ ) {
+ return false
+ }
+
+ this.store.removeOutstanding(oldUserOp.userOperationHash)
+ }
+
+ const hash = getUserOperationHash(
+ op,
+ this.entryPointAddress,
+ this.publicClient.chain.id
+ )
this.store.addOutstanding({
userOperation: op,
userOperationHash: hash,
- firstSubmitted: Date.now(),
- lastReplaced: Date.now()
+ firstSubmitted: oldUserOp ? oldUserOp.firstSubmitted : Date.now(),
+ lastReplaced: Date.now(),
+ referencedContracts
+ })
+ this.monitor.setUserOperationStatus(hash, {
+ status: "not_submitted",
+ transactionHash: null
})
- this.monitor.setUserOperationStatus(hash, { status: "not_submitted", transactionHash: null })
return true
}
- process(maxGasLimit?: bigint, minOps?: number): UserOperation[] {
- const outstandingUserOperations = this.store.dumpOutstanding().slice()
- if (maxGasLimit) {
- let opsTaken = 0
- let gasUsed = 0n
- const result: UserOperation[] = []
- for (const opInfo of outstandingUserOperations) {
- gasUsed +=
- opInfo.userOperation.callGasLimit +
- opInfo.userOperation.verificationGasLimit * 3n +
- opInfo.userOperation.preVerificationGas
- if (gasUsed > maxGasLimit && opsTaken >= (minOps || 0)) {
- break
+ async shouldSkip(
+ opInfo: UserOperationInfo,
+ paymasterDeposit: { [paymaster: string]: bigint },
+ stakedEntityCount: { [addr: string]: number },
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ },
+ senders: Set<string>,
+ storageMap: StorageMap
+ ): Promise<{
+ skip: boolean
+ paymasterDeposit: { [paymaster: string]: bigint }
+ stakedEntityCount: { [addr: string]: number }
+ knownEntities: {
+ sender: Set<`0x${string}`>
+ paymasters: Set<`0x${string}`>
+ facotries: Set<`0x${string}`>
+ }
+ senders: Set<string>
+ storageMap: StorageMap
+ }> {
+ if (!this.safeMode) {
+ return {
+ skip: false,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+ const paymaster = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.paymasterAndData
+ )?.toLowerCase() as Address | undefined
+ const factory = getAddressFromInitCodeOrPaymasterAndData(
+ opInfo.userOperation.initCode
+ )?.toLowerCase() as Address | undefined
+ const paymasterStatus = this.reputationManager.getStatus(paymaster)
+ const factoryStatus = this.reputationManager.getStatus(factory)
+
+ if (
+ paymasterStatus === ReputationStatuses.BANNED ||
+ factoryStatus === ReputationStatuses.BANNED
+ ) {
+ this.store.removeOutstanding(opInfo.userOperationHash)
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (
+ paymasterStatus === ReputationStatuses.THROTTLED &&
+ paymaster &&
+ stakedEntityCount[paymaster] >= this.throttledEntityBundleCount
+ ) {
+ this.logger.info(
+ {
+ paymaster,
+ opHash: opInfo.userOperationHash
+ },
+ "Throttled paymaster skipped"
+ )
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (
+ factoryStatus === ReputationStatuses.THROTTLED &&
+ factory &&
+ stakedEntityCount[factory] >= this.throttledEntityBundleCount
+ ) {
+ this.logger.info(
+ {
+ factory,
+ opHash: opInfo.userOperationHash
+ },
+ "Throttled factory skipped"
+ )
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ if (senders.has(opInfo.userOperation.sender)) {
+ this.logger.info(
+ {
+ sender: opInfo.userOperation.sender,
+ opHash: opInfo.userOperationHash
+ },
+ "Sender skipped because already included in bundle"
+ )
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ let validationResult: ValidationResult & { storageMap: StorageMap }
+
+ try {
+ validationResult = await this.validator.validateUserOperation(
+ opInfo.userOperation,
+ opInfo.referencedContracts
+ )
+ } catch (e) {
+ this.logger.error(
+ {
+ opHash: opInfo.userOperationHash,
+ error: JSON.stringify(e)
+ },
+ "2nd Validation error"
+ )
+ this.store.removeOutstanding(opInfo.userOperationHash)
+ return {
+ skip: true,
+ paymasterDeposit,
+ stakedEntityCount,
+ knownEntities,
+ senders,
+ storageMap
+ }
+ }
+
+ for (const storageAddress of Object.keys(validationResult.storageMap)) {
+ if (
+ storageAddress.toLowerCase() !==
+ opInfo.userOperation.sender.toLowerCase() &&
+ knownEntities.sender.has(
+ storageAddress.toLowerCase() as Address
+ )
+ ) {
+ this.logger.info( | and here |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,603 @@
+import {
+ EntryPointAbi,
+ RpcError,
+ StakeInfo,
+ UserOperation,
+ ValidationErrors,
+ ValidationResult,
+ ValidationResultWithAggregation
+} from "@alto/types"
+import { Logger, getAddressFromInitCodeOrPaymasterAndData } from "@alto/utils"
+import { Address, PublicClient, getContract } from "viem"
+
+export interface IReputationManager {
+ checkReputation(
+ userOperation: UserOperation,
+ validationResult: ValidationResult | ValidationResultWithAggregation
+ ): Promise<void>
+ updateUserOperationSeenStatus(userOperation: UserOperation): void
+ increaseUserOperationCount(userOperation: UserOperation): void
+ decreaseUserOperationCount(userOperation: UserOperation): void
+ getStatus(address?: Address): ReputationStatus
+ updateUserOperationIncludedStatus(
+ userOperation: UserOperation,
+ accountDeployed: boolean
+ ): void
+ crashedHandleOps(userOperation: UserOperation, reason: string): void
+ setReputation(
+ args: {
+ address: Address
+ opsSeen: bigint
+ opsIncluded: bigint
+ }[]
+ ): void
+ dumpReputations(): ReputationEntry[]
+ getStakeStatus(address: Address): Promise<{
+ stakeInfo: StakeInfo
+ isStaked: boolean
+ }>
+ clear(): void
+ clearEntityCount(): void
+}
+
+export enum EntityType {
+ ACCOUNT = "Account",
+ PAYMASTER = "Paymaster",
+ FACTORY = "Factory",
+ AGGREGATOR = "Aggregator"
+}
+
+export type ReputationStatus = 0n | 1n | 2n
+export const ReputationStatuses: {
+ OK: ReputationStatus,
+ THROTTLED: ReputationStatus,
+ BANNED: ReputationStatus
+} = {
+ OK: 0n, | why bigint? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,603 @@
+import {
+ EntryPointAbi,
+ RpcError,
+ StakeInfo,
+ UserOperation,
+ ValidationErrors,
+ ValidationResult,
+ ValidationResultWithAggregation
+} from "@alto/types"
+import { Logger, getAddressFromInitCodeOrPaymasterAndData } from "@alto/utils"
+import { Address, PublicClient, getContract } from "viem"
+
+export interface IReputationManager {
+ checkReputation(
+ userOperation: UserOperation,
+ validationResult: ValidationResult | ValidationResultWithAggregation
+ ): Promise<void>
+ updateUserOperationSeenStatus(userOperation: UserOperation): void
+ increaseUserOperationCount(userOperation: UserOperation): void
+ decreaseUserOperationCount(userOperation: UserOperation): void
+ getStatus(address?: Address): ReputationStatus
+ updateUserOperationIncludedStatus(
+ userOperation: UserOperation,
+ accountDeployed: boolean
+ ): void
+ crashedHandleOps(userOperation: UserOperation, reason: string): void
+ setReputation(
+ args: {
+ address: Address
+ opsSeen: bigint
+ opsIncluded: bigint
+ }[]
+ ): void
+ dumpReputations(): ReputationEntry[]
+ getStakeStatus(address: Address): Promise<{
+ stakeInfo: StakeInfo
+ isStaked: boolean
+ }>
+ clear(): void
+ clearEntityCount(): void
+}
+
+export enum EntityType {
+ ACCOUNT = "Account",
+ PAYMASTER = "Paymaster",
+ FACTORY = "Factory",
+ AGGREGATOR = "Aggregator"
+}
+
+export type ReputationStatus = 0n | 1n | 2n
+export const ReputationStatuses: {
+ OK: ReputationStatus,
+ THROTTLED: ReputationStatus,
+ BANNED: ReputationStatus
+} = {
+ OK: 0n,
+ THROTTLED: 1n,
+ BANNED: 2n
+}
+
+export interface ReputationEntry {
+ address: Address
+ opsSeen: bigint
+ opsIncluded: bigint
+ status?: ReputationStatus
+}
+
+export interface ReputationParams {
+ minInclusionDenominator: bigint
+ throttlingSlack: bigint
+ banSlack: bigint
+}
+
+export const BundlerReputationParams: ReputationParams = {
+ minInclusionDenominator: 10n,
+ throttlingSlack: 10n,
+ banSlack: 50n
+}
+
+export class NullRepuationManager implements IReputationManager {
+ async checkReputation(
+ userOperation: UserOperation,
+ validationResult: ValidationResult | ValidationResultWithAggregation
+ ): Promise<void> {
+ return
+ }
+
+ increaseUserOperationCount(_: UserOperation): void {
+ return
+ }
+
+ decreaseUserOperationCount(_: UserOperation): void {
+ return
+ }
+
+ updateUserOperationSeenStatus(_: UserOperation): void {
+ return
+ }
+
+ updateUserOperationIncludedStatus(_: UserOperation, __: boolean): void {
+ return
+ }
+
+ crashedHandleOps(_: UserOperation, __: string): void {
+ return
+ }
+
+ setReputation(
+ _: {
+ address: Address
+ opsSeen: bigint
+ opsIncluded: bigint
+ }[]
+ ): void {
+ return
+ }
+
+ dumpReputations(): ReputationEntry[] {
+ return []
+ }
+
+ getStatus(_address?: `0x${string}` | undefined): ReputationStatus {
+ throw new Error("Method not implemented.")
+ }
+
+ getStakeStatus(_: Address): Promise<{
+ stakeInfo: StakeInfo
+ isStaked: boolean
+ }> {
+ throw new Error("Method not implemented.")
+ }
+
+ clear(): void {
+ return
+ }
+
+ clearEntityCount(): void {
+ return
+ }
+}
+
+export class ReputationManager implements IReputationManager {
+ private publicClient: PublicClient
+ private entryPoint: Address
+ private minStake: bigint
+ private minUnstakeDelay: bigint
+ private entityCount: { [address: Address]: bigint } = {}
+ private throttledEntityMinMempoolCount: bigint
+ private maxMempoolUserOperationsPerSender: bigint
+ private maxMempoolUserOperationsPerNewUnstakedEntity: bigint
+ private inclusionRateFactor: bigint
+ private entries: { [address: Address]: ReputationEntry } = {}
+ private whitelist: Set<Address> = new Set()
+ private blackList: Set<Address> = new Set()
+ private bundlerReputationParams: ReputationParams
+ private logger: Logger
+
+ constructor(
+ publicClient: PublicClient,
+ entryPoint: Address,
+ minStake: bigint,
+ minUnstakeDelay: bigint,
+ logger: Logger,
+ maxMempoolUserOperationsPerNewUnstakedEntity?: bigint,
+ throttledEntityMinMempoolCount?: bigint,
+ inclusionRateFactor?: bigint,
+ maxMempoolUserOperationsPerSender?: bigint,
+ blackList?: Address[],
+ whiteList?: Address[],
+ bundlerReputationParams?: ReputationParams
+ ) {
+ this.publicClient = publicClient
+ this.entryPoint = entryPoint
+ this.minStake = minStake
+ this.minUnstakeDelay = minUnstakeDelay
+ this.logger = logger
+ this.maxMempoolUserOperationsPerNewUnstakedEntity =
+ maxMempoolUserOperationsPerNewUnstakedEntity ?? 10n
+ this.inclusionRateFactor = inclusionRateFactor ?? 10n
+ this.throttledEntityMinMempoolCount =
+ throttledEntityMinMempoolCount ?? 4n
+ this.maxMempoolUserOperationsPerSender =
+ maxMempoolUserOperationsPerSender ?? 4n
+ this.bundlerReputationParams =
+ bundlerReputationParams ?? BundlerReputationParams
+ for (const address of blackList || []) {
+ this.blackList.add(address.toLowerCase() as Address)
+ }
+ for (const address of whiteList || []) {
+ this.whitelist.add(address.toLowerCase() as Address)
+ }
+ }
+
+ setReputation(
+ reputations: {
+ address: Address
+ opsSeen: bigint
+ opsIncluded: bigint
+ }[]
+ ): void {
+ for (const reputation of reputations) {
+ const address = reputation.address.toLowerCase() as Address
+ this.entries[address] = {
+ address: reputation.address,
+ opsSeen: BigInt(reputation.opsSeen),
+ opsIncluded: BigInt(reputation.opsIncluded)
+ }
+ }
+ this.logger.debug(
+ {
+ reputations: this.entries
+ },
+ "Reputation set"
+ )
+ }
+
+ dumpReputations(): ReputationEntry[] {
+ return Object.values(this.entries).map((entry) => ({
+ ...entry,
+ status: this.getStatus(entry.address)
+ }))
+ }
+
+ clear(): void {
+ this.entries = {}
+ this.entityCount = {}
+ }
+
+ clearEntityCount(): void {
+ this.entityCount = {}
+ }
+
+ async getStakeStatus(address: Address): Promise<{
+ stakeInfo: StakeInfo
+ isStaked: boolean
+ }> {
+ const entryPoint = getContract({
+ abi: EntryPointAbi,
+ address: this.entryPoint,
+ publicClient: this.publicClient
+ })
+ const stakeInfo = await entryPoint.read.getDepositInfo([address])
+
+ const stake = BigInt(stakeInfo.stake)
+ const unstakeDelaySec = BigInt(stakeInfo.unstakeDelaySec)
+
+ const isStaked =
+ stake >= this.minStake && unstakeDelaySec >= this.minUnstakeDelay
+
+ return {
+ stakeInfo: {
+ addr: address,
+ stake: stake,
+ unstakeDelaySec: unstakeDelaySec
+ },
+ isStaked
+ }
+ }
+
+ async checkReputation(
+ userOperation: UserOperation,
+ validationResult: ValidationResult | ValidationResultWithAggregation
+ ): Promise<void> {
+ this.increaseUserOperationCount(userOperation)
+
+ this.checkReputationStatus(
+ EntityType.ACCOUNT,
+ validationResult.senderInfo,
+ this.maxMempoolUserOperationsPerSender
+ )
+
+ if (validationResult.paymasterInfo) {
+ this.checkReputationStatus(
+ EntityType.PAYMASTER,
+ validationResult.paymasterInfo
+ )
+ }
+
+ if (validationResult.factoryInfo) {
+ this.checkReputationStatus(
+ EntityType.FACTORY,
+ validationResult.factoryInfo
+ )
+ }
+
+ const aggregaorValidationResult =
+ validationResult as ValidationResultWithAggregation
+ if (aggregaorValidationResult.aggregatorInfo) {
+ this.checkReputationStatus(
+ EntityType.AGGREGATOR,
+ aggregaorValidationResult.aggregatorInfo.stakeInfo
+ )
+ }
+ }
+
+ getEntityCount(address: Address): bigint {
+ return this.entityCount[address.toLowerCase() as Address] ?? 0
+ }
+
+ increaseSeen(address: Address): void {
+ const entry = this.entries[address.toLowerCase() as Address]
+ if (!entry) {
+ this.entries[address.toLowerCase() as Address] = {
+ address,
+ opsSeen: 1n, | why bigint?
|
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,756 @@
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+import {
+ Address,
+ Hex,
+ decodeErrorResult,
+ decodeFunctionResult,
+ getFunctionSelector,
+ hexToBigInt,
+ keccak256,
+ pad
+} from "viem"
+import { Abi, AbiFunction } from "abitype"
+import { BundlerTracerResult } from "./BundlerCollectorTracer"
+import {
+ EntryPointAbi,
+ PaymasterAbi,
+ RpcError,
+ SenderCreatorAbi,
+ StakeInfo,
+ StorageMap,
+ UserOperation,
+ ValidationErrors,
+ ValidationResult
+} from "@alto/types"
+
+interface CallEntry {
+ to: string
+ from: string
+ type: string // call opcode
+ method: string // parsed method, or signash if unparsed
+ revert?: any // parsed output from REVERT
+ return?: any // parsed method output.
+ value?: Hex
+}
+
+const abi = [...SenderCreatorAbi, ...EntryPointAbi, ...PaymasterAbi] as Abi
+
+const functionSignatureToMethodName = (hash: any) => {
+ let functionName: string | undefined = undefined
+ for (const item of abi) {
+ const signature = getFunctionSelector(item as AbiFunction)
+ if (signature === hash) {
+ functionName = (item as AbiFunction).name
+ }
+ }
+
+ if (functionName === undefined) {
+ throw new Error(`Could not find function name for hash ${hash}`)
+ }
+
+ return functionName
+}
+
+/**
+ * parse all call operation in the trace.
+ * notes:
+ * - entries are ordered by the return (so nested call appears before its outer call
+ * - last entry is top-level return from "simulateValidation". it as ret and rettype, but no type or address
+ * @param tracerResults
+ * @param abi
+ */
+function parseCallStack(tracerResults: BundlerTracerResult): CallEntry[] {
+ function callCatch<T, T1>(x: () => T, def: T1): T | T1 {
+ try {
+ return x()
+ } catch (_) {
+ return def
+ }
+ }
+
+ const out: CallEntry[] = []
+ const stack: any[] = []
+ const filteredTracerResultCalls = tracerResults.calls.filter(
+ (x) => !x.type.startsWith("depth")
+ )
+
+ for (const c of filteredTracerResultCalls) {
+ if (c.type.match(/REVERT|RETURN/) !== null) {
+ const top = stack.splice(-1)[0] ?? {
+ type: "top",
+ method: "validateUserOp"
+ }
+ const returnData: Hex = (c as any).data
+ if (top.type.match(/CREATE/) !== null) {
+ out.push({
+ to: top.to,
+ from: top.from,
+ type: top.type,
+ method: "",
+ return: `len=${returnData.length}`
+ })
+ } else {
+ const method = callCatch(
+ () => functionSignatureToMethodName(top.method),
+ top.method
+ )
+
+ if (c.type === "REVERT") {
+ const parsedError = callCatch(
+ () => decodeErrorResult({ abi: abi, data: returnData }),
+ returnData
+ )
+ out.push({
+ to: top.to,
+ from: top.from,
+ type: top.type,
+ method: method,
+ value: top.value,
+ revert: parsedError
+ })
+ } else {
+ const ret = callCatch(
+ () =>
+ decodeFunctionResult({
+ abi: abi,
+ functionName: method,
+ data: returnData
+ }),
+ returnData
+ )
+ out.push({
+ to: top.to,
+ from: top.from,
+ type: top.type,
+ value: top.value,
+ method: method,
+ return: ret
+ })
+ }
+ }
+ } else {
+ stack.push(c)
+ }
+ }
+
+ // TODO: verify that stack is empty at the end.
+
+ return out
+}
+
+/**
+ * slots associated with each entity.
+ * keccak( A || ...) is associated with "A"
+ * removed rule: keccak( ... || ASSOC ) (for a previously associated hash) is also associated with "A"
+ *
+ * @param stakeInfoEntities stake info for (factory, account, paymaster). factory and paymaster can be null.
+ * @param keccak array of buffers that were given to keccak in the transaction
+ */
+function parseEntitySlots(
+ stakeInfoEntities: { [addr: string]: StakeInfo | undefined },
+ keccak: Hex[]
+): {
+ [addr: string]: Set<string>
+} {
+ // for each entity (sender, factory, paymaster), hold the valid slot addresses
+ // valid: the slot was generated by keccak(entity || ...)
+ const entitySlots: { [addr: string]: Set<string> } = {}
+
+ for (const k of keccak) {
+ const values = Object.values(stakeInfoEntities)
+ for (const info of values) {
+ const addr = info?.addr?.toLowerCase() as Hex
+ if (!addr) {
+ continue
+ }
+
+ const addrPadded = pad(addr).toLowerCase()
+ if (!entitySlots[addr]) {
+ entitySlots[addr] = new Set<string>()
+ }
+
+ const currentEntitySlots = entitySlots[addr]
+
+ // valid slot: the slot was generated by keccak(entityAddr || ...)
+ if (k.startsWith(addrPadded)) {
+ currentEntitySlots.add(keccak256(k))
+ }
+ // disabled 2nd rule: .. or by keccak( ... || OWN) where OWN is previous allowed slot
+ // if (k.length === 130 && currentEntitySlots.has(k.slice(-64))) {
+ // currentEntitySlots.add(value)
+ // }
+ }
+ }
+
+ return entitySlots
+}
+
+// method-signature for calls from entryPoint
+const callsFromEntryPointMethodSigs: { [key: string]: string } = {
+ factory: getFunctionSelector({
+ inputs: [
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ }
+ ],
+ name: "createSender",
+ outputs: [
+ {
+ internalType: "address",
+ name: "sender",
+ type: "address"
+ }
+ ],
+ stateMutability: "nonpayable",
+ type: "function"
+ }),
+ account: getFunctionSelector({
+ inputs: [
+ {
+ components: [
+ {
+ internalType: "address",
+ name: "sender",
+ type: "address"
+ },
+ {
+ internalType: "uint256",
+ name: "nonce",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "callData",
+ type: "bytes"
+ },
+ {
+ internalType: "uint256",
+ name: "callGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "verificationGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "preVerificationGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxPriorityFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "paymasterAndData",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "signature",
+ type: "bytes"
+ }
+ ],
+ internalType: "struct UserOperation",
+ name: "userOp",
+ type: "tuple"
+ },
+ {
+ internalType: "bytes32",
+ name: "",
+ type: "bytes32"
+ },
+ {
+ internalType: "uint256",
+ name: "missingAccountFunds",
+ type: "uint256"
+ }
+ ],
+ name: "validateUserOp",
+ outputs: [
+ {
+ internalType: "uint256",
+ name: "",
+ type: "uint256"
+ }
+ ],
+ stateMutability: "nonpayable",
+ type: "function"
+ }),
+ paymaster: getFunctionSelector({
+ inputs: [
+ {
+ components: [
+ {
+ internalType: "address",
+ name: "sender",
+ type: "address"
+ },
+ {
+ internalType: "uint256",
+ name: "nonce",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "callData",
+ type: "bytes"
+ },
+ {
+ internalType: "uint256",
+ name: "callGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "verificationGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "preVerificationGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxPriorityFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "paymasterAndData",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "signature",
+ type: "bytes"
+ }
+ ],
+ internalType: "struct UserOperation",
+ name: "userOp",
+ type: "tuple"
+ },
+ {
+ internalType: "bytes32",
+ name: "userOpHash",
+ type: "bytes32"
+ },
+ {
+ internalType: "uint256",
+ name: "maxCost",
+ type: "uint256"
+ }
+ ],
+ name: "validatePaymasterUserOp",
+ outputs: [
+ {
+ internalType: "bytes",
+ name: "context",
+ type: "bytes"
+ },
+ {
+ internalType: "uint256",
+ name: "validationData",
+ type: "uint256"
+ }
+ ],
+ stateMutability: "nonpayable",
+ type: "function"
+ })
+}
+
+/**
+ * parse collected simulation traces and revert if they break our rules
+ * @param userOp the userOperation that was used in this simulation
+ * @param tracerResults the tracer return value
+ * @param validationResult output from simulateValidation
+ * @param entryPoint the entryPoint that hosted the "simulatedValidation" traced call.
+ * @return list of contract addresses referenced by this UserOp
+ */
+export function tracerResultParser(
+ userOp: UserOperation,
+ tracerResults: BundlerTracerResult,
+ validationResult: ValidationResult,
+ entryPointAddress: Address
+): [string[], StorageMap] {
+ // todo: block access to no-code addresses (might need update to tracer)
+
+ // opcodes from [OP-011]
+ const bannedOpCodes = new Set([
+ "GASPRICE",
+ "GASLIMIT",
+ "DIFFICULTY",
+ "TIMESTAMP",
+ "BASEFEE",
+ "BLOCKHASH",
+ "NUMBER",
+ "SELFBALANCE",
+ "BALANCE",
+ "ORIGIN",
+ "GAS",
+ "CREATE",
+ "COINBASE",
+ "SELFDESTRUCT",
+ "RANDOM",
+ "PREVRANDAO",
+ "INVALID"
+ ])
+
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
+ if (Object.values(tracerResults.callsFromEntryPoint).length < 1) {
+ throw new Error(
+ "Unexpected traceCall result: no calls from entrypoint."
+ )
+ }
+ const callStack = parseCallStack(tracerResults)
+
+ // [OP-052], [OP-053]
+ const callInfoEntryPoint = callStack.find(
+ (call) =>
+ call.to === entryPointAddress &&
+ call.from !== entryPointAddress &&
+ call.method !== "0x" &&
+ call.method !== "depositTo"
+ )
+ // [OP-054]
+ if (callInfoEntryPoint) {
+ throw new RpcError(
+ `illegal call into EntryPoint during validation ${callInfoEntryPoint?.method}`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ // [OP-061]
+ const illegalNonZeroValueCall = callStack.find(
+ (call) =>
+ call.to !== entryPointAddress &&
+ hexToBigInt(call.value ?? "0x0") !== 0n
+ )
+
+ if (illegalNonZeroValueCall) {
+ throw new RpcError(
+ "May not may CALL with value",
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const sender = userOp.sender.toLowerCase()
+ // stake info per "number" level (factory, sender, paymaster)
+ // we only use stake info if we notice a memory reference that require stake
+ const stakeInfoEntities = {
+ factory: validationResult.factoryInfo,
+ account: validationResult.senderInfo,
+ paymaster: validationResult.paymasterInfo
+ }
+
+ const entitySlots: { [addr: string]: Set<string> } = parseEntitySlots(
+ stakeInfoEntities,
+ tracerResults.keccak as Hex[]
+ )
+
+ for (const [entityTitle, entStakes] of Object.entries(stakeInfoEntities)) {
+ const entityAddr = (entStakes?.addr ?? "").toLowerCase() | yeah can we also not do lowercasing here? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -0,0 +1,756 @@
+// This file contains references to validation rules, in the format [xxx-###]
+// where xxx is OP/STO/COD/EP/SREP/EREP/UREP/ALT, and ### is a number
+// the validation rules are defined in erc-aa-validation.md
+import {
+ Address,
+ Hex,
+ decodeErrorResult,
+ decodeFunctionResult,
+ getFunctionSelector,
+ hexToBigInt,
+ keccak256,
+ pad
+} from "viem"
+import { Abi, AbiFunction } from "abitype"
+import { BundlerTracerResult } from "./BundlerCollectorTracer"
+import {
+ EntryPointAbi,
+ PaymasterAbi,
+ RpcError,
+ SenderCreatorAbi,
+ StakeInfo,
+ StorageMap,
+ UserOperation,
+ ValidationErrors,
+ ValidationResult
+} from "@alto/types"
+
+interface CallEntry {
+ to: string
+ from: string
+ type: string // call opcode
+ method: string // parsed method, or signash if unparsed
+ revert?: any // parsed output from REVERT
+ return?: any // parsed method output.
+ value?: Hex
+}
+
+const abi = [...SenderCreatorAbi, ...EntryPointAbi, ...PaymasterAbi] as Abi
+
+const functionSignatureToMethodName = (hash: any) => {
+ let functionName: string | undefined = undefined
+ for (const item of abi) {
+ const signature = getFunctionSelector(item as AbiFunction)
+ if (signature === hash) {
+ functionName = (item as AbiFunction).name
+ }
+ }
+
+ if (functionName === undefined) {
+ throw new Error(`Could not find function name for hash ${hash}`)
+ }
+
+ return functionName
+}
+
+/**
+ * parse all call operation in the trace.
+ * notes:
+ * - entries are ordered by the return (so nested call appears before its outer call
+ * - last entry is top-level return from "simulateValidation". it as ret and rettype, but no type or address
+ * @param tracerResults
+ * @param abi
+ */
+function parseCallStack(tracerResults: BundlerTracerResult): CallEntry[] {
+ function callCatch<T, T1>(x: () => T, def: T1): T | T1 {
+ try {
+ return x()
+ } catch (_) {
+ return def
+ }
+ }
+
+ const out: CallEntry[] = []
+ const stack: any[] = []
+ const filteredTracerResultCalls = tracerResults.calls.filter(
+ (x) => !x.type.startsWith("depth")
+ )
+
+ for (const c of filteredTracerResultCalls) {
+ if (c.type.match(/REVERT|RETURN/) !== null) {
+ const top = stack.splice(-1)[0] ?? {
+ type: "top",
+ method: "validateUserOp"
+ }
+ const returnData: Hex = (c as any).data
+ if (top.type.match(/CREATE/) !== null) {
+ out.push({
+ to: top.to,
+ from: top.from,
+ type: top.type,
+ method: "",
+ return: `len=${returnData.length}`
+ })
+ } else {
+ const method = callCatch(
+ () => functionSignatureToMethodName(top.method),
+ top.method
+ )
+
+ if (c.type === "REVERT") {
+ const parsedError = callCatch(
+ () => decodeErrorResult({ abi: abi, data: returnData }),
+ returnData
+ )
+ out.push({
+ to: top.to,
+ from: top.from,
+ type: top.type,
+ method: method,
+ value: top.value,
+ revert: parsedError
+ })
+ } else {
+ const ret = callCatch(
+ () =>
+ decodeFunctionResult({
+ abi: abi,
+ functionName: method,
+ data: returnData
+ }),
+ returnData
+ )
+ out.push({
+ to: top.to,
+ from: top.from,
+ type: top.type,
+ value: top.value,
+ method: method,
+ return: ret
+ })
+ }
+ }
+ } else {
+ stack.push(c)
+ }
+ }
+
+ // TODO: verify that stack is empty at the end.
+
+ return out
+}
+
+/**
+ * slots associated with each entity.
+ * keccak( A || ...) is associated with "A"
+ * removed rule: keccak( ... || ASSOC ) (for a previously associated hash) is also associated with "A"
+ *
+ * @param stakeInfoEntities stake info for (factory, account, paymaster). factory and paymaster can be null.
+ * @param keccak array of buffers that were given to keccak in the transaction
+ */
+function parseEntitySlots(
+ stakeInfoEntities: { [addr: string]: StakeInfo | undefined },
+ keccak: Hex[]
+): {
+ [addr: string]: Set<string>
+} {
+ // for each entity (sender, factory, paymaster), hold the valid slot addresses
+ // valid: the slot was generated by keccak(entity || ...)
+ const entitySlots: { [addr: string]: Set<string> } = {}
+
+ for (const k of keccak) {
+ const values = Object.values(stakeInfoEntities)
+ for (const info of values) {
+ const addr = info?.addr?.toLowerCase() as Hex
+ if (!addr) {
+ continue
+ }
+
+ const addrPadded = pad(addr).toLowerCase()
+ if (!entitySlots[addr]) {
+ entitySlots[addr] = new Set<string>()
+ }
+
+ const currentEntitySlots = entitySlots[addr]
+
+ // valid slot: the slot was generated by keccak(entityAddr || ...)
+ if (k.startsWith(addrPadded)) {
+ currentEntitySlots.add(keccak256(k))
+ }
+ // disabled 2nd rule: .. or by keccak( ... || OWN) where OWN is previous allowed slot
+ // if (k.length === 130 && currentEntitySlots.has(k.slice(-64))) {
+ // currentEntitySlots.add(value)
+ // }
+ }
+ }
+
+ return entitySlots
+}
+
+// method-signature for calls from entryPoint
+const callsFromEntryPointMethodSigs: { [key: string]: string } = {
+ factory: getFunctionSelector({
+ inputs: [
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ }
+ ],
+ name: "createSender",
+ outputs: [
+ {
+ internalType: "address",
+ name: "sender",
+ type: "address"
+ }
+ ],
+ stateMutability: "nonpayable",
+ type: "function"
+ }),
+ account: getFunctionSelector({
+ inputs: [
+ {
+ components: [
+ {
+ internalType: "address",
+ name: "sender",
+ type: "address"
+ },
+ {
+ internalType: "uint256",
+ name: "nonce",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "callData",
+ type: "bytes"
+ },
+ {
+ internalType: "uint256",
+ name: "callGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "verificationGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "preVerificationGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxPriorityFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "paymasterAndData",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "signature",
+ type: "bytes"
+ }
+ ],
+ internalType: "struct UserOperation",
+ name: "userOp",
+ type: "tuple"
+ },
+ {
+ internalType: "bytes32",
+ name: "",
+ type: "bytes32"
+ },
+ {
+ internalType: "uint256",
+ name: "missingAccountFunds",
+ type: "uint256"
+ }
+ ],
+ name: "validateUserOp",
+ outputs: [
+ {
+ internalType: "uint256",
+ name: "",
+ type: "uint256"
+ }
+ ],
+ stateMutability: "nonpayable",
+ type: "function"
+ }),
+ paymaster: getFunctionSelector({
+ inputs: [
+ {
+ components: [
+ {
+ internalType: "address",
+ name: "sender",
+ type: "address"
+ },
+ {
+ internalType: "uint256",
+ name: "nonce",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "callData",
+ type: "bytes"
+ },
+ {
+ internalType: "uint256",
+ name: "callGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "verificationGasLimit",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "preVerificationGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "uint256",
+ name: "maxPriorityFeePerGas",
+ type: "uint256"
+ },
+ {
+ internalType: "bytes",
+ name: "paymasterAndData",
+ type: "bytes"
+ },
+ {
+ internalType: "bytes",
+ name: "signature",
+ type: "bytes"
+ }
+ ],
+ internalType: "struct UserOperation",
+ name: "userOp",
+ type: "tuple"
+ },
+ {
+ internalType: "bytes32",
+ name: "userOpHash",
+ type: "bytes32"
+ },
+ {
+ internalType: "uint256",
+ name: "maxCost",
+ type: "uint256"
+ }
+ ],
+ name: "validatePaymasterUserOp",
+ outputs: [
+ {
+ internalType: "bytes",
+ name: "context",
+ type: "bytes"
+ },
+ {
+ internalType: "uint256",
+ name: "validationData",
+ type: "uint256"
+ }
+ ],
+ stateMutability: "nonpayable",
+ type: "function"
+ })
+}
+
+/**
+ * parse collected simulation traces and revert if they break our rules
+ * @param userOp the userOperation that was used in this simulation
+ * @param tracerResults the tracer return value
+ * @param validationResult output from simulateValidation
+ * @param entryPoint the entryPoint that hosted the "simulatedValidation" traced call.
+ * @return list of contract addresses referenced by this UserOp
+ */
+export function tracerResultParser(
+ userOp: UserOperation,
+ tracerResults: BundlerTracerResult,
+ validationResult: ValidationResult,
+ entryPointAddress: Address
+): [string[], StorageMap] {
+ // todo: block access to no-code addresses (might need update to tracer)
+
+ // opcodes from [OP-011]
+ const bannedOpCodes = new Set([
+ "GASPRICE",
+ "GASLIMIT",
+ "DIFFICULTY",
+ "TIMESTAMP",
+ "BASEFEE",
+ "BLOCKHASH",
+ "NUMBER",
+ "SELFBALANCE",
+ "BALANCE",
+ "ORIGIN",
+ "GAS",
+ "CREATE",
+ "COINBASE",
+ "SELFDESTRUCT",
+ "RANDOM",
+ "PREVRANDAO",
+ "INVALID"
+ ])
+
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
+ if (Object.values(tracerResults.callsFromEntryPoint).length < 1) {
+ throw new Error(
+ "Unexpected traceCall result: no calls from entrypoint."
+ )
+ }
+ const callStack = parseCallStack(tracerResults)
+
+ // [OP-052], [OP-053]
+ const callInfoEntryPoint = callStack.find(
+ (call) =>
+ call.to === entryPointAddress &&
+ call.from !== entryPointAddress &&
+ call.method !== "0x" &&
+ call.method !== "depositTo"
+ )
+ // [OP-054]
+ if (callInfoEntryPoint) {
+ throw new RpcError(
+ `illegal call into EntryPoint during validation ${callInfoEntryPoint?.method}`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ // [OP-061]
+ const illegalNonZeroValueCall = callStack.find(
+ (call) =>
+ call.to !== entryPointAddress &&
+ hexToBigInt(call.value ?? "0x0") !== 0n
+ )
+
+ if (illegalNonZeroValueCall) {
+ throw new RpcError(
+ "May not may CALL with value",
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ const sender = userOp.sender.toLowerCase()
+ // stake info per "number" level (factory, sender, paymaster)
+ // we only use stake info if we notice a memory reference that require stake
+ const stakeInfoEntities = {
+ factory: validationResult.factoryInfo,
+ account: validationResult.senderInfo,
+ paymaster: validationResult.paymasterInfo
+ }
+
+ const entitySlots: { [addr: string]: Set<string> } = parseEntitySlots(
+ stakeInfoEntities,
+ tracerResults.keccak as Hex[]
+ )
+
+ for (const [entityTitle, entStakes] of Object.entries(stakeInfoEntities)) {
+ const entityAddr = (entStakes?.addr ?? "").toLowerCase()
+ const currentNumLevel = tracerResults.callsFromEntryPoint.find(
+ (info) =>
+ info.topLevelMethodSig ===
+ callsFromEntryPointMethodSigs[entityTitle]
+ )
+ if (!currentNumLevel) {
+ if (entityTitle === "account") {
+ // should never happen... only factory, paymaster are optional.
+ throw new Error("missing trace into validateUserOp")
+ }
+ continue
+ }
+ const opcodes = currentNumLevel.opcodes
+ const access = currentNumLevel.access
+
+ // [OP-020]
+ if (currentNumLevel.oog ?? false) {
+ throw new RpcError(
+ `${entityTitle} internally reverts on oog`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ // opcodes from [OP-011]
+ for (const opcode of Object.keys(opcodes)) {
+ if (bannedOpCodes.has(opcode)) {
+ throw new RpcError(
+ `${entityTitle} uses banned opcode: ${opcode}`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+ }
+ // [OP-031]
+ if (entityTitle === "factory") {
+ if ((opcodes.CREATE2 ?? 0) > 1) {
+ throw new RpcError(
+ `${entityTitle} with too many CREATE2`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+ } else if (opcodes.CREATE2) {
+ throw new RpcError(
+ `${entityTitle} uses banned opcode: CREATE2`,
+ ValidationErrors.OpcodeValidation
+ )
+ }
+
+ for (const [addr, { reads, writes }] of Object.entries(access)) {
+ // testing read/write access on contract "addr"
+ if (addr === sender) {
+ // allowed to access sender's storage
+ // [STO-010]
+ continue
+ }
+
+ if (addr === entryPointAddress) {
+ // ignore storage access on entryPoint (balance/deposit of entities.
+ // we block them on method calls: only allowed to deposit, never to read
+ continue
+ }
+
+ // return true if the given slot is associated with the given address, given the known keccak operations:
+ // @param slot the SLOAD/SSTORE slot address we're testing
+ // @param addr - the address we try to check for association with
+ // @param reverseKeccak - a mapping we built for keccak values that contained the address
+ function associatedWith(
+ slot: string,
+ addr: string,
+ entitySlots: { [addr: string]: Set<string> }
+ ): boolean {
+ const addrPadded = pad(addr as Hex, {
+ size: 32
+ }).toLowerCase()
+ if (slot.toLowerCase() === addrPadded) {
+ return true
+ }
+ const k = entitySlots[addr]
+ if (!k) {
+ return false
+ }
+ const slotN = hexToBigInt(slot as Hex)
+ // scan all slot entries to check of the given slot is within a structure, starting at that offset.
+ // assume a maximum size on a (static) structure size.
+ for (const k1 of k.keys()) {
+ const kn = hexToBigInt(k1 as Hex)
+ if (slotN >= kn && slotN < kn + 128n) {
+ return true
+ }
+ }
+ return false
+ }
+
+ // scan all slots. find a referenced slot
+ // at the end of the scan, we will check if the entity has stake, and report that slot if not.
+ let requireStakeSlot: string | undefined
+
+ const slots = [...Object.keys(writes), ...Object.keys(reads)]
+
+ for (const slot of slots) {
+ // slot associated with sender is allowed (e.g. token.balanceOf(sender)
+ // but during initial UserOp (where there is an initCode), it is allowed only for staked entity
+ if (associatedWith(slot, sender, entitySlots)) {
+ if (userOp.initCode.length > 2) {
+ // special case: account.validateUserOp is allowed to use assoc storage if factory is staked.
+ // [STO-022], [STO-021]
+ if (
+ !(
+ entityAddr === sender &&
+ isStaked(stakeInfoEntities.factory)
+ )
+ ) {
+ requireStakeSlot = slot
+ }
+ }
+ } else if (associatedWith(slot, entityAddr, entitySlots)) {
+ // [STO-032]
+ // accessing a slot associated with entityAddr (e.g. token.balanceOf(paymaster)
+ requireStakeSlot = slot
+ } else if (addr === entityAddr) {
+ // [STO-031]
+ // accessing storage member of entity itself requires stake.
+ requireStakeSlot = slot
+ } else if (writes[slot] === undefined) {
+ // [STO-033]: staked entity have read-only access to any storage in non-entity contract.
+ requireStakeSlot = slot
+ } else {
+ // accessing arbitrary storage of another contract is not allowed
+ const readWrite = Object.keys(writes).includes(addr)
+ ? "write to"
+ : "read from"
+
+ const message = `${entityTitle} has forbidden ${readWrite} ${nameAddr(
+ addr,
+ entityTitle
+ )} slot ${slot}`
+
+ throw new RpcError(
+ message,
+ ValidationErrors.OpcodeValidation,
+ {
+ [entityTitle]: entStakes?.addr
+ }
+ )
+ }
+ }
+
+ // if addr is current account/paymaster/factory, then return that title
+ // otherwise, return addr as-is
+ function nameAddr(addr: string, currentEntity: string): string {
+ const [title] =
+ Object.entries(stakeInfoEntities).find(
+ ([title, info]) =>
+ info?.addr.toLowerCase() === addr.toLowerCase()
+ ) ?? []
+
+ return title ?? addr
+ }
+
+ requireCondAndStake(
+ requireStakeSlot !== undefined,
+ entStakes,
+ `unstaked ${entityTitle} accessed ${nameAddr(
+ addr,
+ entityTitle
+ )} slot ${requireStakeSlot}`
+ )
+ }
+
+ // [EREP-050]
+ if (entityTitle === "paymaster") { | should we not be using an enum for these? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -52,33 +71,80 @@ async function simulateTenderlyCall(publicClient: PublicClient, params: any) {
return parsedObject.cause.data
}
+const ErrorSig = keccak256(Buffer.from("Error(string)")).slice(0, 10) // 0x08c379a0
+const FailedOpSig = keccak256(Buffer.from("FailedOp(uint256,string)")).slice(
+ 0,
+ 10
+) // 0x220266b6
+
+interface DecodedError {
+ message: string
+ opIndex?: number
+}
+
+/**
+ * decode bytes thrown by revert as Error(message) or FailedOp(opIndex,paymaster,message)
+ */
+export function decodeErrorReason(error: string): DecodedError | null {
+ if (error.startsWith(ErrorSig)) { | you can natively decode errors with viem |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -241,4 +438,222 @@ export class UnsafeValidator implements IValidator {
throw e
}
}
+
+ async getCodeHashes(addresses: string[]): Promise<ReferencedCodeHashes> {
+ const deployData = encodeDeployData({
+ abi: CodeHashGetterAbi,
+ bytecode: CodeHashGetterBytecode,
+ args: [addresses]
+ })
+
+ const wallet = await this.senderManager.getWallet()
+
+ let hash = ""
+
+ try {
+ await this.publicClient.call({
+ account: wallet,
+ data: deployData
+ })
+ } catch (e) {
+ const error = e as ExecutionRevertedError
+ hash = (error.walk() as any).data
+ }
+
+ this.senderManager.pushWallet(wallet)
+
+ return {
+ hash,
+ addresses
+ }
+ }
+
+ async getValidationResult(
+ userOperation: UserOperation,
+ codeHashes?: ReferencedCodeHashes
+ ): Promise<
+ (ValidationResult | ValidationResultWithAggregation) & {
+ referencedContracts?: ReferencedCodeHashes
+ storageMap: StorageMap
+ }
+ > {
+ if (this.usingTenderly) {
+ return super.getValidationResult(userOperation)
+ }
+
+ if (codeHashes && codeHashes.addresses.length > 0) {
+ const { hash } = await this.getCodeHashes(codeHashes.addresses)
+ if (hash !== codeHashes.hash) {
+ throw new RpcError(
+ "code hashes mismatch",
+ ValidationErrors.OpcodeValidation
+ )
+ }
+ }
+
+ const [res, tracerResult] =
+ await this.getValidationResultWithTracer(userOperation)
+
+ const [contractAddresses, storageMap] = tracerResultParser(
+ userOperation,
+ tracerResult,
+ res,
+ this.entryPoint.toLowerCase() as Address
+ )
+
+ if (!codeHashes) {
+ codeHashes = await this.getCodeHashes(contractAddresses)
+ }
+
+ if ((res as any) === "0x") {
+ throw new Error(
+ "simulateValidation reverted with no revert string!"
+ )
+ }
+ return {
+ ...res,
+ referencedContracts: codeHashes,
+ storageMap
+ }
+ }
+
+ async getValidationResultWithTracer(
+ userOperation: UserOperation
+ ): Promise<[ValidationResult, BundlerTracerResult]> {
+ const tracerResult = await debug_traceCall(
+ this.publicClient,
+ {
+ from: zeroAddress,
+ to: this.entryPoint,
+ data: encodeFunctionData({
+ abi: EntryPointAbi,
+ functionName: "simulateValidation",
+ args: [userOperation]
+ })
+ },
+ {
+ tracer: bundlerCollectorTracer
+ }
+ )
+
+ const lastResult = tracerResult.calls.slice(-1)[0]
+ if (lastResult.type !== "REVERT") {
+ throw new Error("Invalid response. simulateCall must revert")
+ }
+
+ const data = (lastResult as ExitInfo).data
+ if (data === "0x") {
+ return [data as any, tracerResult]
+ }
+
+ try {
+ const { errorName, args: errorArgs } = decodeErrorResult({
+ abi: EntryPointAbi,
+ data
+ })
+
+ const errFullName = `${errorName}(${errorArgs.toString()})`
+ const errorResult = this.parseErrorResult(userOperation, {
+ errorName,
+ errorArgs
+ })
+ if (!errorName.includes("Result")) {
+ // a real error, not a result.
+ throw new Error(errFullName)
+ }
+ // @ts-ignore
+ return [errorResult, tracerResult]
+ } catch (e: any) {
+ // if already parsed, throw as is
+ if (e.code != null) {
+ throw e
+ }
+ // not a known error of EntryPoint (probably, only Error(string), since FailedOp is handled above)
+ const err = decodeErrorReason(data)
+ throw new RpcError(err != null ? err.message : data, 111)
+ }
+ }
+
+ parseErrorResult(
+ userOp: UserOperation,
+ errorResult: { errorName: string; errorArgs: any }
+ ): ValidationResult | ValidationResultWithAggregation {
+ if (!errorResult?.errorName?.startsWith("ValidationResult")) { | again i think viem can do this for you |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -275,11 +318,36 @@ const bundlerClearStateResponseSchema = z.object({
result: z.literal("ok")
})
+const bundlerClearMempoolResponseSchema = z.object({
+ method: z.literal("debug_bundler_clearMempool"),
+ result: z.literal("ok")
+})
+
const bundlerDumpMempoolResponseSchema = z.object({
method: z.literal("debug_bundler_dumpMempool"),
result: z.array(userOperationSchema)
})
+const bundlerGetStakeStatusResponseSchema = z.object({
+ method: z.literal("debug_bundler_getStakeStatus"),
+ result: z.object({
+ stakeInfo: z.object({
+ addr: z.string(),
+ stake: z
+ .string()
+ .or(z.number())
+ .or(z.bigint())
+ .transform((val) => Number(val).toString()), | number??? |
alto | github_2023 | typescript | 45 | pimlicolabs | kristofgazso | @@ -1,51 +1,131 @@
import { EntryPointAbi, HexData32, UserOperation } from "@alto/types"
-import { Address, PublicClient, decodeEventLog, encodeAbiParameters, keccak256 } from "viem"
+import {
+ Address,
+ Hex,
+ PublicClient,
+ decodeEventLog,
+ encodeAbiParameters,
+ keccak256,
+} from "viem"
+
+export function getAddressFromInitCodeOrPaymasterAndData(
+ data: Hex
+): string | undefined {
+ if (!data) {
+ return undefined
+ }
+ if (data.length >= 42) {
+ return data.slice(0, 42)
+ }
+ return undefined
+}
import * as sentry from "@sentry/node"
export const transactionIncluded = async (
txHash: HexData32,
publicClient: PublicClient
-): Promise<"included" | "reverted" | "failed" | "not_found"> => {
+): Promise<{
+ status: "included" | "reverted" | "failed" | "not_found"
+ [userOperationHash: HexData32]: {
+ accountDeployed: boolean
+ }
+}> => {
try {
const rcp = await publicClient.getTransactionReceipt({ hash: txHash })
if (rcp.status === "success") {
- // find if any logs are UserOperationEvent
+ // find if any logs are UserOperationEvent or AccountDeployed
const r = rcp.logs
.map((l) => {
if (l.address === rcp.to) {
try {
- const log = decodeEventLog({ abi: EntryPointAbi, data: l.data, topics: l.topics })
+ const log = decodeEventLog({
+ abi: EntryPointAbi,
+ data: l.data,
+ topics: l.topics
+ })
+ if (log.eventName === "AccountDeployed") {
+ return {
+ userOperationHash: log.args.userOpHash,
+ success: !!log.args.factory,
+ accountDeployed: true
+ }
+ }
if (log.eventName === "UserOperationEvent") {
- return log
- } else {
- return undefined
+ return {
+ userOperationHash: log.args.userOpHash,
+ success: !!log.args.success,
+ accountDeployed: false
+ }
}
+ return undefined
} catch (_e) {
sentry.captureException(_e)
- console.log("error decoding transaction inclusion status", _e)
return undefined
}
- } else {
- return undefined
}
+ return undefined
})
- .find((l) => l !== undefined)
+ .reduce(
+ (
+ result: {
+ [userOperationHash: HexData32]: {
+ userOperationHash: HexData32
+ accountDeployed: boolean
+ success: boolean
+ }
+ },
+ log
+ ) => {
+ if (log) {
+ return {
+ [log.userOperationHash]: {
+ accountDeployed:
+ log.accountDeployed ||
+ result[log.userOperationHash]
+ ?.accountDeployed,
+ success:
+ log.success || | not &&? |
alto | github_2023 | typescript | 62 | pimlicolabs | plusminushalf | @@ -38,6 +38,16 @@ JSON.stringify = function (
return originalJsonStringify(value, wrapperReplacer, space)
}
+declare module "fastify" { | `fastify` is typed write? |
permissionless.js | github_2023 | typescript | 350 | pimlicolabs | plusminushalf | @@ -0,0 +1,35 @@
+export const KernelV3FactoryAbi = [
+ {
+ type: "constructor",
+ inputs: [{ name: "_impl", type: "address", internalType: "address" }],
+ stateMutability: "nonpayable"
+ },
+ {
+ type: "function", | I think we just use `createAccount` can we remove rest of unused abi |
permissionless.js | github_2023 | others | 96 | pimlicolabs | plusminushalf | @@ -0,0 +1,175 @@
+# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
+
+# Logs
+ | Can you add these to the global .gitignore |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | plusminushalf | @@ -0,0 +1,150 @@
+import * as p from "@clack/prompts"
+// import chalk from "chalk";
+import { Command } from "commander"
+
+import { CREATE_PERMISSIONLESS_APP, DEFAULT_APP_NAME } from "../constants"
+import { logger } from "../utils/logger"
+import { validateAppName } from "../utils/validateAppName"
+
+interface CliFlags {
+ bundler: string
+ paymaster: string
+ signer: string
+ accountSystem: string
+}
+
+interface CliResults {
+ appName: string
+ flags: CliFlags
+}
+
+const defaultOptions: CliResults = {
+ appName: DEFAULT_APP_NAME,
+ flags: {
+ bundler: "pimlico",
+ paymaster: "pimlico",
+ signer: "privy",
+ accountSystem: "safe"
+ }
+}
+
+export const runCli = async (): Promise<CliResults> => {
+ const cliResults = defaultOptions
+
+ const program = new Command()
+ .name(CREATE_PERMISSIONLESS_APP)
+ .description("A CLI to spin up a permissionless app with Pimlico")
+ .argument(
+ "[dir]",
+ "The name of the application, as well as the name of the directory to create"
+ )
+
+ /** START CI-FLAGS
+ * As of now these CI Flags are not well structured but will be updated soon..
+ */
+ .option(
+ "-b, --bundler",
+ "Specify the bundler provider",
+ defaultOptions.flags.bundler
+ )
+ .option(
+ "-p, --paymaster",
+ "Specify the paymaster provider",
+ defaultOptions.flags.paymaster
+ )
+ .option(
+ "-s, --signer",
+ "Specify the signer",
+ defaultOptions.flags.signer
+ )
+ .option(
+ "-a, --account-system",
+ "Specify the account system",
+ defaultOptions.flags.accountSystem
+ )
+ /** END CI-FLAGS */
+ .parse(process.argv)
+
+ const cliProvidedName = program.args[0]
+ if (cliProvidedName) {
+ cliResults.appName = cliProvidedName
+ }
+
+ cliResults.flags = program.opts()
+
+ try {
+ const project = await p.group(
+ {
+ ...(!cliProvidedName && {
+ name: () =>
+ p.text({
+ message: "What will your project be called?",
+ defaultValue: cliProvidedName,
+ validate: validateAppName
+ })
+ }),
+ bundler: () => {
+ return p.select({
+ message: "Pick your bundler provider",
+ options: [{ value: "pimlico", label: "Pimlico" }],
+ initialValue: cliResults.flags.bundler
+ })
+ },
+ paymaster: () => {
+ return p.select({
+ message: "Pick your paymaster provider",
+ options: [{ value: "pimlico", label: "Pimlico" }],
+ initialValue: cliResults.flags.paymaster
+ })
+ },
+ accountSystem: () => {
+ return p.select({
+ message: "Pick your account system",
+ options: [{ value: "safe", label: "Safe" }], | I see you have simple account & kernel as well right? |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | plusminushalf | @@ -0,0 +1,37 @@
+import path from "path"
+import chalk from "chalk"
+import { execa } from "execa"
+import ora from "ora"
+import {
+ type PackageManager,
+ detectPackageManager
+} from "../utils/detectPackageManager"
+
+export const installDependencies = async (projectDir: string) => {
+ const boilerplateDir = path.resolve(process.cwd(), projectDir)
+
+ try {
+ // Change directory to the generated boilerplate directory
+ process.chdir(boilerplateDir)
+
+ // Detect the package manager being used
+ const packageManager: PackageManager = detectPackageManager()
+
+ // Start spinner to notify users
+ const spinner = ora({
+ text: `Installing dependencies using ${packageManager}...`,
+ spinner: "dots"
+ }).start()
+
+ // Install dependencies using the detected package manager
+ await execa(packageManager, ["install"], { stdio: "inherit" })
+
+ // Stop spinner and notify users
+ spinner.succeed(chalk.green("Dependencies installed successfully."))
+ } catch (error) {
+ console.error( | Hey I saw you have a logger class, I think we can replace such console logs with it. |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | plusminushalf | @@ -0,0 +1,43 @@
+import pathModule from "path"
+
+import { removeTrailingSlash } from "./general"
+
+/**
+ * Parses the appName and its path from the user input.
+ *
+ * Returns a tuple of of `[appName, path]`, where `appName` is the name put in the "package.json"
+ * file and `path` is the path to the directory where the app will be created.
+ *
+ * If `appName` is ".", the name of the directory will be used instead. Handles the case where the
+ * input includes a scoped package name in which case that is being parsed as the name, but not
+ * included as the path.
+ *
+ * For example:
+ *
+ * - dir/@mono/app => ["@mono/app", "dir/app"]
+ * - dir/app => ["app", "dir/app"]
+ */
+
+export const parseNameAndPath = (rawInput: string) => {
+ const input = removeTrailingSlash(rawInput)
+
+ const paths = input.split("/")
+
+ let appName = paths.length > 0 ? paths[paths.length - 1] : ""
+
+ // If the user ran `npx create-permissionless-app .` or similar, the appName should be the current directory
+ if (appName === ".") {
+ const parsedCwd = pathModule.resolve(process.cwd())
+ appName = pathModule.basename(parsedCwd)
+ }
+
+ // If the first part is a @, it's a scoped package
+ const indexOfDelimiter = paths.findIndex((p) => p.startsWith("@"))
+ if (paths.findIndex((p) => p.startsWith("@")) !== -1) { | You can use `indexOfDelimiter !== -1` |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | plusminushalf | @@ -0,0 +1,32 @@
+import Image from "next/image"
+import React from "react"
+
+export const Header: React.FC = () => {
+ return (
+ <div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex">
+ <p className="fixed left-0 top-0 flex flex-col w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30">
+ Get started by cloning | I think we might want to change this, as this template shouldn't need to clone anything. |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | plusminushalf | @@ -0,0 +1,37 @@
+import { pimlicoPaymaster } from "@/config/pimlicoConfig"
+import { createSmartAccountClient } from "permissionless"
+import { type SmartAccountClient } from "permissionless"
+import {
+ type SafeSmartAccount,
+ privateKeyToSafeSmartAccount
+} from "permissionless/accounts"
+import { http, type Address, type Chain } from "viem"
+import { type PublicClient } from "viem"
+import { usePublicClient } from "wagmi"
+import { sepolia } from "wagmi"
+
+export const createSafeAccount = async (publicClient: PublicClient) => {
+ const safeAccount: SafeSmartAccount = await privateKeyToSafeSmartAccount( | we are creating safe account but the directory is called simple |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | plusminushalf | @@ -0,0 +1,8 @@
+import { createPimlicoBundlerClient } from "permissionless/clients/pimlico"
+import { http } from "viem"
+import { goerli } from "viem/chains"
+
+export const bundlerClient = createPimlicoBundlerClient({
+ chain: goerli, | wagmi config is with sepolia, we might want to change this to sepolia too.
Also we can use transport as:
`https://api.pimlico.io/v1/sepolia/rpc?apikey=API_KEY` |
permissionless.js | github_2023 | others | 96 | pimlicolabs | mouseless0x | @@ -0,0 +1,15 @@
+# create-permissionless-app
+
+To install dependencies:
+
+```bash
+bun install
+```
+
+To run:
+
+```bash
+bun run index.ts | small nit, `bun run ./src/index.ts` |
permissionless.js | github_2023 | others | 96 | pimlicolabs | mouseless0x | @@ -1,12 +1,33 @@
{
"name": "create-permissionless-app",
- "version": "0.0.0",
+ "version": "0.0.1",
"description": "",
- "main": "index.js",
+ "module": "index.ts",
+ "type": "module",
"scripts": {
+ "build": "npx tsc",
"test": "echo \"Error: no test specified\" && exit 1"
},
- "keywords": [],
- "author": "",
- "license": "ISC" | license can be set to MIT |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | mouseless0x | @@ -0,0 +1,42 @@
+import React from "react"
+
+export const Footer = () => {
+ return (
+ <div className="mb-32 grid text-center lg:max-w-5xl lg:w-full lg:mb-0 lg:grid-cols-2 lg:text-left">
+ <a
+ href="https://docs.pimlico.io/permissionless"
+ className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <h2 className={"mb-3 text-2xl font-semibold"}>
+ Docs{" "}
+ <span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
+ ->
+ </span>
+ </h2>
+ <p className={"m-0 max-w-[30ch] text-sm opacity-50"}>
+ Find in-depth information about permissionless features and
+ API.
+ </p>
+ </a>
+
+ <a
+ href="https://docs.pimlico.io/permissionless/how-to" | This is a dead link |
permissionless.js | github_2023 | typescript | 96 | pimlicolabs | mouseless0x | @@ -0,0 +1,126 @@
+#!/usr/bin/env node
+import path from "path"
+import fs from "fs-extra"
+import { type PackageJson } from "type-fest"
+
+import { runCli } from "./cli/index"
+import { createProject } from "./helpers/createProject"
+import { installDependencies } from "./helpers/installDependencies"
+import { addPackageDependency } from "./utils/addPackageDependency"
+import {
+ type PackageManager,
+ detectPackageManager
+} from "./utils/detectPackageManager"
+import { logger } from "./utils/logger"
+import { parseNameAndPath } from "./utils/parseNameAndPath"
+import { renderTitle } from "./utils/renderTitle"
+
+type CPAPackageJSON = PackageJson & {
+ cpaMetadata?: {
+ initVersion: string
+ }
+}
+
+const main = async () => {
+ await renderTitle()
+
+ const {
+ appName,
+ flags: {
+ noInstall,
+ bundler,
+ paymaster,
+ signer,
+ accountSystem,
+ privyAppId,
+ pimlicoApiKey,
+ publicRPCUrl
+ }
+ } = await runCli()
+ const packageManager: PackageManager = detectPackageManager()
+
+ const [scopedAppName, appDir] = parseNameAndPath(appName)
+
+ const projectDir = await createProject({
+ projectName: appDir,
+ bundler,
+ paymaster,
+ signer,
+ accountSystem,
+ privyAppId,
+ pimlicoApiKey,
+ publicRPCUrl
+ })
+
+ // Write name to package.json
+ const pkgJson = fs.readJSONSync(
+ path.join(projectDir, "package.json")
+ ) as CPAPackageJSON
+ pkgJson.name = scopedAppName
+
+ fs.writeJSONSync(path.join(projectDir, "package.json"), pkgJson, {
+ spaces: 2
+ })
+
+ addPackageDependency(signer, projectDir)
+
+ if (!noInstall) {
+ await installDependencies(projectDir)
+ }
+
+ // Display next steps for the user
+ logger.info("\n Next steps:")
+ scopedAppName !== "." && logger.info(` - cd ${scopedAppName}`)
+ if (noInstall) {
+ // To reflect yarn's default behavior of installing packages when no additional args provided
+ if (packageManager === "yarn") {
+ logger.info(` - ${packageManager}`)
+ } else {
+ logger.info(` - ${packageManager} install`)
+ }
+ }
+
+ logger.info(
+ " - create a .env file in the root dir based on the .env.example template and provide the necessary values"
+ )
+
+ if (packageManager === "yarn") {
+ logger.info(` - ${packageManager} dev`)
+ } else {
+ logger.info(` - ${packageManager} run dev`)
+ }
+
+ logger.info("\nThank you for using our CLI tool!")
+ logger.info(
+ "As we launch the first version, please pardon any issues during beta testing."
+ )
+ logger.info(
+ "Your feedback helps us improve. If you encounter any bugs or have suggestions, please let us know."
+ )
+ logger.info("We appreciate your support!")
+
+ // Thank you note and apology for beta issues
+ logger.info("\nThank you for using our CLI tool!") | Looks like this is a duplicate print? I would remove lines 93-100 and keep 103-113 |
permissionless.js | github_2023 | typescript | 245 | pimlicolabs | wilsoncusack | @@ -0,0 +1,8 @@
+export const COINBASE_SMART_WALLET_IMPLEMENTATION_ADDRESS =
+ "0x000100abaad02f1cfC8Bbe32bD5a564817339E72"
+
+export const COINBASE_SMART_WALLET_FACTORY_ADDRESS =
+ "0x0BA5ED0c6AA8c49038F819E587E2633c4A9F428a"
+
+export const ERC1271InputGeneratorByteCode = | we've actually moved away from using this in favor of just manually computing the replaySafeHash. Will try to share code |
permissionless.js | github_2023 | typescript | 278 | pimlicolabs | plusminushalf | @@ -145,5 +150,28 @@ export function createSmartAccountClient(
userOperation
})
+ if (parameters.userOperation?.prepareUserOperation) { | ```ts
const client = Object.assign(
createClient({
...parameters,
chain: parameters.chain ?? client_?.chain,
key,
name,
transport,
type: 'bundlerClient',
}),
{ client: client_, paymaster, paymasterContext, userOperation },
``` |
permissionless.js | github_2023 | typescript | 278 | pimlicolabs | plusminushalf | @@ -0,0 +1,231 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type ContractFunctionParameters,
+ type Transport,
+ encodeFunctionData,
+ getAddress,
+ maxUint256,
+ parseAbi
+} from "viem"
+import {
+ type BundlerClient,
+ type PrepareUserOperationParameters,
+ type PrepareUserOperationRequest,
+ type PrepareUserOperationReturnType,
+ type SmartAccount,
+ type UserOperation,
+ type UserOperationCall,
+ getPaymasterData as getPaymasterData_,
+ prepareUserOperation
+} from "viem/account-abstraction"
+import { getAction, parseAccount } from "viem/utils"
+import type { PimlicoClient } from "../clients/pimlico"
+
+export const prepareUserOperationWithErc20Paymaster =
+ (pimlicoClient: PimlicoClient) =>
+ async <
+ account extends SmartAccount | undefined,
+ const calls extends readonly unknown[],
+ const request extends PrepareUserOperationRequest<
+ account,
+ accountOverride,
+ calls
+ >,
+ accountOverride extends SmartAccount | undefined = undefined
+ >(
+ client: Client<Transport, Chain | undefined, account>,
+ parameters_: PrepareUserOperationParameters<
+ account,
+ accountOverride,
+ calls,
+ request
+ >
+ ): Promise<
+ PrepareUserOperationReturnType<account, accountOverride, calls, request>
+ > => {
+ const parameters = parameters_ as PrepareUserOperationParameters
+ const account_ = client.account
+
+ if (!account_) throw new Error("Account not found")
+ const account = parseAccount(account_)
+
+ const { paymasterContext } = parameters
+
+ if (
+ typeof paymasterContext === "object" &&
+ paymasterContext !== null &&
+ "token" in paymasterContext &&
+ typeof paymasterContext.token === "string"
+ ) {
+ ////////////////////////////////////////////////////////////////////////////////
+ // Inject custom approval before calling prepareUserOperation
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const quotes = await pimlicoClient.getTokenQuotes({ | use `getAction` |
permissionless.js | github_2023 | typescript | 278 | pimlicolabs | plusminushalf | @@ -0,0 +1,231 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type ContractFunctionParameters,
+ type Transport,
+ encodeFunctionData,
+ getAddress,
+ maxUint256,
+ parseAbi
+} from "viem"
+import {
+ type BundlerClient,
+ type PrepareUserOperationParameters,
+ type PrepareUserOperationRequest,
+ type PrepareUserOperationReturnType,
+ type SmartAccount,
+ type UserOperation,
+ type UserOperationCall,
+ getPaymasterData as getPaymasterData_,
+ prepareUserOperation
+} from "viem/account-abstraction"
+import { getAction, parseAccount } from "viem/utils"
+import type { PimlicoClient } from "../clients/pimlico"
+
+export const prepareUserOperationWithErc20Paymaster =
+ (pimlicoClient: PimlicoClient) => | use `Client` |
permissionless.js | github_2023 | typescript | 278 | pimlicolabs | plusminushalf | @@ -0,0 +1,231 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type ContractFunctionParameters,
+ type Transport,
+ encodeFunctionData,
+ getAddress,
+ maxUint256,
+ parseAbi
+} from "viem"
+import {
+ type BundlerClient,
+ type PrepareUserOperationParameters,
+ type PrepareUserOperationRequest,
+ type PrepareUserOperationReturnType,
+ type SmartAccount,
+ type UserOperation,
+ type UserOperationCall,
+ getPaymasterData as getPaymasterData_,
+ prepareUserOperation
+} from "viem/account-abstraction"
+import { getAction, parseAccount } from "viem/utils"
+import type { PimlicoClient } from "../clients/pimlico"
+
+export const prepareUserOperationWithErc20Paymaster =
+ (pimlicoClient: PimlicoClient) =>
+ async <
+ account extends SmartAccount | undefined,
+ const calls extends readonly unknown[],
+ const request extends PrepareUserOperationRequest<
+ account,
+ accountOverride,
+ calls
+ >,
+ accountOverride extends SmartAccount | undefined = undefined
+ >(
+ client: Client<Transport, Chain | undefined, account>,
+ parameters_: PrepareUserOperationParameters<
+ account,
+ accountOverride,
+ calls,
+ request
+ >
+ ): Promise<
+ PrepareUserOperationReturnType<account, accountOverride, calls, request>
+ > => {
+ const parameters = parameters_ as PrepareUserOperationParameters
+ const account_ = client.account
+
+ if (!account_) throw new Error("Account not found")
+ const account = parseAccount(account_)
+
+ const { paymasterContext } = parameters
+
+ if (
+ typeof paymasterContext === "object" &&
+ paymasterContext !== null &&
+ "token" in paymasterContext &&
+ typeof paymasterContext.token === "string"
+ ) {
+ ////////////////////////////////////////////////////////////////////////////////
+ // Inject custom approval before calling prepareUserOperation
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const quotes = await pimlicoClient.getTokenQuotes({
+ tokens: [getAddress(paymasterContext.token)],
+ chain: pimlicoClient.chain ?? (client.chain as Chain)
+ })
+
+ const {
+ postOpGas,
+ exchangeRate,
+ paymaster: paymasterERC20Address
+ } = quotes[0]
+
+ const callsWithApproval = [
+ {
+ abi: parseAbi(["function approve(address,uint)"]),
+ functionName: "approve",
+ args: [paymasterERC20Address, maxUint256], // dummy approval to ensure simulation passes
+ to: paymasterContext.token
+ },
+ ...(parameters.calls ? parameters.calls : [])
+ ]
+
+ if (parameters.callData) {
+ throw new Error(
+ "callData not supported in erc20 approval+sponsor flow"
+ )
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Call prepareUserOperation
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const userOperation = await getAction(
+ client,
+ prepareUserOperation,
+ "prepareUserOperation"
+ )({
+ ...parameters,
+ calls: callsWithApproval
+ } as unknown as PrepareUserOperationParameters)
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Call pimlico_getTokenQuotes and calculate the approval amount needed for op
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const maxFeePerGas =
+ parameters.maxFeePerGas ?? userOperation.maxFeePerGas | no need for `parameters.maxFeePerGas` |
permissionless.js | github_2023 | typescript | 278 | pimlicolabs | plusminushalf | @@ -0,0 +1,231 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type ContractFunctionParameters,
+ type Transport,
+ encodeFunctionData,
+ getAddress,
+ maxUint256,
+ parseAbi
+} from "viem"
+import {
+ type BundlerClient,
+ type PrepareUserOperationParameters,
+ type PrepareUserOperationRequest,
+ type PrepareUserOperationReturnType,
+ type SmartAccount,
+ type UserOperation,
+ type UserOperationCall,
+ getPaymasterData as getPaymasterData_,
+ prepareUserOperation
+} from "viem/account-abstraction"
+import { getAction, parseAccount } from "viem/utils"
+import type { PimlicoClient } from "../clients/pimlico"
+
+export const prepareUserOperationWithErc20Paymaster =
+ (pimlicoClient: PimlicoClient) =>
+ async <
+ account extends SmartAccount | undefined,
+ const calls extends readonly unknown[],
+ const request extends PrepareUserOperationRequest<
+ account,
+ accountOverride,
+ calls
+ >,
+ accountOverride extends SmartAccount | undefined = undefined
+ >(
+ client: Client<Transport, Chain | undefined, account>,
+ parameters_: PrepareUserOperationParameters<
+ account,
+ accountOverride,
+ calls,
+ request
+ >
+ ): Promise<
+ PrepareUserOperationReturnType<account, accountOverride, calls, request>
+ > => {
+ const parameters = parameters_ as PrepareUserOperationParameters
+ const account_ = client.account
+
+ if (!account_) throw new Error("Account not found")
+ const account = parseAccount(account_)
+
+ const { paymasterContext } = parameters
+
+ if (
+ typeof paymasterContext === "object" &&
+ paymasterContext !== null &&
+ "token" in paymasterContext &&
+ typeof paymasterContext.token === "string"
+ ) {
+ ////////////////////////////////////////////////////////////////////////////////
+ // Inject custom approval before calling prepareUserOperation
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const quotes = await pimlicoClient.getTokenQuotes({
+ tokens: [getAddress(paymasterContext.token)],
+ chain: pimlicoClient.chain ?? (client.chain as Chain)
+ })
+
+ const {
+ postOpGas,
+ exchangeRate,
+ paymaster: paymasterERC20Address
+ } = quotes[0]
+
+ const callsWithApproval = [
+ {
+ abi: parseAbi(["function approve(address,uint)"]),
+ functionName: "approve",
+ args: [paymasterERC20Address, maxUint256], // dummy approval to ensure simulation passes
+ to: paymasterContext.token
+ },
+ ...(parameters.calls ? parameters.calls : [])
+ ]
+
+ if (parameters.callData) {
+ throw new Error(
+ "callData not supported in erc20 approval+sponsor flow"
+ )
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Call prepareUserOperation
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const userOperation = await getAction(
+ client,
+ prepareUserOperation,
+ "prepareUserOperation"
+ )({
+ ...parameters,
+ calls: callsWithApproval
+ } as unknown as PrepareUserOperationParameters)
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Call pimlico_getTokenQuotes and calculate the approval amount needed for op
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const maxFeePerGas =
+ parameters.maxFeePerGas ?? userOperation.maxFeePerGas
+
+ if (!maxFeePerGas) {
+ throw new Error("failed to get maxFeePerGas")
+ }
+
+ const userOperationMaxGas =
+ userOperation.preVerificationGas +
+ userOperation.callGasLimit +
+ userOperation.verificationGasLimit +
+ (userOperation.paymasterPostOpGasLimit || 0n) +
+ (userOperation.paymasterVerificationGasLimit || 0n)
+
+ const userOperationMaxCost =
+ userOperationMaxGas * userOperation.maxFeePerGas
+
+ // using formula here https://github.com/pimlicolabs/singleton-paymaster/blob/main/src/base/BaseSingletonPaymaster.sol#L334-L341
+ const maxCostInToken =
+ ((userOperationMaxCost + postOpGas * maxFeePerGas) *
+ exchangeRate) /
+ BigInt(1e18)
+
+ const finalCalls = [
+ {
+ abi: parseAbi(["function approve(address,uint)"]), | use `erc20Abi` from viem |
permissionless.js | github_2023 | typescript | 278 | pimlicolabs | plusminushalf | @@ -0,0 +1,261 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type ContractFunctionParameters,
+ type Transport,
+ encodeFunctionData,
+ erc20Abi,
+ getAddress,
+ isAddress,
+ maxUint256
+} from "viem"
+import {
+ type BundlerClient,
+ type PrepareUserOperationParameters,
+ type PrepareUserOperationRequest,
+ type PrepareUserOperationReturnType,
+ type SmartAccount,
+ type UserOperation,
+ type UserOperationCall,
+ getPaymasterData as getPaymasterData_,
+ prepareUserOperation
+} from "viem/account-abstraction"
+import { readContract } from "viem/actions"
+import { getAction, parseAccount } from "viem/utils"
+import { getTokenQuotes } from "../../actions/pimlico"
+
+export const prepareUserOperationWithErc20Paymaster =
+ (pimlicoClient: Client) =>
+ async <
+ account extends SmartAccount | undefined,
+ const calls extends readonly unknown[],
+ const request extends PrepareUserOperationRequest<
+ account,
+ accountOverride,
+ calls
+ >,
+ accountOverride extends SmartAccount | undefined = undefined
+ >(
+ client: Client<Transport, Chain | undefined, account>,
+ parameters_: PrepareUserOperationParameters<
+ account,
+ accountOverride,
+ calls,
+ request
+ >
+ ): Promise<
+ PrepareUserOperationReturnType<account, accountOverride, calls, request>
+ > => {
+ const parameters = parameters_ as PrepareUserOperationParameters
+ const account_ = client.account
+
+ if (!account_) throw new Error("Account not found")
+ const account = parseAccount(account_)
+
+ const bundlerClient = client as unknown as BundlerClient
+
+ const paymasterContext = parameters.paymasterContext
+ ? parameters.paymasterContext
+ : bundlerClient?.paymasterContext
+
+ if (
+ typeof paymasterContext === "object" &&
+ paymasterContext !== null &&
+ "token" in paymasterContext &&
+ typeof paymasterContext.token === "string"
+ ) {
+ if (!isAddress(paymasterContext.token, { strict: false })) {
+ throw new Error(
+ "paymasterContext.token should be of type Address"
+ )
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // Inject custom approval before calling prepareUserOperation
+ ////////////////////////////////////////////////////////////////////////////////
+
+ const quotes = await getAction(
+ pimlicoClient,
+ getTokenQuotes,
+ "getTokenQuotes"
+ )({
+ tokens: [getAddress(paymasterContext.token)],
+ chain: pimlicoClient.chain ?? (client.chain as Chain), | ```ts
let chainId: number | undefined
async function getChainId(): Promise<number> {
if (chainId) return chainId
if (client.chain) return client.chain.id
const chainId_ = await getAction(client, getChainId_, 'getChainId')({})
chainId = chainId_
return chainId
}
``` |
permissionless.js | github_2023 | typescript | 278 | pimlicolabs | plusminushalf | @@ -0,0 +1,261 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type ContractFunctionParameters,
+ type Transport,
+ encodeFunctionData,
+ erc20Abi,
+ getAddress,
+ isAddress,
+ maxUint256
+} from "viem"
+import {
+ type BundlerClient,
+ type PrepareUserOperationParameters,
+ type PrepareUserOperationRequest,
+ type PrepareUserOperationReturnType,
+ type SmartAccount,
+ type UserOperation,
+ type UserOperationCall,
+ getPaymasterData as getPaymasterData_,
+ prepareUserOperation
+} from "viem/account-abstraction"
+import { readContract } from "viem/actions"
+import { getAction, parseAccount } from "viem/utils"
+import { getTokenQuotes } from "../../actions/pimlico"
+
+export const prepareUserOperationWithErc20Paymaster =
+ (pimlicoClient: Client) =>
+ async <
+ account extends SmartAccount | undefined,
+ const calls extends readonly unknown[],
+ const request extends PrepareUserOperationRequest<
+ account,
+ accountOverride,
+ calls
+ >,
+ accountOverride extends SmartAccount | undefined = undefined
+ >(
+ client: Client<Transport, Chain | undefined, account>,
+ parameters_: PrepareUserOperationParameters< | omit `callData` |
permissionless.js | github_2023 | typescript | 214 | pimlicolabs | plusminushalf | @@ -0,0 +1,112 @@
+import type {
+ Abi,
+ Chain,
+ Client,
+ DeployContractParameters,
+ EncodeDeployDataParameters,
+ Hash,
+ Transport
+} from "viem"
+import { getAction } from "viem/utils"
+import type { SmartAccount } from "../../accounts/types"
+import type { Prettify } from "../../types/"
+import type { EntryPoint } from "../../types/entrypoint"
+import { parseAccount } from "../../utils/"
+import { AccountOrClientNotFoundError } from "../../utils/signUserOperationHashWithECDSA"
+import { waitForUserOperationReceipt } from "../bundler/waitForUserOperationReceipt"
+import { type Middleware } from "./prepareUserOperationRequest"
+import { sendUserOperation } from "./sendUserOperation"
+
+export type DeployContractParametersWithPaymaster<
+ entryPoint extends EntryPoint,
+ TAbi extends Abi | readonly unknown[] = Abi | readonly unknown[],
+ TChain extends Chain | undefined = Chain | undefined,
+ TAccount extends SmartAccount<entryPoint> | undefined =
+ | SmartAccount<entryPoint>
+ | undefined,
+ TChainOverride extends Chain | undefined = Chain | undefined
+> = DeployContractParameters<TAbi, TChain, TAccount, TChainOverride> &
+ Middleware<entryPoint>
+
+/**
+ * Deploys a contract to the network, given bytecode and constructor arguments.
+ * This function also allows you to sponsor this transaction if sender is a smartAccount
+ *
+ * - Docs: https://viem.sh/docs/contract/deployContract.html
+ *
+ * @param client - Client to use
+ * @param parameters - {@link DeployContractParameters}
+ * @returns The [Transaction](https://viem.sh/docs/glossary/terms.html#transaction) hash.
+ *
+ * @example
+ * import { createWalletClient, http } from 'viem'
+ * import { privateKeyToAccount } from 'viem/accounts'
+ * import { mainnet } from 'viem/chains'
+ * import { deployContract } from 'viem/contract'
+ *
+ * const client = createWalletClient({
+ * account: privateKeyToAccount('0x…'),
+ * chain: mainnet,
+ * transport: http(),
+ * })
+ * const hash = await deployContract(client, {
+ * abi: [],
+ * account: '0x…,
+ * bytecode: '0x608060405260405161083e38038061083e833981016040819052610...',
+ * })
+ */
+export async function deployContract< | Why can't we use the existing actions? |
permissionless.js | github_2023 | typescript | 214 | pimlicolabs | plusminushalf | @@ -0,0 +1,479 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type Hex,
+ type LocalAccount,
+ type Transport,
+ type TypedData,
+ type TypedDataDefinition,
+ concatHex,
+ encodeAbiParameters,
+ encodeFunctionData,
+ toHex,
+ zeroAddress
+} from "viem"
+import {
+ getChainId,
+ readContract,
+ signMessage as _signMessage
+} from "viem/actions"
+import { getAccountNonce } from "../../actions/public/getAccountNonce"
+import type { EntryPoint, Prettify } from "../../types"
+import { getEntryPointVersion } from "../../utils"
+import { getUserOperationHash } from "../../utils/getUserOperationHash"
+import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed"
+import { toSmartAccount } from "../toSmartAccount"
+import type { SmartAccount } from "../types"
+import {
+ SignTransactionNotSupportedBySmartAccount,
+ type SmartAccountSigner
+} from "../types"
+import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi"
+import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants"
+import { encodeCallData } from "./utils/encodeCallData"
+import { getInitMSAData } from "./utils/getInitMSAData"
+import { getNonceKeyWithEncoding } from "./utils/getNonceKey"
+import { signMessage } from "./utils/signMessage"
+import { signTypedData } from "./utils/signTypedData"
+
+export type EtherspotSmartAccount<
+ entryPoint extends EntryPoint,
+ transport extends Transport = Transport,
+ chain extends Chain | undefined = Chain | undefined
+> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain>
+
+/**
+ * The account creation ABI for a modular etherspot smart account
+ */
+const createAccountAbi = [
+ {
+ inputs: [
+ {
+ internalType: "bytes32",
+ name: "salt",
+ type: "bytes32"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ }
+ ],
+ name: "createAccount",
+ outputs: [
+ {
+ internalType: "address",
+ name: "",
+ type: "address"
+ }
+ ],
+ stateMutability: "payable",
+ type: "function"
+ }
+] as const
+
+type KERNEL_ADDRESSES = {
+ ecdsaValidatorAddress: Address
+ accountLogicAddress: Address
+ factoryAddress: Address
+ metaFactoryAddress: Address
+ bootstrapAddress: Address
+}
+
+/**
+ * Get default addresses for Etherspot Smart Account based on chainId
+ * @param chainId
+ * @param ecdsaValidatorAddress
+ * @param accountLogicAddress
+ * @param factoryAddress
+ * @param metaFactoryAddress
+ */
+const getDefaultAddresses = (
+ chainId: number,
+ {
+ ecdsaValidatorAddress: _ecdsaValidatorAddress,
+ accountLogicAddress: _accountLogicAddress,
+ factoryAddress: _factoryAddress,
+ metaFactoryAddress: _metaFactoryAddress
+ }: Partial<KERNEL_ADDRESSES>
+): KERNEL_ADDRESSES => {
+ const addresses = Networks[chainId]
+ const ecdsaValidatorAddress =
+ _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator
+ const accountLogicAddress =
+ _accountLogicAddress ?? addresses.modularEtherspotWallet
+ const factoryAddress =
+ _factoryAddress ?? addresses.modularEtherspotWalletFactory
+ const metaFactoryAddress =
+ _metaFactoryAddress ??
+ addresses?.modularEtherspotWalletFactory ??
+ zeroAddress
+ const bootstrapAddress = addresses.bootstrap ?? zeroAddress
+
+ return {
+ ecdsaValidatorAddress,
+ accountLogicAddress,
+ factoryAddress,
+ metaFactoryAddress,
+ bootstrapAddress
+ }
+}
+
+export const getEcdsaRootIdentifier = (validatorAddress: Address) => {
+ return concatHex([VALIDATOR_TYPE.VALIDATOR, validatorAddress])
+}
+
+/**
+ * Get the initialization data for a etherspot smart account
+ * @param entryPoint
+ * @param owner
+ * @param ecdsaValidatorAddress
+ */
+const getInitialisationData = <entryPoint extends EntryPoint>({
+ entryPoint: entryPointAddress,
+ owner,
+ ecdsaValidatorAddress,
+ bootstrapAddress
+}: {
+ entryPoint: entryPoint
+ owner: Address
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+}) => {
+ const entryPointVersion = getEntryPointVersion(entryPointAddress)
+
+ if (entryPointVersion === "v0.6") {
+ throw new Error("Only EntryPoint 0.7 is supported")
+ }
+
+ const initMSAData = getInitMSAData(ecdsaValidatorAddress)
+
+ const initCode = encodeAbiParameters(
+ [{ type: "address" }, { type: "address" }, { type: "bytes" }],
+ [owner, bootstrapAddress, initMSAData]
+ )
+
+ return initCode
+}
+
+/**
+ * Get the account initialization code for a etherspot smart account
+ * @param entryPoint
+ * @param owner
+ * @param index
+ * @param factoryAddress
+ * @param accountLogicAddress
+ * @param ecdsaValidatorAddress
+ */
+const getAccountInitCode = async <entryPoint extends EntryPoint>({
+ entryPoint: entryPointAddress,
+ owner,
+ index,
+ ecdsaValidatorAddress,
+ bootstrapAddress
+}: {
+ entryPoint: entryPoint
+ owner: Address
+ index: bigint
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+}): Promise<Hex> => {
+ if (!owner) throw new Error("Owner account not found")
+
+ // Build the account initialization data
+ const initialisationData = getInitialisationData({
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ owner,
+ bootstrapAddress
+ })
+
+ return encodeFunctionData({
+ abi: createAccountAbi,
+ functionName: "createAccount",
+ args: [toHex(index, { size: 32 }), initialisationData]
+ })
+}
+
+/**
+ * Check the validity of an existing account address, or fetch the pre-deterministic account address for a etherspot smart wallet
+ * @param client
+ * @param owner
+ * @param entryPoint
+ * @param ecdsaValidatorAddress
+ * @param initCodeProvider
+ * @param deployedAccountAddress
+ * @param factoryAddress
+ */
+const getAccountAddress = async <
+ entryPoint extends EntryPoint,
+ TTransport extends Transport = Transport,
+ TChain extends Chain | undefined = Chain | undefined
+>({
+ client,
+ owner,
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ bootstrapAddress,
+ factoryAddress,
+ index
+}: {
+ client: Client<TTransport, TChain>
+ owner: Address
+ factoryAddress: Address
+ entryPoint: entryPoint
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+ index: bigint
+}): Promise<Address> => {
+ const factoryData = getInitialisationData({
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ owner,
+ bootstrapAddress
+ })
+
+ return await readContract(client, {
+ address: factoryAddress,
+ abi: EtherspotWalletFactoryAbi,
+ functionName: "getAddress",
+ args: [toHex(index, { size: 32 }), factoryData]
+ })
+}
+
+export type SignerToEtherspotSmartAccountParameters<
+ entryPoint extends EntryPoint,
+ TSource extends string = string,
+ TAddress extends Address = Address
+> = Prettify<{
+ signer: SmartAccountSigner<TSource, TAddress>
+ entryPoint: entryPoint
+ address?: Address
+ index?: bigint
+ factoryAddress?: Address
+ metaFactoryAddress?: Address
+ accountLogicAddress?: Address
+ ecdsaValidatorAddress?: Address
+ deployedAccountAddress?: Address
+}>
+/**
+ * Build a etherspot smart account from a private key, that use the ECDSA signer behind the scene
+ * @param client
+ * @param privateKey
+ * @param entryPoint
+ * @param index
+ * @param factoryAddress
+ * @param accountLogicAddress
+ * @param ecdsaValidatorAddress
+ * @param deployedAccountAddress
+ */
+export async function signerToEtherspotSmartAccount<
+ entryPoint extends EntryPoint, | Make this to `entryPoint extends ENTRYPOINT_ADDRESS_V07_TYPE` so that users are aware of the type of entryPoint they can pass. |
permissionless.js | github_2023 | typescript | 214 | pimlicolabs | plusminushalf | @@ -0,0 +1,479 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type Hex,
+ type LocalAccount,
+ type Transport,
+ type TypedData,
+ type TypedDataDefinition,
+ concatHex,
+ encodeAbiParameters,
+ encodeFunctionData,
+ toHex,
+ zeroAddress
+} from "viem"
+import {
+ getChainId,
+ readContract,
+ signMessage as _signMessage
+} from "viem/actions"
+import { getAccountNonce } from "../../actions/public/getAccountNonce"
+import type { EntryPoint, Prettify } from "../../types"
+import { getEntryPointVersion } from "../../utils"
+import { getUserOperationHash } from "../../utils/getUserOperationHash"
+import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed"
+import { toSmartAccount } from "../toSmartAccount"
+import type { SmartAccount } from "../types"
+import {
+ SignTransactionNotSupportedBySmartAccount,
+ type SmartAccountSigner
+} from "../types"
+import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi"
+import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants"
+import { encodeCallData } from "./utils/encodeCallData"
+import { getInitMSAData } from "./utils/getInitMSAData"
+import { getNonceKeyWithEncoding } from "./utils/getNonceKey"
+import { signMessage } from "./utils/signMessage"
+import { signTypedData } from "./utils/signTypedData"
+
+export type EtherspotSmartAccount<
+ entryPoint extends EntryPoint,
+ transport extends Transport = Transport,
+ chain extends Chain | undefined = Chain | undefined
+> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain>
+
+/**
+ * The account creation ABI for a modular etherspot smart account
+ */
+const createAccountAbi = [
+ {
+ inputs: [
+ {
+ internalType: "bytes32",
+ name: "salt",
+ type: "bytes32"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ }
+ ],
+ name: "createAccount",
+ outputs: [
+ {
+ internalType: "address",
+ name: "",
+ type: "address"
+ }
+ ],
+ stateMutability: "payable",
+ type: "function"
+ }
+] as const
+
+type KERNEL_ADDRESSES = {
+ ecdsaValidatorAddress: Address
+ accountLogicAddress: Address
+ factoryAddress: Address
+ metaFactoryAddress: Address
+ bootstrapAddress: Address
+}
+
+/**
+ * Get default addresses for Etherspot Smart Account based on chainId
+ * @param chainId
+ * @param ecdsaValidatorAddress
+ * @param accountLogicAddress
+ * @param factoryAddress
+ * @param metaFactoryAddress
+ */
+const getDefaultAddresses = (
+ chainId: number,
+ {
+ ecdsaValidatorAddress: _ecdsaValidatorAddress,
+ accountLogicAddress: _accountLogicAddress,
+ factoryAddress: _factoryAddress,
+ metaFactoryAddress: _metaFactoryAddress
+ }: Partial<KERNEL_ADDRESSES>
+): KERNEL_ADDRESSES => {
+ const addresses = Networks[chainId]
+ const ecdsaValidatorAddress =
+ _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator
+ const accountLogicAddress =
+ _accountLogicAddress ?? addresses.modularEtherspotWallet
+ const factoryAddress =
+ _factoryAddress ?? addresses.modularEtherspotWalletFactory
+ const metaFactoryAddress =
+ _metaFactoryAddress ??
+ addresses?.modularEtherspotWalletFactory ??
+ zeroAddress
+ const bootstrapAddress = addresses.bootstrap ?? zeroAddress
+
+ return {
+ ecdsaValidatorAddress,
+ accountLogicAddress,
+ factoryAddress,
+ metaFactoryAddress,
+ bootstrapAddress
+ }
+}
+
+export const getEcdsaRootIdentifier = (validatorAddress: Address) => {
+ return concatHex([VALIDATOR_TYPE.VALIDATOR, validatorAddress])
+}
+
+/**
+ * Get the initialization data for a etherspot smart account
+ * @param entryPoint
+ * @param owner
+ * @param ecdsaValidatorAddress
+ */
+const getInitialisationData = <entryPoint extends EntryPoint>({
+ entryPoint: entryPointAddress,
+ owner,
+ ecdsaValidatorAddress,
+ bootstrapAddress
+}: {
+ entryPoint: entryPoint
+ owner: Address
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+}) => {
+ const entryPointVersion = getEntryPointVersion(entryPointAddress)
+
+ if (entryPointVersion === "v0.6") {
+ throw new Error("Only EntryPoint 0.7 is supported")
+ }
+
+ const initMSAData = getInitMSAData(ecdsaValidatorAddress)
+
+ const initCode = encodeAbiParameters(
+ [{ type: "address" }, { type: "address" }, { type: "bytes" }],
+ [owner, bootstrapAddress, initMSAData]
+ )
+
+ return initCode
+}
+
+/**
+ * Get the account initialization code for a etherspot smart account
+ * @param entryPoint
+ * @param owner
+ * @param index
+ * @param factoryAddress
+ * @param accountLogicAddress
+ * @param ecdsaValidatorAddress
+ */
+const getAccountInitCode = async <entryPoint extends EntryPoint>({
+ entryPoint: entryPointAddress,
+ owner,
+ index,
+ ecdsaValidatorAddress,
+ bootstrapAddress
+}: {
+ entryPoint: entryPoint
+ owner: Address
+ index: bigint
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+}): Promise<Hex> => {
+ if (!owner) throw new Error("Owner account not found")
+
+ // Build the account initialization data
+ const initialisationData = getInitialisationData({
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ owner,
+ bootstrapAddress
+ })
+
+ return encodeFunctionData({
+ abi: createAccountAbi,
+ functionName: "createAccount",
+ args: [toHex(index, { size: 32 }), initialisationData]
+ })
+}
+
+/**
+ * Check the validity of an existing account address, or fetch the pre-deterministic account address for a etherspot smart wallet
+ * @param client
+ * @param owner
+ * @param entryPoint
+ * @param ecdsaValidatorAddress
+ * @param initCodeProvider
+ * @param deployedAccountAddress
+ * @param factoryAddress
+ */
+const getAccountAddress = async <
+ entryPoint extends EntryPoint,
+ TTransport extends Transport = Transport,
+ TChain extends Chain | undefined = Chain | undefined
+>({
+ client,
+ owner,
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ bootstrapAddress,
+ factoryAddress,
+ index
+}: {
+ client: Client<TTransport, TChain>
+ owner: Address
+ factoryAddress: Address
+ entryPoint: entryPoint
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+ index: bigint
+}): Promise<Address> => {
+ const factoryData = getInitialisationData({
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ owner,
+ bootstrapAddress
+ })
+
+ return await readContract(client, {
+ address: factoryAddress,
+ abi: EtherspotWalletFactoryAbi,
+ functionName: "getAddress",
+ args: [toHex(index, { size: 32 }), factoryData]
+ })
+}
+
+export type SignerToEtherspotSmartAccountParameters<
+ entryPoint extends EntryPoint,
+ TSource extends string = string,
+ TAddress extends Address = Address
+> = Prettify<{
+ signer: SmartAccountSigner<TSource, TAddress>
+ entryPoint: entryPoint
+ address?: Address
+ index?: bigint
+ factoryAddress?: Address
+ metaFactoryAddress?: Address
+ accountLogicAddress?: Address
+ ecdsaValidatorAddress?: Address
+ deployedAccountAddress?: Address
+}>
+/**
+ * Build a etherspot smart account from a private key, that use the ECDSA signer behind the scene
+ * @param client
+ * @param privateKey
+ * @param entryPoint
+ * @param index
+ * @param factoryAddress
+ * @param accountLogicAddress
+ * @param ecdsaValidatorAddress
+ * @param deployedAccountAddress
+ */
+export async function signerToEtherspotSmartAccount<
+ entryPoint extends EntryPoint,
+ TTransport extends Transport = Transport,
+ TChain extends Chain | undefined = Chain | undefined,
+ TSource extends string = string,
+ TAddress extends Address = Address
+>(
+ client: Client<TTransport, TChain, undefined>, | `undefined` is not needed. |
permissionless.js | github_2023 | typescript | 214 | pimlicolabs | plusminushalf | @@ -0,0 +1,479 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type Hex,
+ type LocalAccount,
+ type Transport,
+ type TypedData,
+ type TypedDataDefinition,
+ concatHex,
+ encodeAbiParameters,
+ encodeFunctionData,
+ toHex,
+ zeroAddress
+} from "viem"
+import {
+ getChainId,
+ readContract,
+ signMessage as _signMessage
+} from "viem/actions"
+import { getAccountNonce } from "../../actions/public/getAccountNonce"
+import type { EntryPoint, Prettify } from "../../types"
+import { getEntryPointVersion } from "../../utils"
+import { getUserOperationHash } from "../../utils/getUserOperationHash"
+import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed"
+import { toSmartAccount } from "../toSmartAccount"
+import type { SmartAccount } from "../types"
+import {
+ SignTransactionNotSupportedBySmartAccount,
+ type SmartAccountSigner
+} from "../types"
+import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi"
+import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants"
+import { encodeCallData } from "./utils/encodeCallData"
+import { getInitMSAData } from "./utils/getInitMSAData"
+import { getNonceKeyWithEncoding } from "./utils/getNonceKey"
+import { signMessage } from "./utils/signMessage"
+import { signTypedData } from "./utils/signTypedData"
+
+export type EtherspotSmartAccount<
+ entryPoint extends EntryPoint,
+ transport extends Transport = Transport,
+ chain extends Chain | undefined = Chain | undefined
+> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain>
+
+/**
+ * The account creation ABI for a modular etherspot smart account
+ */
+const createAccountAbi = [
+ {
+ inputs: [
+ {
+ internalType: "bytes32",
+ name: "salt",
+ type: "bytes32"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ }
+ ],
+ name: "createAccount",
+ outputs: [
+ {
+ internalType: "address",
+ name: "",
+ type: "address"
+ }
+ ],
+ stateMutability: "payable",
+ type: "function"
+ }
+] as const
+
+type KERNEL_ADDRESSES = {
+ ecdsaValidatorAddress: Address
+ accountLogicAddress: Address
+ factoryAddress: Address
+ metaFactoryAddress: Address
+ bootstrapAddress: Address
+}
+
+/**
+ * Get default addresses for Etherspot Smart Account based on chainId
+ * @param chainId
+ * @param ecdsaValidatorAddress
+ * @param accountLogicAddress
+ * @param factoryAddress
+ * @param metaFactoryAddress
+ */
+const getDefaultAddresses = (
+ chainId: number,
+ {
+ ecdsaValidatorAddress: _ecdsaValidatorAddress,
+ accountLogicAddress: _accountLogicAddress,
+ factoryAddress: _factoryAddress,
+ metaFactoryAddress: _metaFactoryAddress
+ }: Partial<KERNEL_ADDRESSES>
+): KERNEL_ADDRESSES => {
+ const addresses = Networks[chainId]
+ const ecdsaValidatorAddress =
+ _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator
+ const accountLogicAddress =
+ _accountLogicAddress ?? addresses.modularEtherspotWallet
+ const factoryAddress =
+ _factoryAddress ?? addresses.modularEtherspotWalletFactory
+ const metaFactoryAddress =
+ _metaFactoryAddress ??
+ addresses?.modularEtherspotWalletFactory ??
+ zeroAddress
+ const bootstrapAddress = addresses.bootstrap ?? zeroAddress
+
+ return {
+ ecdsaValidatorAddress,
+ accountLogicAddress,
+ factoryAddress,
+ metaFactoryAddress,
+ bootstrapAddress
+ }
+}
+
+export const getEcdsaRootIdentifier = (validatorAddress: Address) => {
+ return concatHex([VALIDATOR_TYPE.VALIDATOR, validatorAddress])
+}
+
+/**
+ * Get the initialization data for a etherspot smart account
+ * @param entryPoint
+ * @param owner
+ * @param ecdsaValidatorAddress
+ */
+const getInitialisationData = <entryPoint extends EntryPoint>({
+ entryPoint: entryPointAddress,
+ owner,
+ ecdsaValidatorAddress,
+ bootstrapAddress
+}: {
+ entryPoint: entryPoint
+ owner: Address
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+}) => {
+ const entryPointVersion = getEntryPointVersion(entryPointAddress)
+
+ if (entryPointVersion === "v0.6") {
+ throw new Error("Only EntryPoint 0.7 is supported")
+ }
+
+ const initMSAData = getInitMSAData(ecdsaValidatorAddress)
+
+ const initCode = encodeAbiParameters(
+ [{ type: "address" }, { type: "address" }, { type: "bytes" }],
+ [owner, bootstrapAddress, initMSAData]
+ )
+
+ return initCode
+}
+
+/**
+ * Get the account initialization code for a etherspot smart account
+ * @param entryPoint
+ * @param owner
+ * @param index
+ * @param factoryAddress
+ * @param accountLogicAddress
+ * @param ecdsaValidatorAddress
+ */
+const getAccountInitCode = async <entryPoint extends EntryPoint>({
+ entryPoint: entryPointAddress,
+ owner,
+ index,
+ ecdsaValidatorAddress,
+ bootstrapAddress
+}: {
+ entryPoint: entryPoint
+ owner: Address
+ index: bigint
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+}): Promise<Hex> => {
+ if (!owner) throw new Error("Owner account not found")
+
+ // Build the account initialization data
+ const initialisationData = getInitialisationData({
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ owner,
+ bootstrapAddress
+ })
+
+ return encodeFunctionData({
+ abi: createAccountAbi,
+ functionName: "createAccount",
+ args: [toHex(index, { size: 32 }), initialisationData]
+ })
+}
+
+/**
+ * Check the validity of an existing account address, or fetch the pre-deterministic account address for a etherspot smart wallet
+ * @param client
+ * @param owner
+ * @param entryPoint
+ * @param ecdsaValidatorAddress
+ * @param initCodeProvider
+ * @param deployedAccountAddress
+ * @param factoryAddress
+ */
+const getAccountAddress = async <
+ entryPoint extends EntryPoint,
+ TTransport extends Transport = Transport,
+ TChain extends Chain | undefined = Chain | undefined
+>({
+ client,
+ owner,
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ bootstrapAddress,
+ factoryAddress,
+ index
+}: {
+ client: Client<TTransport, TChain>
+ owner: Address
+ factoryAddress: Address
+ entryPoint: entryPoint
+ ecdsaValidatorAddress: Address
+ bootstrapAddress: Address
+ index: bigint
+}): Promise<Address> => {
+ const factoryData = getInitialisationData({
+ entryPoint: entryPointAddress,
+ ecdsaValidatorAddress,
+ owner,
+ bootstrapAddress
+ })
+
+ return await readContract(client, {
+ address: factoryAddress,
+ abi: EtherspotWalletFactoryAbi,
+ functionName: "getAddress",
+ args: [toHex(index, { size: 32 }), factoryData]
+ })
+}
+
+export type SignerToEtherspotSmartAccountParameters<
+ entryPoint extends EntryPoint,
+ TSource extends string = string,
+ TAddress extends Address = Address
+> = Prettify<{
+ signer: SmartAccountSigner<TSource, TAddress>
+ entryPoint: entryPoint
+ address?: Address
+ index?: bigint
+ factoryAddress?: Address
+ metaFactoryAddress?: Address
+ accountLogicAddress?: Address
+ ecdsaValidatorAddress?: Address
+ deployedAccountAddress?: Address
+}>
+/**
+ * Build a etherspot smart account from a private key, that use the ECDSA signer behind the scene
+ * @param client
+ * @param privateKey
+ * @param entryPoint
+ * @param index
+ * @param factoryAddress
+ * @param accountLogicAddress
+ * @param ecdsaValidatorAddress
+ * @param deployedAccountAddress
+ */
+export async function signerToEtherspotSmartAccount<
+ entryPoint extends EntryPoint,
+ TTransport extends Transport = Transport,
+ TChain extends Chain | undefined = Chain | undefined,
+ TSource extends string = string,
+ TAddress extends Address = Address
+>(
+ client: Client<TTransport, TChain, undefined>,
+ {
+ signer,
+ address,
+ entryPoint: entryPointAddress,
+ index = BigInt(0),
+ factoryAddress: _factoryAddress,
+ metaFactoryAddress: _metaFactoryAddress,
+ accountLogicAddress: _accountLogicAddress,
+ ecdsaValidatorAddress: _ecdsaValidatorAddress
+ }: SignerToEtherspotSmartAccountParameters<entryPoint, TSource, TAddress>
+): Promise<EtherspotSmartAccount<entryPoint, TTransport, TChain>> {
+ const entryPointVersion = getEntryPointVersion(entryPointAddress)
+
+ if (entryPointVersion === "v0.6") {
+ throw new Error("Only EntryPoint 0.7 is supported")
+ }
+
+ const chainID = await getChainId(client) | We can check if client already have a chain by `client.chain?.id ?? getChainId(client)` |
permissionless.js | github_2023 | typescript | 214 | pimlicolabs | plusminushalf | @@ -0,0 +1,479 @@
+import {
+ type Address,
+ type Chain,
+ type Client,
+ type Hex,
+ type LocalAccount,
+ type Transport,
+ type TypedData,
+ type TypedDataDefinition,
+ concatHex,
+ encodeAbiParameters,
+ encodeFunctionData,
+ toHex,
+ zeroAddress
+} from "viem"
+import {
+ getChainId,
+ readContract,
+ signMessage as _signMessage
+} from "viem/actions"
+import { getAccountNonce } from "../../actions/public/getAccountNonce"
+import type { EntryPoint, Prettify } from "../../types"
+import { getEntryPointVersion } from "../../utils"
+import { getUserOperationHash } from "../../utils/getUserOperationHash"
+import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed"
+import { toSmartAccount } from "../toSmartAccount"
+import type { SmartAccount } from "../types"
+import {
+ SignTransactionNotSupportedBySmartAccount,
+ type SmartAccountSigner
+} from "../types"
+import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi"
+import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants"
+import { encodeCallData } from "./utils/encodeCallData"
+import { getInitMSAData } from "./utils/getInitMSAData"
+import { getNonceKeyWithEncoding } from "./utils/getNonceKey"
+import { signMessage } from "./utils/signMessage"
+import { signTypedData } from "./utils/signTypedData"
+
+export type EtherspotSmartAccount<
+ entryPoint extends EntryPoint,
+ transport extends Transport = Transport,
+ chain extends Chain | undefined = Chain | undefined
+> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain>
+
+/**
+ * The account creation ABI for a modular etherspot smart account
+ */
+const createAccountAbi = [
+ {
+ inputs: [
+ {
+ internalType: "bytes32",
+ name: "salt",
+ type: "bytes32"
+ },
+ {
+ internalType: "bytes",
+ name: "initCode",
+ type: "bytes"
+ }
+ ],
+ name: "createAccount",
+ outputs: [
+ {
+ internalType: "address",
+ name: "",
+ type: "address"
+ }
+ ],
+ stateMutability: "payable",
+ type: "function"
+ }
+] as const
+
+type KERNEL_ADDRESSES = {
+ ecdsaValidatorAddress: Address
+ accountLogicAddress: Address
+ factoryAddress: Address
+ metaFactoryAddress: Address
+ bootstrapAddress: Address
+}
+
+/**
+ * Get default addresses for Etherspot Smart Account based on chainId
+ * @param chainId
+ * @param ecdsaValidatorAddress
+ * @param accountLogicAddress
+ * @param factoryAddress
+ * @param metaFactoryAddress
+ */
+const getDefaultAddresses = (
+ chainId: number,
+ {
+ ecdsaValidatorAddress: _ecdsaValidatorAddress,
+ accountLogicAddress: _accountLogicAddress,
+ factoryAddress: _factoryAddress,
+ metaFactoryAddress: _metaFactoryAddress
+ }: Partial<KERNEL_ADDRESSES>
+): KERNEL_ADDRESSES => {
+ const addresses = Networks[chainId] | Can we check if the chainId is supported or not, as addresses can be undefined. in safe we also have similar implementation but we don't check because we have a type check on all the types of versions that can be passed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.