@nevermined-io/core-kit 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { signerToEcdsaValidator } from '@zerodev/ecdsa-validator';
|
|
1
2
|
import { KernelAccountClient } from '@zerodev/sdk';
|
|
2
3
|
import { Address, type Abi, type AbiEvent, type AbiFunction, type Account, type PublicClient, type TransactionReceipt } from 'viem';
|
|
3
4
|
import { SmartAccount } from 'viem/account-abstraction';
|
|
@@ -295,10 +296,30 @@ export declare function estimateUserOperationFees(bundlerClient: any, _publicCli
|
|
|
295
296
|
* @returns the kernel client
|
|
296
297
|
*/
|
|
297
298
|
export declare function createKernelClient(kernelAccount: SmartAccount, chainId: number, zeroDevProjectId: string, publicClient: any, useUltraRelay?: boolean): Promise<KernelAccountClient>;
|
|
298
|
-
export
|
|
299
|
+
export type EcdsaValidator = Awaited<ReturnType<typeof signerToEcdsaValidator>>;
|
|
300
|
+
/**
|
|
301
|
+
* Identifies the smart-account derivation inputs (entryPoint + kernel version).
|
|
302
|
+
* The SCA is deterministic from `(EOA, entryPoint, kernelVersion, index)`, so a
|
|
303
|
+
* bump here means the same EOA derives a different SCA. Persisted SCA caches
|
|
304
|
+
* (e.g. the webapp's localStorage) should stamp this and invalidate on change.
|
|
305
|
+
*/
|
|
306
|
+
export declare const SCA_DERIVATION_VERSION: string;
|
|
307
|
+
/**
|
|
308
|
+
* Build the ECDSA sudo validator for a signer. Both `createKernelSmartAccount`
|
|
309
|
+
* and `createSessionKey` need this validator and each derives it via a ZeroDev
|
|
310
|
+
* RPC round-trip. Callers that run both in sequence (e.g. the webapp API-key
|
|
311
|
+
* creation path) can compute it once here and pass it into both helpers to
|
|
312
|
+
* avoid the redundant round-trip.
|
|
313
|
+
*
|
|
314
|
+
* @param ecdsaValidator (on the consumers) must be one built for the SAME
|
|
315
|
+
* `signer` — passing a validator derived from a different signer would attach
|
|
316
|
+
* the wrong owner to the account.
|
|
317
|
+
*/
|
|
318
|
+
export declare function createEcdsaValidator(signer: Signer, publicClient: PublicClient): Promise<EcdsaValidator>;
|
|
319
|
+
export declare function createKernelSmartAccount(signer: Signer, publicClient: PublicClient, ecdsaValidator?: EcdsaValidator): Promise<SmartAccount>;
|
|
299
320
|
export declare function getApproval(signer: Signer, publicClient: any, policies: any[]): Promise<string>;
|
|
300
321
|
export declare function useSessionKey(approval: string, signer: Signer, publicClient: any): Promise<import("@zerodev/sdk").CreateKernelAccountReturnType<"0.7">>;
|
|
301
|
-
export declare function createSessionKey(signer: Signer, publicClient: any, policies: any[]): Promise<string>;
|
|
322
|
+
export declare function createSessionKey(signer: Signer, publicClient: any, policies: any[], ecdsaValidator?: EcdsaValidator): Promise<string>;
|
|
302
323
|
export declare function getSessionKey(serializedSessionKey: string, publicClient: any): Promise<import("@zerodev/sdk").CreateKernelAccountReturnType<"0.7">>;
|
|
303
324
|
/**
|
|
304
325
|
* Creates a delegated session key for an existing kernel account.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BlockchainViemUtils.d.ts","sourceRoot":"","sources":["../../../src/nevermined/utils/BlockchainViemUtils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"BlockchainViemUtils.d.ts","sourceRoot":"","sources":["../../../src/nevermined/utils/BlockchainViemUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AAOjE,OAAO,EAML,mBAAmB,EAEpB,MAAM,cAAc,CAAA;AAErB,OAAO,EACL,OAAO,EAYP,KAAK,GAAG,EACR,KAAK,QAAQ,EACb,KAAK,WAAW,EAChB,KAAK,OAAO,EACZ,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACxB,MAAM,MAAM,CAAA;AACb,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAQvD,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,WAAW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AAE,GAAG,EAAE,EACf,cAAc,CAAC,EAAE,cAAc,mBA0BhC;AAED,wBAAsB,aAAa,CAAC,oBAAoB,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,wEASlF;AAED;;;;;;;;;GASG;AACH,wBAAsB,mCAAmC,CACvD,aAAa,EAAE,YAAY,EAC3B,YAAY,EAAE,YAAY,EAC1B,QAAQ,EAAE,GAAG,EAAE,GACd,OAAO,CAAC,MAAM,CAAC,CAsCjB;AAED,eAAO,MAAM,WAAW;;;;;CAKvB,CAAA"}
|
|
@@ -317,15 +317,34 @@ const TRANSACTION_RECEIPT_POLLING_INTERVAL_MS = 1_500;
|
|
|
317
317
|
}
|
|
318
318
|
});
|
|
319
319
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
320
|
+
/**
|
|
321
|
+
* Identifies the smart-account derivation inputs (entryPoint + kernel version).
|
|
322
|
+
* The SCA is deterministic from `(EOA, entryPoint, kernelVersion, index)`, so a
|
|
323
|
+
* bump here means the same EOA derives a different SCA. Persisted SCA caches
|
|
324
|
+
* (e.g. the webapp's localStorage) should stamp this and invalidate on change.
|
|
325
|
+
*/ export const SCA_DERIVATION_VERSION = `${ENTRY_POINT_VERSION}:${KERNEL_V3_1}`;
|
|
326
|
+
/**
|
|
327
|
+
* Build the ECDSA sudo validator for a signer. Both `createKernelSmartAccount`
|
|
328
|
+
* and `createSessionKey` need this validator and each derives it via a ZeroDev
|
|
329
|
+
* RPC round-trip. Callers that run both in sequence (e.g. the webapp API-key
|
|
330
|
+
* creation path) can compute it once here and pass it into both helpers to
|
|
331
|
+
* avoid the redundant round-trip.
|
|
332
|
+
*
|
|
333
|
+
* @param ecdsaValidator (on the consumers) must be one built for the SAME
|
|
334
|
+
* `signer` — passing a validator derived from a different signer would attach
|
|
335
|
+
* the wrong owner to the account.
|
|
336
|
+
*/ export async function createEcdsaValidator(signer, publicClient) {
|
|
337
|
+
return signerToEcdsaValidator(publicClient, {
|
|
338
|
+
signer,
|
|
323
339
|
entryPoint: getEntryPoint(ENTRY_POINT_VERSION),
|
|
324
340
|
kernelVersion: KERNEL_V3_1
|
|
325
341
|
});
|
|
342
|
+
}
|
|
343
|
+
export async function createKernelSmartAccount(signer, publicClient, ecdsaValidator) {
|
|
344
|
+
const validator = ecdsaValidator ?? await createEcdsaValidator(signer, publicClient);
|
|
326
345
|
return await createKernelAccount(publicClient, {
|
|
327
346
|
plugins: {
|
|
328
|
-
sudo:
|
|
347
|
+
sudo: validator
|
|
329
348
|
},
|
|
330
349
|
entryPoint: getEntryPoint(ENTRY_POINT_VERSION),
|
|
331
350
|
kernelVersion: KERNEL_V3_1
|
|
@@ -364,12 +383,8 @@ export async function useSessionKey(approval, signer, publicClient) {
|
|
|
364
383
|
const sessionKeyAccount = await deserializePermissionAccount(publicClient, getEntryPoint(ENTRY_POINT_VERSION), KERNEL_V3_1, approval, sessionKeySigner);
|
|
365
384
|
return sessionKeyAccount;
|
|
366
385
|
}
|
|
367
|
-
export async function createSessionKey(signer, publicClient, policies) {
|
|
368
|
-
const
|
|
369
|
-
entryPoint: getEntryPoint(ENTRY_POINT_VERSION),
|
|
370
|
-
signer,
|
|
371
|
-
kernelVersion: KERNEL_V3_1
|
|
372
|
-
});
|
|
386
|
+
export async function createSessionKey(signer, publicClient, policies, ecdsaValidator) {
|
|
387
|
+
const validator = ecdsaValidator ?? await createEcdsaValidator(signer, publicClient);
|
|
373
388
|
const sessionPrivateKey = generatePrivateKey();
|
|
374
389
|
const masterAccount = privateKeyToAccount(sessionPrivateKey);
|
|
375
390
|
const sessionKeySigner = await toECDSASigner({
|
|
@@ -384,7 +399,7 @@ export async function createSessionKey(signer, publicClient, policies) {
|
|
|
384
399
|
const sessionKeyAccount = await createKernelAccount(publicClient, {
|
|
385
400
|
entryPoint: getEntryPoint(ENTRY_POINT_VERSION),
|
|
386
401
|
plugins: {
|
|
387
|
-
sudo:
|
|
402
|
+
sudo: validator,
|
|
388
403
|
regular: permissionPlugin
|
|
389
404
|
},
|
|
390
405
|
kernelVersion: KERNEL_V3_1
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/nevermined/utils/BlockchainViemUtils.ts"],"sourcesContent":["import { signerToEcdsaValidator } from '@zerodev/ecdsa-validator'\nimport {\n deserializePermissionAccount,\n serializePermissionAccount,\n toPermissionValidator,\n} from '@zerodev/permissions'\nimport { toECDSASigner } from '@zerodev/permissions/signers'\nimport {\n addressToEmptyAccount,\n createKernelAccount,\n createKernelAccountClient,\n createZeroDevPaymasterClient,\n getUserOperationGasPrice,\n KernelAccountClient,\n type KernelSmartAccountImplementation,\n} from '@zerodev/sdk'\nimport { KERNEL_V3_1, getEntryPoint } from '@zerodev/sdk/constants'\nimport {\n Address,\n encodeAbiParameters,\n getAbiItem,\n getAddress,\n getContract,\n http,\n isAddress,\n pad,\n stringToBytes,\n stringToHex,\n toBytes,\n keccak256 as viemKeccak256,\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type Account,\n type PublicClient,\n type TransactionReceipt,\n} from 'viem'\nimport { SmartAccount } from 'viem/account-abstraction'\nimport {\n english,\n generateMnemonic,\n generatePrivateKey,\n mnemonicToAccount,\n privateKeyToAccount,\n} from 'viem/accounts'\nimport { Instantiable, InstantiableConfig, Web3Clients } from '../../Instantiable.abstract.js'\nimport { ContractsError } from '../../errors/NeverminedErrors.js'\nimport { getChain } from '../../utils/Network.js'\nimport { Signer } from '@zerodev/sdk/types'\n\nconst ENTRY_POINT_VERSION = '0.7'\n\n/**\n * Utility class with methods that allow the interaction with the blockchain.\n * This class uses Viem library to interact with the blockchain.\n */\nexport class BlockchainViemUtils extends Instantiable {\n constructor(config: InstantiableConfig) {\n super()\n this.setInstanceConfig(config)\n }\n}\n\n//////////////////////////\n///// UTILITIES //////////\n//////////////////////////\n\n///// CONTRACTS\n\n// Wait budget for an L2 block to be mined and the receipt to surface.\n// Base / Base Sepolia block time is ~2s; 30s ≈ 15 blocks of headroom.\nconst TRANSACTION_RECEIPT_TIMEOUT_MS = 30_000\nconst TRANSACTION_RECEIPT_POLLING_INTERVAL_MS = 1_500\n\n/**\n * Given a transaction hash, it returns the transaction receipt.\n * Uses viem's `waitForTransactionReceipt` which polls until the receipt is\n * available, retrying on `TransactionReceiptNotFoundError` and handling\n * tx-replacement / reorgs natively.\n * @param txHash - the transaction hash\n * @returns the transaction receipt\n */\nexport async function getTransactionReceipt({\n txHash,\n publicClient,\n}: {\n txHash: `0x${string}`\n publicClient: PublicClient\n iteration?: number\n}): Promise<TransactionReceipt> {\n try {\n return await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: TRANSACTION_RECEIPT_TIMEOUT_MS,\n pollingInterval: TRANSACTION_RECEIPT_POLLING_INTERVAL_MS,\n confirmations: 1,\n })\n } catch (error) {\n throw new ContractsError(\n `Unable to get transaction receipt with hash: ${txHash}. Error: ${error}`,\n )\n }\n}\n\n/**\n * Given an already deployed contract address and the ABI, it returns the contract instance.\n *\n * @param contractAddress - the contract address\n * @param abi - the contract artifact\n * @param client - the client to interact with the blockchain\n * @returns a contract instance\n */\nexport async function getContractInstance(contractAddress: string, abi: Abi, client: Web3Clients) {\n return getContract({\n abi,\n address: contractAddress as `0x${string}`,\n client: { wallet: client.wallet, public: client.public },\n })\n}\n\n///// ABIs\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function searchAbiFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n const func = getAbiItem({ abi, name: funcName, args })\n if (!func || func.type !== 'function') {\n throw new ContractsError(`Function \"${funcName}\" is not part of contract`)\n }\n return func as AbiFunction\n}\n\n/**\n * It searchs an ABI event in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the event name\n * @returns the event found\n */\nexport function searchAbiEvent(abi: Abi, eventName: string): AbiEvent {\n const event = getAbiItem({\n abi,\n name: eventName,\n })\n if (!event || event.type !== 'event') {\n throw new ContractsError(`Event \"${event}\" is not part of contract`)\n }\n return event as AbiEvent\n}\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getSignatureOfFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n return searchAbiFunction(abi, funcName, args)\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunction(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs formatted.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunctionFormatted(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs.map((input, i) => {\n return {\n name: input.name,\n value: args[i],\n }\n })\n}\n\n//////// UTILS\n\n/**\n * Given an address it returns that address in checksum format.\n * @param address the address\n * @returns the same address in checksum format\n */\nexport function getChecksumAddress(address: string): string {\n return getAddress(address)\n}\n\n/**\n * It checks if the address is a valid address.\n * @param address the address to check\n * @returns true of the address is valid\n */\nexport function isValidAddress(address: string): boolean {\n return isAddress(address)\n}\n\n/**\n * Encodes a UTF-8 string into a byte array.\n\n * @param message the string to encode\n * @returns the encoded byte array\n */\nexport function getBytes(message: string): Uint8Array {\n return stringToBytes(message)\n}\n\n/**\n * It pads a value with zeros.\n * @param value the value to pad\n * @param length the expected longitutde of the value\n * @returns the padded value\n */\nexport function zeroPadValue(value: `0x${string}` | Uint8Array, length: number): string {\n return pad(value, { size: length }) as `0x${string}`\n}\n\n/**\n * Encodes a UTF-8 string into a hex string\n * @param message the string to encode\n * @returns the hex string\n */\nexport function encodeBytes32String(message: string) {\n return stringToHex(message, { size: 32 })\n}\n\n////// ACCOUNTS\n/**\n * Given a seedphrase, it returns an account.\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param addressIndex - the address index\n * @returns an account\n */\nexport function makeWallet(seedphrase: string, addressIndex = 0): Account {\n return mnemonicToAccount(seedphrase, { addressIndex })\n}\n\n/**\n * Given a seedphrase generates multiple accounts\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeWallets(seedphrase: string, numAccounts = 10) {\n const accounts: Account[] = []\n for (let i = 0; i < numAccounts; i++) {\n accounts.push(makeWallet(seedphrase, i))\n }\n return accounts\n}\n\n/**\n * It generates a random account.\n * @returns a new account\n */\nexport function makeRandomWallet(): Account {\n const mnemonic = generateMnemonic(english)\n return makeWallet(mnemonic)\n}\n\n/**\n * It generates a list of random accounts\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeRandomWallets(numAccounts = 10): Account[] {\n const mnemonic = generateMnemonic(english)\n return makeWallets(mnemonic, numAccounts)\n}\n\n/////// HASHES\n\n/**\n * It hashes a string using keccak256.\n * @param seed the string to hash\n * @returns the hash\n */\nexport function keccak256(seed: string): string {\n return viemKeccak256(toBytes(seed))\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256WithEncode(types: any[], values: any[]): string {\n const encoded = encodeAbiParameters(types, values as never)\n return keccak256(encoded)\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256Packed(types: any[], values: any[]): string {\n return keccak256WithEncode(types, values)\n}\n\n/////// ZERO DEV\n\n/**\n * Returns the bundler RPC URL. When `BUNDLER_RPC_URL_OVERRIDE` is set\n * (used by tests against a local Alto + anvil-fork stack), it takes precedence\n * over the canonical ZeroDev URL. When `useUltraRelay` is true, the production\n * URL is routed through ZeroDev's UltraRelay (`?provider=ULTRA_RELAY`); the\n * override branch is left untouched.\n * @param useUltraRelay - when true, append `?provider=ULTRA_RELAY` to route the\n * UserOperation through ZeroDev's UltraRelay bundler tier. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n */\nexport function getBundlerRpcUrl(\n zeroDevProjectId: string,\n chainId: number,\n useUltraRelay = false,\n): string {\n const base = `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n // `||` (not `??`) because Vite replaces missing browser env vars with the\n // empty string at build time; an empty override is equivalent to \"no\n // override\" for our purposes.\n return (\n process.env.BUNDLER_RPC_URL_OVERRIDE || (useUltraRelay ? `${base}?provider=ULTRA_RELAY` : base)\n )\n}\n\n/**\n * Returns the paymaster RPC URL (ZeroDev-only; the local fork stack uses\n * `ultra-relay` which sponsors via the bundler's executor key without a\n * paymaster, so this URL is not consulted when `BUNDLER_RPC_URL_OVERRIDE` is\n * set).\n */\nexport function getPaymasterRpcUrl(zeroDevProjectId: string, chainId: number): string {\n return `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n}\n\n/**\n * Returns true when the kernel client should run in \"relayer mode\" — no\n * paymaster, gas fees zeroed out. Used by tests against a local\n * `ultra-relay` (ZeroDev's fork of Alto) on top of an anvil-fork. The relayer's\n * executor key pays gas directly via `EntryPoint.handleOps`, avoiding the\n * paymaster sponsorship handshake altogether.\n */\nexport function isRelayerMode(): boolean {\n return Boolean(process.env.BUNDLER_RPC_URL_OVERRIDE)\n}\n\n/**\n * Returns gas prices for UserOperation fee estimation. ZeroDev's bundler\n * exposes a custom `zd_getUserOperationGasPrice` method; standard ERC-4337\n * bundlers do not. In relayer mode the bundler accepts UserOps with zeroed\n * `maxFeePerGas`/`maxPriorityFeePerGas` and pays gas itself.\n */\nexport async function estimateUserOperationFees(\n bundlerClient: any,\n _publicClient: any,\n): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }> {\n if (isRelayerMode()) {\n return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n }\n }\n return getUserOperationGasPrice(bundlerClient)\n}\n\n/**\n * It creates a ZeroDev Kernel client.\n * @param signer the signer account\n * @param chainId the chain id\n * @param zeroDevProjectId the zero dev project id, you can get it from the ZeroDev dashboard\n * @param useUltraRelay forwarded straight to `getBundlerRpcUrl` — when true the\n * bundler RPC is routed through ZeroDev's UltraRelay. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n * @returns the kernel client\n */\nexport async function createKernelClient(\n kernelAccount: SmartAccount,\n chainId: number,\n zeroDevProjectId: string,\n publicClient: any,\n useUltraRelay = false,\n): Promise<KernelAccountClient> {\n const bundlerRpc = getBundlerRpcUrl(zeroDevProjectId, chainId, useUltraRelay)\n const paymasterRpc = getPaymasterRpcUrl(zeroDevProjectId, chainId)\n\n return createKernelAccountClient({\n account: kernelAccount,\n chain: getChain(chainId),\n bundlerTransport: http(bundlerRpc),\n client: publicClient,\n ...(isRelayerMode()\n ? {}\n : {\n paymaster: {\n getPaymasterData: (userOperation: any) => {\n const zerodevPaymaster = createZeroDevPaymasterClient({\n chain: getChain(chainId),\n transport: http(paymasterRpc),\n })\n return zerodevPaymaster.sponsorUserOperation({ userOperation })\n },\n },\n }),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, publicClient)\n },\n },\n })\n}\n\nexport async function createKernelSmartAccount(\n signer: Signer,\n publicClient: PublicClient,\n): Promise<SmartAccount> {\n const ecdsaValidator = await signerToEcdsaValidator(publicClient, {\n signer: signer,\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n\n return await createKernelAccount(publicClient, {\n plugins: {\n sudo: ecdsaValidator,\n },\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n}\n\nexport async function getApproval(signer: Signer, publicClient: any, policies: any[]) {\n const ecdsaValidator = await signerToEcdsaValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer,\n kernelVersion: KERNEL_V3_1,\n })\n const emptyAccount = addressToEmptyAccount(signer.address as Address)\n const emptySessionKeySigner = await toECDSASigner({ signer: emptyAccount })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: emptySessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: ecdsaValidator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n return await serializePermissionAccount(sessionKeyAccount)\n}\n\nexport async function useSessionKey(approval: string, signer: Signer, publicClient: any) {\n const sessionKeySigner = await toECDSASigner({\n signer,\n })\n const sessionKeyAccount = await deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n KERNEL_V3_1,\n approval,\n sessionKeySigner,\n )\n\n return sessionKeyAccount\n}\n\nexport async function createSessionKey(signer: Signer, publicClient: any, policies: any[]) {\n const ecdsaValidator = await signerToEcdsaValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer,\n kernelVersion: KERNEL_V3_1,\n })\n const sessionPrivateKey = generatePrivateKey()\n const masterAccount = privateKeyToAccount(sessionPrivateKey)\n const sessionKeySigner = await toECDSASigner({\n signer: masterAccount,\n })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: ecdsaValidator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n return serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n}\n\nexport async function getSessionKey(serializedSessionKey: string, publicClient: any) {\n const sessionKeyAccount = await deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n KERNEL_V3_1,\n serializedSessionKey,\n )\n\n return sessionKeyAccount\n}\n\n/**\n * Creates a delegated session key for an existing kernel account.\n * The resulting serialized session key can be deserialized into a SmartAccount\n * that shares the same address as the kernel account but enforces the given policies.\n *\n * @param kernelAccount The existing SmartAccount (kernel) to delegate from\n * @param publicClient Viem PublicClient instance\n * @param policies Array of policies to enforce for this session key\n * @returns Serialized session key string\n */\nexport async function createDelegatedSessionKeyFromKernel(\n kernelAccount: SmartAccount,\n publicClient: PublicClient,\n policies: any[],\n): Promise<string> {\n // 1) Generate ephemeral session private key (used only for the permission plugin)\n const sessionPrivateKey = generatePrivateKey()\n const sessionAccount = privateKeyToAccount(sessionPrivateKey)\n\n // 2) Wrap ephemeral key as ECDSA signer for permissions\n const sessionKeySigner = await toECDSASigner({ signer: sessionAccount })\n\n // 3) Create the permission validator plugin\n const permissionValidator = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies,\n kernelVersion: KERNEL_V3_1,\n })\n\n // 4) Extract the sudo validator from the existing kernel account\n const kernelAccountTyped = kernelAccount as SmartAccount<KernelSmartAccountImplementation>\n const sudoValidator = kernelAccountTyped.kernelPluginManager.sudoValidator\n\n if (!sudoValidator) {\n throw new Error('Kernel account does not have a sudo validator')\n }\n\n // 5) Create a new kernel account with both sudo (from original) and permission validator\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: sudoValidator, // Use existing sudo validator\n regular: permissionValidator,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n // 6) Serialize the session key account with the ephemeral private key\n const serialized = await serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n\n return serialized\n}\n\nexport const WalletUtils = {\n makeWallet,\n makeWallets,\n makeRandomWallet,\n makeRandomWallets,\n}\n"],"names":["signerToEcdsaValidator","deserializePermissionAccount","serializePermissionAccount","toPermissionValidator","toECDSASigner","addressToEmptyAccount","createKernelAccount","createKernelAccountClient","createZeroDevPaymasterClient","getUserOperationGasPrice","KERNEL_V3_1","getEntryPoint","encodeAbiParameters","getAbiItem","getAddress","getContract","http","isAddress","pad","stringToBytes","stringToHex","toBytes","keccak256","viemKeccak256","english","generateMnemonic","generatePrivateKey","mnemonicToAccount","privateKeyToAccount","Instantiable","ContractsError","getChain","ENTRY_POINT_VERSION","BlockchainViemUtils","config","setInstanceConfig","TRANSACTION_RECEIPT_TIMEOUT_MS","TRANSACTION_RECEIPT_POLLING_INTERVAL_MS","getTransactionReceipt","txHash","publicClient","waitForTransactionReceipt","hash","timeout","pollingInterval","confirmations","error","getContractInstance","contractAddress","abi","client","address","wallet","public","searchAbiFunction","funcName","args","func","name","type","searchAbiEvent","eventName","event","getSignatureOfFunction","getInputsOfFunction","inputs","getInputsOfFunctionFormatted","map","input","i","value","getChecksumAddress","isValidAddress","getBytes","message","zeroPadValue","length","size","encodeBytes32String","makeWallet","seedphrase","addressIndex","makeWallets","numAccounts","accounts","push","makeRandomWallet","mnemonic","makeRandomWallets","seed","keccak256WithEncode","types","values","encoded","keccak256Packed","getBundlerRpcUrl","zeroDevProjectId","chainId","useUltraRelay","base","process","env","BUNDLER_RPC_URL_OVERRIDE","getPaymasterRpcUrl","isRelayerMode","Boolean","estimateUserOperationFees","bundlerClient","_publicClient","maxFeePerGas","maxPriorityFeePerGas","createKernelClient","kernelAccount","bundlerRpc","paymasterRpc","account","chain","bundlerTransport","paymaster","getPaymasterData","userOperation","zerodevPaymaster","transport","sponsorUserOperation","estimateFeesPerGas","createKernelSmartAccount","signer","ecdsaValidator","entryPoint","kernelVersion","plugins","sudo","getApproval","policies","emptyAccount","emptySessionKeySigner","permissionPlugin","sessionKeyAccount","regular","useSessionKey","approval","sessionKeySigner","createSessionKey","sessionPrivateKey","masterAccount","getSessionKey","serializedSessionKey","createDelegatedSessionKeyFromKernel","sessionAccount","permissionValidator","kernelAccountTyped","sudoValidator","kernelPluginManager","Error","serialized","WalletUtils"],"mappings":"AAAA,SAASA,sBAAsB,QAAQ,2BAA0B;AACjE,SACEC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,qBAAqB,QAChB,uBAAsB;AAC7B,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,yBAAyB,EACzBC,4BAA4B,EAC5BC,wBAAwB,QAGnB,eAAc;AACrB,SAASC,WAAW,EAAEC,aAAa,QAAQ,yBAAwB;AACnE,SAEEC,mBAAmB,EACnBC,UAAU,EACVC,UAAU,EACVC,WAAW,EACXC,IAAI,EACJC,SAAS,EACTC,GAAG,EACHC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,aAAaC,aAAa,QAOrB,OAAM;AAEb,SACEC,OAAO,EACPC,gBAAgB,EAChBC,kBAAkB,EAClBC,iBAAiB,EACjBC,mBAAmB,QACd,gBAAe;AACtB,SAASC,YAAY,QAAyC,iCAAgC;AAC9F,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,QAAQ,QAAQ,yBAAwB;AAGjD,MAAMC,sBAAsB;AAE5B;;;CAGC,GACD,OAAO,MAAMC,4BAA4BJ;IACvC,YAAYK,MAA0B,CAAE;QACtC,KAAK;QACL,IAAI,CAACC,iBAAiB,CAACD;IACzB;AACF;AAEA,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAE1B,eAAe;AAEf,sEAAsE;AACtE,sEAAsE;AACtE,MAAME,iCAAiC;AACvC,MAAMC,0CAA0C;AAEhD;;;;;;;CAOC,GACD,OAAO,eAAeC,sBAAsB,EAC1CC,MAAM,EACNC,YAAY,EAKb;IACC,IAAI;QACF,OAAO,MAAMA,aAAaC,yBAAyB,CAAC;YAClDC,MAAMH;YACNI,SAASP;YACTQ,iBAAiBP;YACjBQ,eAAe;QACjB;IACF,EAAE,OAAOC,OAAO;QACd,MAAM,IA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AAMC,sBAAsB,MAAMlJ,sBAAsBqC,cAAc;QACpEwF,YAAYrH,cAAcqB;QAC1B8F,QAAQe;QACRR;QACAJ,eAAevH;IACjB;IAEA,iEAAiE;IACjE,MAAM4I,qBAAqBtC;IAC3B,MAAMuC,gBAAgBD,mBAAmBE,mBAAmB,CAACD,aAAa;IAE1E,IAAI,CAACA,eAAe;QAClB,MAAM,IAAIE,MAAM;IAClB;IAEA,yFAAyF;IACzF,MAAMhB,oBAAoB,MAAMnI,oBAAoBkC,cAAc;QAChEwF,YAAYrH,cAAcqB;QAC1BkG,SAAS;YACPC,MAAMoB;YACNb,SAASW;QACX;QACApB,eAAevH;IACjB;IAEA,sEAAsE;IACtE,MAAMgJ,aAAa,MAAMxJ,2BAA2BuI,mBAAmBM;IAEvE,OAAOW;AACT;AAEA,OAAO,MAAMC,cAAc;IACzB5E;IACAG;IACAI;IACAE;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/nevermined/utils/BlockchainViemUtils.ts"],"sourcesContent":["import { signerToEcdsaValidator } from '@zerodev/ecdsa-validator'\nimport {\n deserializePermissionAccount,\n serializePermissionAccount,\n toPermissionValidator,\n} from '@zerodev/permissions'\nimport { toECDSASigner } from '@zerodev/permissions/signers'\nimport {\n addressToEmptyAccount,\n createKernelAccount,\n createKernelAccountClient,\n createZeroDevPaymasterClient,\n getUserOperationGasPrice,\n KernelAccountClient,\n type KernelSmartAccountImplementation,\n} from '@zerodev/sdk'\nimport { KERNEL_V3_1, getEntryPoint } from '@zerodev/sdk/constants'\nimport {\n Address,\n encodeAbiParameters,\n getAbiItem,\n getAddress,\n getContract,\n http,\n isAddress,\n pad,\n stringToBytes,\n stringToHex,\n toBytes,\n keccak256 as viemKeccak256,\n type Abi,\n type AbiEvent,\n type AbiFunction,\n type Account,\n type PublicClient,\n type TransactionReceipt,\n} from 'viem'\nimport { SmartAccount } from 'viem/account-abstraction'\nimport {\n english,\n generateMnemonic,\n generatePrivateKey,\n mnemonicToAccount,\n privateKeyToAccount,\n} from 'viem/accounts'\nimport { Instantiable, InstantiableConfig, Web3Clients } from '../../Instantiable.abstract.js'\nimport { ContractsError } from '../../errors/NeverminedErrors.js'\nimport { getChain } from '../../utils/Network.js'\nimport { Signer } from '@zerodev/sdk/types'\n\nconst ENTRY_POINT_VERSION = '0.7'\n\n/**\n * Utility class with methods that allow the interaction with the blockchain.\n * This class uses Viem library to interact with the blockchain.\n */\nexport class BlockchainViemUtils extends Instantiable {\n constructor(config: InstantiableConfig) {\n super()\n this.setInstanceConfig(config)\n }\n}\n\n//////////////////////////\n///// UTILITIES //////////\n//////////////////////////\n\n///// CONTRACTS\n\n// Wait budget for an L2 block to be mined and the receipt to surface.\n// Base / Base Sepolia block time is ~2s; 30s ≈ 15 blocks of headroom.\nconst TRANSACTION_RECEIPT_TIMEOUT_MS = 30_000\nconst TRANSACTION_RECEIPT_POLLING_INTERVAL_MS = 1_500\n\n/**\n * Given a transaction hash, it returns the transaction receipt.\n * Uses viem's `waitForTransactionReceipt` which polls until the receipt is\n * available, retrying on `TransactionReceiptNotFoundError` and handling\n * tx-replacement / reorgs natively.\n * @param txHash - the transaction hash\n * @returns the transaction receipt\n */\nexport async function getTransactionReceipt({\n txHash,\n publicClient,\n}: {\n txHash: `0x${string}`\n publicClient: PublicClient\n iteration?: number\n}): Promise<TransactionReceipt> {\n try {\n return await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: TRANSACTION_RECEIPT_TIMEOUT_MS,\n pollingInterval: TRANSACTION_RECEIPT_POLLING_INTERVAL_MS,\n confirmations: 1,\n })\n } catch (error) {\n throw new ContractsError(\n `Unable to get transaction receipt with hash: ${txHash}. Error: ${error}`,\n )\n }\n}\n\n/**\n * Given an already deployed contract address and the ABI, it returns the contract instance.\n *\n * @param contractAddress - the contract address\n * @param abi - the contract artifact\n * @param client - the client to interact with the blockchain\n * @returns a contract instance\n */\nexport async function getContractInstance(contractAddress: string, abi: Abi, client: Web3Clients) {\n return getContract({\n abi,\n address: contractAddress as `0x${string}`,\n client: { wallet: client.wallet, public: client.public },\n })\n}\n\n///// ABIs\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function searchAbiFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n const func = getAbiItem({ abi, name: funcName, args })\n if (!func || func.type !== 'function') {\n throw new ContractsError(`Function \"${funcName}\" is not part of contract`)\n }\n return func as AbiFunction\n}\n\n/**\n * It searchs an ABI event in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the event name\n * @returns the event found\n */\nexport function searchAbiEvent(abi: Abi, eventName: string): AbiEvent {\n const event = getAbiItem({\n abi,\n name: eventName,\n })\n if (!event || event.type !== 'event') {\n throw new ContractsError(`Event \"${event}\" is not part of contract`)\n }\n return event as AbiEvent\n}\n\n/**\n * It searchs an ABI function in the ABI.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getSignatureOfFunction(abi: Abi, funcName: string, args: any[] = []): AbiFunction {\n return searchAbiFunction(abi, funcName, args)\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunction(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs\n}\n\n/**\n * It searchs an ABI function in the ABI and return the inputs formatted.\n * @param abi the ABI of the contract\n * @param funcName the function name\n * @param args the args of the function\n * @returns the function found\n */\nexport function getInputsOfFunctionFormatted(abi: Abi, funcName: string, args: any[] = []) {\n return searchAbiFunction(abi, funcName, args).inputs.map((input, i) => {\n return {\n name: input.name,\n value: args[i],\n }\n })\n}\n\n//////// UTILS\n\n/**\n * Given an address it returns that address in checksum format.\n * @param address the address\n * @returns the same address in checksum format\n */\nexport function getChecksumAddress(address: string): string {\n return getAddress(address)\n}\n\n/**\n * It checks if the address is a valid address.\n * @param address the address to check\n * @returns true of the address is valid\n */\nexport function isValidAddress(address: string): boolean {\n return isAddress(address)\n}\n\n/**\n * Encodes a UTF-8 string into a byte array.\n\n * @param message the string to encode\n * @returns the encoded byte array\n */\nexport function getBytes(message: string): Uint8Array {\n return stringToBytes(message)\n}\n\n/**\n * It pads a value with zeros.\n * @param value the value to pad\n * @param length the expected longitutde of the value\n * @returns the padded value\n */\nexport function zeroPadValue(value: `0x${string}` | Uint8Array, length: number): string {\n return pad(value, { size: length }) as `0x${string}`\n}\n\n/**\n * Encodes a UTF-8 string into a hex string\n * @param message the string to encode\n * @returns the hex string\n */\nexport function encodeBytes32String(message: string) {\n return stringToHex(message, { size: 32 })\n}\n\n////// ACCOUNTS\n/**\n * Given a seedphrase, it returns an account.\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param addressIndex - the address index\n * @returns an account\n */\nexport function makeWallet(seedphrase: string, addressIndex = 0): Account {\n return mnemonicToAccount(seedphrase, { addressIndex })\n}\n\n/**\n * Given a seedphrase generates multiple accounts\n * @param seedphrase - the seedphrase to be used to generate the account\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeWallets(seedphrase: string, numAccounts = 10) {\n const accounts: Account[] = []\n for (let i = 0; i < numAccounts; i++) {\n accounts.push(makeWallet(seedphrase, i))\n }\n return accounts\n}\n\n/**\n * It generates a random account.\n * @returns a new account\n */\nexport function makeRandomWallet(): Account {\n const mnemonic = generateMnemonic(english)\n return makeWallet(mnemonic)\n}\n\n/**\n * It generates a list of random accounts\n * @param numAccounts - the number of accounts to create\n * @returns the array of accounts\n */\nexport function makeRandomWallets(numAccounts = 10): Account[] {\n const mnemonic = generateMnemonic(english)\n return makeWallets(mnemonic, numAccounts)\n}\n\n/////// HASHES\n\n/**\n * It hashes a string using keccak256.\n * @param seed the string to hash\n * @returns the hash\n */\nexport function keccak256(seed: string): string {\n return viemKeccak256(toBytes(seed))\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256WithEncode(types: any[], values: any[]): string {\n const encoded = encodeAbiParameters(types, values as never)\n return keccak256(encoded)\n}\n\n/**\n * It encodes and hashes a list of primitive values into an ABI-encoded hex value.\n * @param types the types of the values\n * @param values the values to encode\n * @returns the hash\n */\nexport function keccak256Packed(types: any[], values: any[]): string {\n return keccak256WithEncode(types, values)\n}\n\n/////// ZERO DEV\n\n/**\n * Returns the bundler RPC URL. When `BUNDLER_RPC_URL_OVERRIDE` is set\n * (used by tests against a local Alto + anvil-fork stack), it takes precedence\n * over the canonical ZeroDev URL. When `useUltraRelay` is true, the production\n * URL is routed through ZeroDev's UltraRelay (`?provider=ULTRA_RELAY`); the\n * override branch is left untouched.\n * @param useUltraRelay - when true, append `?provider=ULTRA_RELAY` to route the\n * UserOperation through ZeroDev's UltraRelay bundler tier. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n */\nexport function getBundlerRpcUrl(\n zeroDevProjectId: string,\n chainId: number,\n useUltraRelay = false,\n): string {\n const base = `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n // `||` (not `??`) because Vite replaces missing browser env vars with the\n // empty string at build time; an empty override is equivalent to \"no\n // override\" for our purposes.\n return (\n process.env.BUNDLER_RPC_URL_OVERRIDE || (useUltraRelay ? `${base}?provider=ULTRA_RELAY` : base)\n )\n}\n\n/**\n * Returns the paymaster RPC URL (ZeroDev-only; the local fork stack uses\n * `ultra-relay` which sponsors via the bundler's executor key without a\n * paymaster, so this URL is not consulted when `BUNDLER_RPC_URL_OVERRIDE` is\n * set).\n */\nexport function getPaymasterRpcUrl(zeroDevProjectId: string, chainId: number): string {\n return `https://rpc.zerodev.app/api/v3/${zeroDevProjectId}/chain/${chainId}`\n}\n\n/**\n * Returns true when the kernel client should run in \"relayer mode\" — no\n * paymaster, gas fees zeroed out. Used by tests against a local\n * `ultra-relay` (ZeroDev's fork of Alto) on top of an anvil-fork. The relayer's\n * executor key pays gas directly via `EntryPoint.handleOps`, avoiding the\n * paymaster sponsorship handshake altogether.\n */\nexport function isRelayerMode(): boolean {\n return Boolean(process.env.BUNDLER_RPC_URL_OVERRIDE)\n}\n\n/**\n * Returns gas prices for UserOperation fee estimation. ZeroDev's bundler\n * exposes a custom `zd_getUserOperationGasPrice` method; standard ERC-4337\n * bundlers do not. In relayer mode the bundler accepts UserOps with zeroed\n * `maxFeePerGas`/`maxPriorityFeePerGas` and pays gas itself.\n */\nexport async function estimateUserOperationFees(\n bundlerClient: any,\n _publicClient: any,\n): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }> {\n if (isRelayerMode()) {\n return { maxFeePerGas: 0n, maxPriorityFeePerGas: 0n }\n }\n return getUserOperationGasPrice(bundlerClient)\n}\n\n/**\n * It creates a ZeroDev Kernel client.\n * @param signer the signer account\n * @param chainId the chain id\n * @param zeroDevProjectId the zero dev project id, you can get it from the ZeroDev dashboard\n * @param useUltraRelay forwarded straight to `getBundlerRpcUrl` — when true the\n * bundler RPC is routed through ZeroDev's UltraRelay. Ignored when\n * `BUNDLER_RPC_URL_OVERRIDE` is set.\n * @returns the kernel client\n */\nexport async function createKernelClient(\n kernelAccount: SmartAccount,\n chainId: number,\n zeroDevProjectId: string,\n publicClient: any,\n useUltraRelay = false,\n): Promise<KernelAccountClient> {\n const bundlerRpc = getBundlerRpcUrl(zeroDevProjectId, chainId, useUltraRelay)\n const paymasterRpc = getPaymasterRpcUrl(zeroDevProjectId, chainId)\n\n return createKernelAccountClient({\n account: kernelAccount,\n chain: getChain(chainId),\n bundlerTransport: http(bundlerRpc),\n client: publicClient,\n ...(isRelayerMode()\n ? {}\n : {\n paymaster: {\n getPaymasterData: (userOperation: any) => {\n const zerodevPaymaster = createZeroDevPaymasterClient({\n chain: getChain(chainId),\n transport: http(paymasterRpc),\n })\n return zerodevPaymaster.sponsorUserOperation({ userOperation })\n },\n },\n }),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, publicClient)\n },\n },\n })\n}\n\nexport type EcdsaValidator = Awaited<ReturnType<typeof signerToEcdsaValidator>>\n\n/**\n * Identifies the smart-account derivation inputs (entryPoint + kernel version).\n * The SCA is deterministic from `(EOA, entryPoint, kernelVersion, index)`, so a\n * bump here means the same EOA derives a different SCA. Persisted SCA caches\n * (e.g. the webapp's localStorage) should stamp this and invalidate on change.\n */\nexport const SCA_DERIVATION_VERSION = `${ENTRY_POINT_VERSION}:${KERNEL_V3_1}`\n\n/**\n * Build the ECDSA sudo validator for a signer. Both `createKernelSmartAccount`\n * and `createSessionKey` need this validator and each derives it via a ZeroDev\n * RPC round-trip. Callers that run both in sequence (e.g. the webapp API-key\n * creation path) can compute it once here and pass it into both helpers to\n * avoid the redundant round-trip.\n *\n * @param ecdsaValidator (on the consumers) must be one built for the SAME\n * `signer` — passing a validator derived from a different signer would attach\n * the wrong owner to the account.\n */\nexport async function createEcdsaValidator(\n signer: Signer,\n publicClient: PublicClient,\n): Promise<EcdsaValidator> {\n return signerToEcdsaValidator(publicClient, {\n signer,\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n}\n\nexport async function createKernelSmartAccount(\n signer: Signer,\n publicClient: PublicClient,\n ecdsaValidator?: EcdsaValidator,\n): Promise<SmartAccount> {\n const validator = ecdsaValidator ?? (await createEcdsaValidator(signer, publicClient))\n\n return await createKernelAccount(publicClient, {\n plugins: {\n sudo: validator,\n },\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n kernelVersion: KERNEL_V3_1,\n })\n}\n\nexport async function getApproval(signer: Signer, publicClient: any, policies: any[]) {\n const ecdsaValidator = await signerToEcdsaValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer,\n kernelVersion: KERNEL_V3_1,\n })\n const emptyAccount = addressToEmptyAccount(signer.address as Address)\n const emptySessionKeySigner = await toECDSASigner({ signer: emptyAccount })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: emptySessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: ecdsaValidator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n return await serializePermissionAccount(sessionKeyAccount)\n}\n\nexport async function useSessionKey(approval: string, signer: Signer, publicClient: any) {\n const sessionKeySigner = await toECDSASigner({\n signer,\n })\n const sessionKeyAccount = await deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n KERNEL_V3_1,\n approval,\n sessionKeySigner,\n )\n\n return sessionKeyAccount\n}\n\nexport async function createSessionKey(\n signer: Signer,\n publicClient: any,\n policies: any[],\n ecdsaValidator?: EcdsaValidator,\n) {\n const validator = ecdsaValidator ?? (await createEcdsaValidator(signer, publicClient))\n const sessionPrivateKey = generatePrivateKey()\n const masterAccount = privateKeyToAccount(sessionPrivateKey)\n const sessionKeySigner = await toECDSASigner({\n signer: masterAccount,\n })\n\n const permissionPlugin = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies: policies,\n kernelVersion: KERNEL_V3_1,\n })\n\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: validator,\n regular: permissionPlugin,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n return serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n}\n\nexport async function getSessionKey(serializedSessionKey: string, publicClient: any) {\n const sessionKeyAccount = await deserializePermissionAccount(\n publicClient,\n getEntryPoint(ENTRY_POINT_VERSION),\n KERNEL_V3_1,\n serializedSessionKey,\n )\n\n return sessionKeyAccount\n}\n\n/**\n * Creates a delegated session key for an existing kernel account.\n * The resulting serialized session key can be deserialized into a SmartAccount\n * that shares the same address as the kernel account but enforces the given policies.\n *\n * @param kernelAccount The existing SmartAccount (kernel) to delegate from\n * @param publicClient Viem PublicClient instance\n * @param policies Array of policies to enforce for this session key\n * @returns Serialized session key string\n */\nexport async function createDelegatedSessionKeyFromKernel(\n kernelAccount: SmartAccount,\n publicClient: PublicClient,\n policies: any[],\n): Promise<string> {\n // 1) Generate ephemeral session private key (used only for the permission plugin)\n const sessionPrivateKey = generatePrivateKey()\n const sessionAccount = privateKeyToAccount(sessionPrivateKey)\n\n // 2) Wrap ephemeral key as ECDSA signer for permissions\n const sessionKeySigner = await toECDSASigner({ signer: sessionAccount })\n\n // 3) Create the permission validator plugin\n const permissionValidator = await toPermissionValidator(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n signer: sessionKeySigner,\n policies,\n kernelVersion: KERNEL_V3_1,\n })\n\n // 4) Extract the sudo validator from the existing kernel account\n const kernelAccountTyped = kernelAccount as SmartAccount<KernelSmartAccountImplementation>\n const sudoValidator = kernelAccountTyped.kernelPluginManager.sudoValidator\n\n if (!sudoValidator) {\n throw new Error('Kernel account does not have a sudo validator')\n }\n\n // 5) Create a new kernel account with both sudo (from original) and permission validator\n const sessionKeyAccount = await createKernelAccount(publicClient, {\n entryPoint: getEntryPoint(ENTRY_POINT_VERSION),\n plugins: {\n sudo: sudoValidator, // Use existing sudo validator\n regular: permissionValidator,\n },\n kernelVersion: KERNEL_V3_1,\n })\n\n // 6) Serialize the session key account with the ephemeral private key\n const serialized = await serializePermissionAccount(sessionKeyAccount, sessionPrivateKey)\n\n return serialized\n}\n\nexport const WalletUtils = {\n makeWallet,\n makeWallets,\n makeRandomWallet,\n makeRandomWallets,\n}\n"],"names":["signerToEcdsaValidator","deserializePermissionAccount","serializePermissionAccount","toPermissionValidator","toECDSASigner","addressToEmptyAccount","createKernelAccount","createKernelAccountClient","createZeroDevPaymasterClient","getUserOperationGasPrice","KERNEL_V3_1","getEntryPoint","encodeAbiParameters","getAbiItem","getAddress","getContract","http","isAddress","pad","stringToBytes","stringToHex","toBytes","keccak256","viemKeccak256","english","generateMnemonic","generatePrivateKey","mnemonicToAccount","privateKeyToAccount","Instantiable","ContractsError","getChain","ENTRY_POINT_VERSION","BlockchainViemUtils","config","setInstanceConfig","TRANSACTION_RECEIPT_TIMEOUT_MS","TRANSACTION_RECEIPT_POLLING_INTERVAL_MS","getTransactionReceipt","txHash","publicClient","waitForTransactionReceipt","hash","timeout","pollingInterval","confirmations","error","getContractInstance","contractAddress","abi","client","address","wallet","public","searchAbiFunction","funcName","args","func","name","type","searchAbiEvent","eventName","event","getSignatureOfFunction","getInputsOfFunction","inputs","getInputsOfFunctionFormatted","map","input","i","value","getChecksumAddress","isValidAddress","getBytes","message","zeroPadValue","length","size","encodeBytes32String","makeWallet","seedphrase","addressIndex","makeWallets","numAccounts","accounts","push","makeRandomWallet","mnemonic","makeRandomWallets","seed","keccak256WithEncode","types","values","encoded","keccak256Packed","getBundlerRpcUrl","zeroDevProjectId","chainId","useUltraRelay","base","process","env","BUNDLER_RPC_URL_OVERRIDE","getPaymasterRpcUrl","isRelayerMode","Boolean","estimateUserOperationFees","bundlerClient","_publicClient","maxFeePerGas","maxPriorityFeePerGas","createKernelClient","kernelAccount","bundlerRpc","paymasterRpc","account","chain","bundlerTransport","paymaster","getPaymasterData","userOperation","zerodevPaymaster","transport","sponsorUserOperation","estimateFeesPerGas","SCA_DERIVATION_VERSION","createEcdsaValidator","signer","entryPoint","kernelVersion","createKernelSmartAccount","ecdsaValidator","validator","plugins","sudo","getApproval","policies","emptyAccount","emptySessionKeySigner","permissionPlugin","sessionKeyAccount","regular","useSessionKey","approval","sessionKeySigner","createSessionKey","sessionPrivateKey","masterAccount","getSessionKey","serializedSessionKey","createDelegatedSessionKeyFromKernel","sessionAccount","permissionValidator","kernelAccountTyped","sudoValidator","kernelPluginManager","Error","serialized","WalletUtils"],"m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