@nevermined-io/core-kit 1.6.0 → 1.8.0
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.
- package/dist/Instantiable.abstract.d.ts.map +1 -1
- package/dist/Instantiable.abstract.js +23 -4
- package/dist/Instantiable.abstract.js.map +1 -1
- package/dist/contracts/ContractBase.d.ts.map +1 -1
- package/dist/contracts/ContractBase.js +2 -2
- package/dist/contracts/ContractBase.js.map +1 -1
- package/dist/models/Logger.d.ts.map +1 -1
- package/dist/models/Logger.js +4 -1
- package/dist/models/Logger.js.map +1 -1
- package/dist/models/NeverminedOptions.d.ts +8 -0
- package/dist/models/NeverminedOptions.d.ts.map +1 -1
- package/dist/models/NeverminedOptions.js.map +1 -1
- package/dist/models/NvmApiKey.d.ts +9 -1
- package/dist/models/NvmApiKey.d.ts.map +1 -1
- package/dist/models/NvmApiKey.js +6 -0
- package/dist/models/NvmApiKey.js.map +1 -1
- package/dist/nevermined/utils/BlockchainViemUtils.d.ts +70 -11
- package/dist/nevermined/utils/BlockchainViemUtils.d.ts.map +1 -1
- package/dist/nevermined/utils/BlockchainViemUtils.js +206 -25
- package/dist/nevermined/utils/BlockchainViemUtils.js.map +1 -1
- package/dist/nevermined/utils/ZeroDevPolicies.d.ts +2 -2
- package/dist/nevermined/utils/ZeroDevPolicies.d.ts.map +1 -1
- package/dist/nevermined/utils/ZeroDevPolicies.js +87 -35
- package/dist/nevermined/utils/ZeroDevPolicies.js.map +1 -1
- package/dist/utils/Network.d.ts +5 -0
- package/dist/utils/Network.d.ts.map +1 -1
- package/dist/utils/Network.js +228 -222
- package/dist/utils/Network.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Instantiable.abstract.d.ts","sourceRoot":"","sources":["../src/Instantiable.abstract.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,KAAK,EACV,KAAK,YAAY,EACjB,KAAK,YAAY,
|
|
1
|
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AE,GAAG,GAAG,GAAG;IAI7C,SAAS,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC,SAAS,YAAY,EACvD,QAAQ,EAAE,CAAC,EACX,kBAAkB,EAAE,kBAAkB;IAKxC,OAAO,CAAC,mBAAmB,CAAC,CAAoB;IAEhD,SAAS,CAAC,iBAAiB,CAAC,MAAM,EAAE,kBAAkB;CAGvD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createPublicClient, createWalletClient, custom, http } from 'viem';
|
|
1
|
+
import { createPublicClient, createWalletClient, custom, fallback, http } from 'viem';
|
|
2
2
|
import 'viem/window';
|
|
3
3
|
import { createLogger, LoggerInstance } from './models/Logger.js';
|
|
4
4
|
import { getChain } from './utils/Network.js';
|
|
@@ -16,15 +16,34 @@ export async function generateInstantiableConfigFromConfig(config, loadClient =
|
|
|
16
16
|
}
|
|
17
17
|
export async function getWeb3ViemClients(config = {}) {
|
|
18
18
|
const chain = getChain(config.chainId);
|
|
19
|
-
|
|
19
|
+
// Primary + optional secondary HTTP endpoint, in priority order. `fallback()`
|
|
20
|
+
// auto-fails over on TRANSPORT errors (network failure, 5xx, timeout) — not on
|
|
21
|
+
// a valid RPC error like a revert — so a primary-endpoint outage no longer
|
|
22
|
+
// takes protocol reads/writes down (the boot-time SPOF behind #2142). Pair the
|
|
23
|
+
// primary with a DIFFERENT provider for real single-provider-outage coverage.
|
|
24
|
+
// With no fallback configured the behaviour is identical to a single http().
|
|
25
|
+
const httpUrls = [
|
|
26
|
+
config.web3ProviderUri,
|
|
27
|
+
config.web3ProviderUriFallback
|
|
28
|
+
].filter(Boolean);
|
|
29
|
+
// Reads: always a neutral RPC (never the injected wallet), matching prior
|
|
30
|
+
// behaviour. `fallback()` fails over on transport errors when a secondary is
|
|
31
|
+
// configured; a single URL stays a plain `http()` (identical to before).
|
|
32
|
+
const httpTransport = httpUrls.length > 1 ? fallback(httpUrls.map((url)=>http(url))) : httpUrls.length === 1 ? http(httpUrls[0]) : http();
|
|
33
|
+
// Writes: fall back to window.ethereum only when no URL is configured, as before.
|
|
34
|
+
const walletTransport = httpUrls.length > 0 ? httpTransport : typeof window !== 'undefined' && window.ethereum ? custom(window.ethereum) : http();
|
|
20
35
|
const publicClient = createPublicClient({
|
|
21
36
|
chain,
|
|
22
|
-
transport:
|
|
37
|
+
transport: httpTransport,
|
|
38
|
+
// #2206: coalesce concurrent eth_call into a single multicall round-trip.
|
|
39
|
+
batch: {
|
|
40
|
+
multicall: true
|
|
41
|
+
}
|
|
23
42
|
});
|
|
24
43
|
const walletClient = createWalletClient({
|
|
25
44
|
// cacheTime: 0 as number,
|
|
26
45
|
chain,
|
|
27
|
-
transport:
|
|
46
|
+
transport: walletTransport
|
|
28
47
|
});
|
|
29
48
|
return {
|
|
30
49
|
public: publicClient,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/Instantiable.abstract.ts"],"sourcesContent":["import {\n type Chain,\n type PublicClient,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n custom,\n http,\n} from 'viem'\nimport 'viem/window'\nimport { createLogger, LoggerInstance, LogLevel } from './models/Logger.js'\nimport type { NeverminedOptions } from './models/NeverminedOptions.js'\nimport { Nevermined } from './nevermined/Nevermined.js'\nimport { getChain } from './utils/Network.js'\n\nexport interface InstantiableConfig {\n nevermined: Nevermined\n config?: NeverminedOptions\n client?: Web3Clients\n logger?: ReturnType<typeof LoggerInstance>\n}\n\nexport interface Web3Clients {\n public: PublicClient\n wallet: WalletClient\n chain?: Chain\n}\n\nexport async function generateInstantiableConfigFromConfig(\n config: NeverminedOptions,\n loadClient = true,\n): Promise<Partial<InstantiableConfig>> {\n const logLevel = config.logLevel || ('info' as LogLevel)\n const logger = createLogger({\n level: logLevel as LogLevel,\n pretty: process.env.NODE_ENV === 'development',\n })\n\n return {\n config,\n client: loadClient ? await getWeb3ViemClients(config) : undefined,\n logger,\n }\n}\n\nexport async function getWeb3ViemClients(\n config: Partial<NeverminedOptions> = {},\n): Promise<Web3Clients> {\n const chain = getChain(config.chainId)\n const
|
|
1
|
+
{"version":3,"sources":["../src/Instantiable.abstract.ts"],"sourcesContent":["import {\n type Chain,\n type PublicClient,\n type WalletClient,\n createPublicClient,\n createWalletClient,\n custom,\n fallback,\n http,\n} from 'viem'\nimport 'viem/window'\nimport { createLogger, LoggerInstance, LogLevel } from './models/Logger.js'\nimport type { NeverminedOptions } from './models/NeverminedOptions.js'\nimport { Nevermined } from './nevermined/Nevermined.js'\nimport { getChain } from './utils/Network.js'\n\nexport interface InstantiableConfig {\n nevermined: Nevermined\n config?: NeverminedOptions\n client?: Web3Clients\n logger?: ReturnType<typeof LoggerInstance>\n}\n\nexport interface Web3Clients {\n public: PublicClient\n wallet: WalletClient\n chain?: Chain\n}\n\nexport async function generateInstantiableConfigFromConfig(\n config: NeverminedOptions,\n loadClient = true,\n): Promise<Partial<InstantiableConfig>> {\n const logLevel = config.logLevel || ('info' as LogLevel)\n const logger = createLogger({\n level: logLevel as LogLevel,\n pretty: process.env.NODE_ENV === 'development',\n })\n\n return {\n config,\n client: loadClient ? await getWeb3ViemClients(config) : undefined,\n logger,\n }\n}\n\nexport async function getWeb3ViemClients(\n config: Partial<NeverminedOptions> = {},\n): Promise<Web3Clients> {\n const chain = getChain(config.chainId)\n\n // Primary + optional secondary HTTP endpoint, in priority order. `fallback()`\n // auto-fails over on TRANSPORT errors (network failure, 5xx, timeout) — not on\n // a valid RPC error like a revert — so a primary-endpoint outage no longer\n // takes protocol reads/writes down (the boot-time SPOF behind #2142). Pair the\n // primary with a DIFFERENT provider for real single-provider-outage coverage.\n // With no fallback configured the behaviour is identical to a single http().\n const httpUrls = [config.web3ProviderUri, config.web3ProviderUriFallback].filter(\n Boolean,\n ) as string[]\n\n // Reads: always a neutral RPC (never the injected wallet), matching prior\n // behaviour. `fallback()` fails over on transport errors when a secondary is\n // configured; a single URL stays a plain `http()` (identical to before).\n const httpTransport =\n httpUrls.length > 1\n ? fallback(httpUrls.map((url) => http(url)))\n : httpUrls.length === 1\n ? http(httpUrls[0])\n : http()\n\n // Writes: fall back to window.ethereum only when no URL is configured, as before.\n const walletTransport =\n httpUrls.length > 0\n ? httpTransport\n : typeof window !== 'undefined' && window.ethereum\n ? custom(window.ethereum!)\n : http()\n\n const publicClient = createPublicClient({\n chain,\n transport: httpTransport,\n // #2206: coalesce concurrent eth_call into a single multicall round-trip.\n batch: { multicall: true },\n })\n\n const walletClient = createWalletClient({\n // cacheTime: 0 as number,\n chain,\n transport: walletTransport,\n })\n\n return {\n public: publicClient,\n wallet: walletClient,\n chain,\n } as Web3Clients\n}\n\nexport abstract class Instantiable {\n protected get nevermined() {\n if (!this._instantiableConfig?.nevermined) {\n this.logger.error('Nevermined instance is not defined.')\n throw new Error('Nevermined instance is not defined.')\n }\n return this._instantiableConfig.nevermined\n }\n\n public get client() {\n if (!this._instantiableConfig?.client) {\n this.logger.error('Web3 Provider not initialized')\n throw new Error('Web3 Provider not initialized')\n }\n return this._instantiableConfig.client\n }\n\n public get publicClient(): PublicClient {\n if (!this._instantiableConfig?.client?.public) {\n this.logger.error('Web3 Provider not initialized')\n throw new Error('Web3 Provider not initialized')\n }\n return this._instantiableConfig.client?.public\n }\n\n public get walletClient(): WalletClient {\n if (!this._instantiableConfig?.client?.wallet) {\n this.logger.error('Web3 Provider not initialized')\n throw new Error('Web3 Provider not initialized')\n }\n return this._instantiableConfig.client?.wallet\n }\n\n protected get instantiableConfig() {\n if (!this._instantiableConfig) {\n this.logger.error('InstantiableConfig instance is not defined.')\n }\n return this._instantiableConfig\n }\n\n protected get config() {\n if (!this._instantiableConfig?.config) {\n this.logger.error('Config instance is not defined.')\n throw new Error('Config instance is not defined.')\n }\n return this._instantiableConfig.config\n }\n\n protected get logger() {\n return this._instantiableConfig?.logger || LoggerInstance()\n }\n\n protected get instanceConfig(): InstantiableConfig {\n const { nevermined, client, config, logger } = this\n return { nevermined, client, config, logger }\n }\n\n public static getInstance(..._args: any): any {\n LoggerInstance().warn('getInstance() methods has needs to be added to child class.')\n }\n\n protected static setInstanceConfig<T extends Instantiable>(\n instance: T,\n instantiableConfig: InstantiableConfig,\n ) {\n instance._instantiableConfig = instantiableConfig\n }\n\n private _instantiableConfig?: InstantiableConfig\n\n protected setInstanceConfig(config: InstantiableConfig) {\n Instantiable.setInstanceConfig(this, config)\n }\n}\n"],"names":["createPublicClient","createWalletClient","custom","fallback","http","createLogger","LoggerInstance","getChain","generateInstantiableConfigFromConfig","config","loadClient","logLevel","logger","level","pretty","process","env","NODE_ENV","client","getWeb3ViemClients","undefined","chain","chainId","httpUrls","web3ProviderUri","web3ProviderUriFallback","filter","Boolean","httpTransport","length","map","url","walletTransport","window","ethereum","publicClient","transport","batch","multicall","walletClient","public","wallet","Instantiable","nevermined","_instantiableConfig","error","Error","instantiableConfig","instanceConfig","getInstance","_args","warn","setInstanceConfig","instance"],"mappings":"AAAA,SAIEA,kBAAkB,EAClBC,kBAAkB,EAClBC,MAAM,EACNC,QAAQ,EACRC,IAAI,QACC,OAAM;AACb,OAAO,cAAa;AACpB,SAASC,YAAY,EAAEC,cAAc,QAAkB,qBAAoB;AAG3E,SAASC,QAAQ,QAAQ,qBAAoB;AAe7C,OAAO,eAAeC,qCACpBC,MAAyB,EACzBC,aAAa,IAAI;IAEjB,MAAMC,WAAWF,OAAOE,QAAQ,IAAK;IACrC,MAAMC,SAASP,aAAa;QAC1BQ,OAAOF;QACPG,QAAQC,QAAQC,GAAG,CAACC,QAAQ,KAAK;IACnC;IAEA,OAAO;QACLR;QACAS,QAAQR,aAAa,MAAMS,mBAAmBV,UAAUW;QACxDR;IACF;AACF;AAEA,OAAO,eAAeO,mBACpBV,SAAqC,CAAC,CAAC;IAEvC,MAAMY,QAAQd,SAASE,OAAOa,OAAO;IAErC,8EAA8E;IAC9E,+EAA+E;IAC/E,2EAA2E;IAC3E,+EAA+E;IAC/E,8EAA8E;IAC9E,6EAA6E;IAC7E,MAAMC,WAAW;QAACd,OAAOe,eAAe;QAAEf,OAAOgB,u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,CAAC1B,MAAM,EAAEsB;IAC1C;IAEA,IAAWD,eAA6B;QACtC,IAAI,CAAC,IAAI,CAACK,mBAAmB,EAAE1B,QAAQuB,QAAQ;YAC7C,IAAI,CAAC7B,MAAM,CAACiC,KAAK,CAAC;YAClB,MAAM,IAAIC,MAAM;QAClB;QACA,OAAO,IAAI,CAACF,mBAAmB,CAAC1B,MAAM,EAAEuB;IAC1C;IAEA,IAAcM,qBAAqB;QACjC,IAAI,CAAC,IAAI,CAACH,mBAAmB,EAAE;YAC7B,IAAI,CAAChC,MAAM,CAACiC,KAAK,CAAC;QACpB;QACA,OAAO,IAAI,CAACD,mBAAmB;IACjC;IAEA,IAAcnC,SAAS;QACrB,IAAI,CAAC,IAAI,CAACmC,mBAAmB,EAAEnC,QAAQ;YACrC,IAAI,CAACG,MAAM,CAACiC,KAAK,CAAC;YAClB,MAAM,IAAIC,MAAM;QAClB;QACA,OAAO,IAAI,CAACF,mBAAmB,CAACnC,MAAM;IACxC;IAEA,IAAcG,SAAS;QACrB,OAAO,IAAI,CAACgC,mBAAmB,EAAEhC,UAAUN;IAC7C;IAEA,IAAc0C,iBAAqC;QACjD,MAAM,EAAEL,UAAU,EAAEzB,MAAM,EAAET,MAAM,EAAEG,MAAM,EAAE,GAAG,IAAI;QACnD,OAAO;YAAE+B;YAAYzB;YAAQT;YAAQG;QAAO;IAC9C;IAEA,OAAcqC,YAAY,GAAGC,KAAU,EAAO;QAC5C5C,iBAAiB6C,IAAI,CAAC;IACxB;IAEA,OAAiBC,kBACfC,QAAW,EACXN,kBAAsC,EACtC;QACAM,SAAST,mBAAmB,GAAGG;IACjC;IAIUK,kBAAkB3C,MAA0B,EAAE;QACtDiC,aAAaU,iBAAiB,CAAC,IAAI,EAAE3C;IACvC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ContractBase.d.ts","sourceRoot":"","sources":["../../src/contracts/ContractBase.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"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undlerRpcUrl, getPaymasterRpcUrl, isRelayerMode } from '../nevermined/utils/BlockchainViemUtils.js';
|
|
2
|
+
import { applyTempoVerificationGasFloor, estimateUserOperationFees, getBundlerRpcUrl, getPaymasterRpcUrl, isRelayerMode } from '../nevermined/utils/BlockchainViemUtils.js';
|
|
3
3
|
import { BaseError, ContractFunctionRevertedError, encodeFunctionData, getContract, http, parseAbi, parseEventLogs } from 'viem';
|
|
4
4
|
import { createBundlerClient, getUserOperationHash } from 'viem/account-abstraction';
|
|
5
5
|
import { ContractsError, ContractSimulationError } from '../errors/index.js';
|
|
@@ -689,7 +689,7 @@ export class ContractBase extends Instantiable {
|
|
|
689
689
|
return {
|
|
690
690
|
paymaster: {
|
|
691
691
|
getPaymasterData: (userOperation)=>zerodevPaymaster.sponsorUserOperation({
|
|
692
|
-
userOperation
|
|
692
|
+
userOperation: applyTempoVerificationGasFloor(userOperation, this.config.chainId)
|
|
693
693
|
})
|
|
694
694
|
}
|
|
695
695
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/contracts/ContractBase.ts"],"sourcesContent":["import { createKernelAccountClient, createZeroDevPaymasterClient } from '@zerodev/sdk'\nimport {\n estimateUserOperationFees,\n getBundlerRpcUrl,\n getPaymasterRpcUrl,\n isRelayerMode,\n} from '../nevermined/utils/BlockchainViemUtils.js'\nimport {\n Abi,\n Account,\n Address,\n BaseError,\n ContractFunctionRevertedError,\n encodeFunctionData,\n getContract,\n http,\n parseAbi,\n parseEventLogs,\n TransactionReceipt,\n} from 'viem'\nimport {\n createBundlerClient,\n getUserOperationHash,\n SmartAccount,\n UserOperationReceipt,\n} from 'viem/account-abstraction'\nimport { ContractsError, ContractSimulationError } from '../errors/index.js'\nimport { Instantiable, InstantiableConfig } from '../Instantiable.abstract.js'\nimport { TxParameters } from '../models/Transactions.js'\nimport { getInputsOfFunctionFormatted, getTransactionReceipt } from '../nevermined/index.js'\nimport { getRandomBigInt } from '../utils/helpers.js'\nimport { getChain } from '../utils/Network.js'\n\nexport interface MulticallEntry {\n contractName?: string\n contractAddress: Address\n abi: Abi\n functionName: string\n args: any[]\n}\n\n/**\n * When a testnet RPC (Base Sepolia) fails internally, some providers return\n * `eth_estimateGas` values equal to — or even above — the block gas limit\n * instead of a real error. Using that value causes the node to reject the tx\n * with `intrinsic gas too high` before it ever reaches the mempool.\n *\n * `writeContract` in viem re-estimates gas internally when `gas` isn't\n * already set on the request (viem's `simulateContract` only performs\n * `eth_call`, not `eth_estimateGas`). That means the naïve path has no\n * chance to intercept a bogus estimate. We run the estimation ourselves\n * here, sanity-check the result, and always pass an explicit gas value\n * into `writeContract` so it doesn't re-query the misbehaving RPC.\n */\nconst GAS_SANITY_THRESHOLD = 25_000_000n\nconst GAS_FALLBACK_CAP = 5_000_000n\n\n// EntryPoint v0.7: ZeroDev's `toKernelPluginManager` rejects `customNonceKey > maxUint16`.\n// 16 bits = 65 536 channels — collision probability for the SDK's expected concurrency\n// (k=2–5 parallel sends from one SCA) is negligible (< 0.02 %). High-fan-out callers\n// (k > 50) should consider a per-process monotonic counter instead. See issue #1579.\nconst ZERODEV_NONCE_KEY_BITS = 16\n\n// Client-side cap on `waitForUserOperationReceipt`. The userOp is already in the bundler\n// mempool when this fires — a client-side timeout does NOT cancel it. Callers that catch\n// the resulting `ContractsError` MUST poll `bundlerClient.getUserOperationReceipt(hash)`\n// before retrying; otherwise a retry can produce a duplicate on-chain op.\nconst USEROP_RECEIPT_TIMEOUT_MS = 90_000\n\nfunction capForBogusEstimate(\n estimatedGas: bigint,\n logger: { warn: (msg: string) => void },\n): bigint {\n if (estimatedGas < GAS_SANITY_THRESHOLD) return estimatedGas\n logger.warn(\n `Estimated gas (${estimatedGas}) exceeds sanity threshold ` +\n `(${GAS_SANITY_THRESHOLD}); overriding with ${GAS_FALLBACK_CAP} to bypass misbehaving RPC estimate.`,\n )\n return GAS_FALLBACK_CAP\n}\n\nexport interface SimulateMulticallEntry {\n functionName: string\n value?: bigint\n abi: Abi\n args: any[]\n to: Address\n}\n\nexport abstract class ContractBase extends Instantiable {\n public readonly contractName: string\n public contract: any\n public address: Address\n private _zeroDevPaymaster: ReturnType<typeof createZeroDevPaymasterClient> | null = null\n\n constructor(contractName: string, address: Address) {\n super()\n this.contractName = contractName\n this.address = address\n }\n\n protected async init(\n config: InstantiableConfig,\n contractConfig: { address: `0x${string}`; abi: Abi },\n ) {\n this.setInstanceConfig(config)\n this.address = contractConfig.address\n\n this.contract = getContract({\n address: contractConfig.address,\n abi: contractConfig.abi,\n client: { public: this.publicClient, wallet: this.walletClient },\n })\n }\n\n public async call<T>(functionName: string, args: any[], from?: string): Promise<T> {\n try {\n return (await this.client.public.readContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: parseAbi([functionName]),\n args,\n ...(from && { account: from as `0x${string}` }),\n })) as T\n //return await this.contract[functionSignature](...args, { from })\n } catch (err) {\n throw new ContractsError(\n `Calling method \"${functionName}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n }\n\n public async getTransactionReceipt(\n txHash: UserOperationReceipt | TransactionReceipt,\n ): Promise<TransactionReceipt> {\n // Get the transaction receipt depending on the type of txHash\n if ('transactionHash' in txHash) {\n // txHash is TransactionReceipt\n return txHash\n } else if ('userOpHash' in txHash) {\n // txHash is UserOperationReceipt, fetch the actual receipt using the utility function with retry logic\n const hash = txHash.receipt.transactionHash\n return await getTransactionReceipt({\n txHash: hash,\n publicClient: this.client.public,\n })\n } else {\n throw new Error('Unknown transaction type')\n }\n }\n\n public getTransactionLogs(\n txReceipt: TransactionReceipt | UserOperationReceipt,\n eventName?: string,\n ) {\n return parseEventLogs({\n abi: this.contract.abi,\n logs: txReceipt.logs,\n eventName,\n strict: false,\n }) as any[]\n }\n\n public async multicall(\n calls: MulticallEntry[],\n from: Account | SmartAccount,\n params: TxParameters = {},\n ) {\n if (from.type === 'local') {\n this.logger.debug(`Blockchain Multicall using Local account`)\n return await this.localAccountMulticall(calls, from, params, params.progress)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Blockchain Multicall using JSON-RPC account`)\n return await this.localAccountMulticall(calls, from, params, params.progress)\n } else if (from.type === 'smart') {\n this.logger.debug(`Blockchain Multicall using ZeroDev account`)\n return await this.internalMulticallSmartAccount(calls, from, params, params.progress)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n public async simulateMulticall(\n calls: SimulateMulticallEntry[],\n from: Account | SmartAccount,\n params: TxParameters = {},\n ) {\n if (from.type === 'local') {\n this.logger.debug(`Simulating calls using Local account`)\n return await this.localAccountSimulateMulticall(calls, from, params)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Simulating calls using JSON-RPC account`)\n return await this.localAccountSimulateMulticall(calls, from, params)\n } else if (from.type === 'smart') {\n this.logger.debug(`Simulating calls using Smart Account account`)\n return await this.internalSimulateMulticallSmartAccount(calls, from, params)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n public async simulate(\n functionName: string,\n from: Account | SmartAccount,\n args: any[],\n params: TxParameters = {},\n ) {\n if (from.type === 'local') {\n this.logger.debug(`Simulating calls using Local account`)\n return await this.localAccountSimulate(functionName, from, args, params)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Simulating calls using JSON-RPC account`)\n return await this.localAccountSimulate(functionName, from, args, params)\n } else if (from.type === 'smart') {\n this.logger.debug(`Simulating calls using Smart Account account`)\n return await this.internalSimulateSmartAccount(functionName, from, args, params)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n public async send(\n functionName: string,\n from: Account | SmartAccount,\n args: any[],\n params: TxParameters = {},\n ): Promise<TransactionReceipt | UserOperationReceipt> {\n if (from.type === 'local') {\n this.logger.debug(\n `Blockchain Send using Local account with functionName: ${functionName} and following args: ${args}`,\n )\n return await this.localAccountSend(functionName, from, args, params, params.progress)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Blockchain Send using JSON-RPC account to ${functionName}`)\n return await this.localAccountSend(functionName, from, args, params, params.progress)\n } else if (from.type === 'smart') {\n this.logger.debug(`Blockchain Send using ZeroDev account`)\n return await this.internalSendSmartAccount(functionName, from, args, params, params.progress)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n /**\n * Poll a previously-submitted UserOperation's receipt by hash WITHOUT\n * blocking. Returns the receipt once the bundler has mined it, or `null`\n * while it is still in the mempool / not yet known. A client-side\n * receipt-wait timeout does NOT cancel a submitted UserOp, so callers that\n * persist the hash (e.g. the onchain-mirror worker, nvm-monorepo#1508) use\n * this to confirm a prior submission instead of resubmitting a duplicate.\n */\n public async getUserOperationReceipt(hash: `0x${string}`): Promise<UserOperationReceipt | null> {\n try {\n const bundlerClient = createBundlerClient({\n chain: getChain(this.config.chainId),\n transport: http(this.getBundlerRPC()),\n client: this.client.public,\n })\n return (await bundlerClient.getUserOperationReceipt({ hash })) ?? null\n } catch (err) {\n // A genuinely-absent receipt (UserOp still in the mempool) is expected\n // and benign — some bundlers signal it by throwing rather than returning\n // null. Anything else (RPC/transport/config fault) must NOT masquerade as\n // \"still pending\": surface it at `warn` so a bundler outage is visible\n // instead of silently driving the caller's grace-window logic. Either\n // way we return null so the caller re-polls rather than consuming a retry.\n const message = err instanceof Error ? err.message : String(err)\n if (/not[\\s_]?found|UserOperationReceiptNotFound/i.test(message)) {\n this.logger.debug(`getUserOperationReceipt(${hash}): not yet mined`)\n } else {\n // Redact URLs before logging: the bundler RPC URL embeds the ZeroDev\n // project id, which should not leak into logs.\n const safeMessage = message.replace(/https?:\\/\\/[^\\s'\")]+/gi, '<redacted-url>')\n this.logger.warn(\n `getUserOperationReceipt(${hash}) lookup error (treating as not-yet-mined): ${safeMessage}`,\n )\n }\n return null\n }\n }\n\n private async internalMulticallSmartAccount(\n calls: MulticallEntry[],\n from: SmartAccount,\n txparams: any,\n progress: ((data: any) => void) | undefined,\n ) {\n if (progress) {\n progress({\n stage: 'multicall-sending',\n args: [],\n method: '',\n from: from,\n contractAddress: this.address,\n })\n }\n\n const kernelClient = createKernelAccountClient({\n account: from,\n chain: getChain(this.config.chainId),\n bundlerTransport: http(this.getBundlerRPC()),\n client: this.client.public,\n ...this.getPaymasterConfig(),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, this.client.public)\n },\n },\n })\n\n const encodedCalls: any[] = []\n calls.map((call) => {\n encodedCalls.push({\n to: call.contractAddress || this.address,\n value: txparams.value || 0n,\n data: encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args,\n }),\n })\n })\n\n let userOpHash: `0x${string}` | undefined\n try {\n // Random nonce key per send so concurrent userOps from the same SCA\n // hit distinct EntryPoint nonce channels instead of colliding on the\n // default `customNonceKey=0n`. See issue #1579.\n const nonce = await from.getNonce({ key: getRandomBigInt(ZERODEV_NONCE_KEY_BITS) })\n userOpHash = await kernelClient.sendUserOperation({\n callData: await kernelClient.account.encodeCalls(encodedCalls),\n nonce,\n })\n\n if (progress) {\n progress({\n stage: 'multicall-sent',\n args: [],\n method: '',\n from: from,\n contractAddress: this.address,\n })\n }\n\n // Wait for the transaction to be mined\n this.logger.debug(`Waiting for transaction to be mined... ${userOpHash}`)\n const txReceipt = await kernelClient.waitForUserOperationReceipt({\n hash: userOpHash,\n timeout: USEROP_RECEIPT_TIMEOUT_MS,\n })\n this.logger.debug(`Transaction mined - UserOperationHash: ${userOpHash}`)\n this.logger.debug(\n `Transaction receipt - TransactionHash: ${txReceipt.receipt.transactionHash}`,\n )\n this.assertUserOpSucceeded(txReceipt, 'multicall', userOpHash)\n return txReceipt.receipt\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n // Surface userOpHash so callers can poll for eventual inclusion before\n // retrying — a client-side receipt-wait timeout does NOT cancel the userOp.\n const hashSuffix = userOpHash ? ` userOpHash=${userOpHash}` : ''\n throw new ContractsError(`Multicall failed:${hashSuffix} ${err}`)\n }\n }\n\n private assertUserOpSucceeded(\n txReceipt: UserOperationReceipt,\n method: string,\n userOpHash: string,\n ): void {\n if (txReceipt.success) return\n throw new ContractsError(\n `UserOp inner call reverted for \"${method}\" on \"${this.contractName}\". ` +\n `userOpHash=${userOpHash} txHash=${txReceipt.receipt.transactionHash} ` +\n `reason=${txReceipt.reason ?? 'unknown'}`,\n )\n }\n\n private async internalSendSmartAccount(\n name: string,\n from: SmartAccount,\n args: any[],\n txparams: any,\n progress: ((data: any) => void) | undefined,\n ): Promise<UserOperationReceipt> {\n const functionInputs = getInputsOfFunctionFormatted(this.contract.abi, name, args)\n\n const { gasLimit, value } = txparams\n if (progress) {\n progress({\n stage: 'sending',\n args: functionInputs,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n }\n\n try {\n await this.client.public.simulateContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n\n const kernelClient = createKernelAccountClient({\n account: from,\n chain: getChain(this.config.chainId),\n bundlerTransport: http(this.getBundlerRPC()),\n client: this.client.public,\n ...this.getPaymasterConfig(),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, this.client.public)\n },\n },\n })\n const data = encodeFunctionData({ abi: this.contract.abi, functionName: name, args })\n\n let userOpHash\n try {\n // Random nonce key per send so concurrent userOps from the same SCA\n // hit distinct EntryPoint nonce channels instead of colliding on the\n // default `customNonceKey=0n`. See issue #1579.\n const nonce = await from.getNonce({ key: getRandomBigInt(ZERODEV_NONCE_KEY_BITS) })\n const callData = await kernelClient.account.encodeCalls([\n {\n to: this.address,\n value: txparams.value || 0n,\n data,\n },\n ])\n\n // When a caller supplies a `progress` callback it may need the UserOp\n // hash BEFORE the send completes — the onchain-mirror worker races the\n // send against a per-tick deadline and must persist the hash even if the\n // send is cut off mid-flight, otherwise it resubmits and double-burns\n // (#1508/#1904). So prepare the UserOp here, surface its hash via\n // `progress({stage:'prepared'})`, and send that exact prepared op so the\n // bundler-returned hash matches. Best-effort and GATED ON `progress`:\n // any failure falls back to the normal send, and callers that pass no\n // progress callback keep the original send path byte-for-byte.\n let preparedUserOp: Awaited<ReturnType<typeof kernelClient.prepareUserOperation>> | undefined\n let preparedHash: `0x${string}` | undefined\n if (progress) {\n try {\n preparedUserOp = await kernelClient.prepareUserOperation({ callData, nonce })\n preparedHash = getUserOperationHash({\n chainId: this.config.chainId,\n entryPointAddress: from.entryPoint.address,\n entryPointVersion: from.entryPoint.version,\n userOperation: preparedUserOp,\n })\n progress({\n stage: 'prepared',\n args: functionInputs,\n userOpHash: preparedHash,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n } catch (prepErr) {\n this.logger.warn(\n `prepareUserOperation (pre-send hash) failed for \"${name}\"; ` +\n `sending without an early hash: ${prepErr}`,\n )\n preparedUserOp = undefined\n preparedHash = undefined\n }\n }\n\n userOpHash = await kernelClient.sendUserOperation(\n // Re-send the exact prepared op (stripping the estimation stub\n // signature so the kernel re-signs) so the bundler hash matches the one\n // emitted above. Falls back to the original {callData, nonce} path\n // (which prepares internally) when no early hash was prepared.\n preparedUserOp\n ? ({ ...preparedUserOp, signature: undefined } as Parameters<\n typeof kernelClient.sendUserOperation\n >[0])\n : { callData, nonce },\n )\n\n // Determinism guard: the 'prepared' hash should equal the bundler's. If a\n // paymaster re-request changed the op it won't — a caller that persisted\n // the 'prepared' hash then just fails to find it and reconciles safely\n // (never a double-burn), but we log so we can see whether the early-hash\n // path is actually holding in practice.\n if (preparedHash && userOpHash !== preparedHash) {\n this.logger.warn(\n `UserOp 'prepared' hash ${preparedHash} != sent hash ${userOpHash} for \"${name}\"; ` +\n `early-hash callers will reconcile via receipt-not-found`,\n )\n }\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n\n if (progress) {\n progress({\n stage: 'sent',\n args: functionInputs,\n userOpHash,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n }\n\n let txReceipt: UserOperationReceipt\n try {\n txReceipt = await kernelClient.waitForUserOperationReceipt({\n hash: userOpHash,\n timeout: USEROP_RECEIPT_TIMEOUT_MS,\n })\n } catch (err) {\n // The userOp is already in the bundler mempool — a client-side timeout\n // does NOT cancel it. Surface userOpHash so callers can poll for eventual\n // inclusion before retrying, otherwise a retry can produce a duplicate\n // on-chain op. Wrap symmetric to `internalMulticallSmartAccount`.\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${this.contractName}\" timed out ` +\n `waiting for UserOp receipt. userOpHash=${userOpHash} — confirm on-chain ` +\n `inclusion before retrying. Underlying: ${err}`,\n )\n }\n\n this.assertUserOpSucceeded(txReceipt, name, userOpHash)\n\n if (progress) {\n progress({\n stage: 'receipt',\n args: functionInputs,\n txReceipt,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n }\n\n return txReceipt\n }\n\n private async internalSimulateSmartAccount(\n name: string,\n from: SmartAccount,\n args: any[],\n txparams: any,\n ) {\n try {\n await this.client.public.simulateContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: name,\n args,\n account: from.address,\n ...(txparams.value && { value: txparams.value }),\n })\n return true\n } catch (err) {\n throw new ContractSimulationError(\n `Error Simulating contract call \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n }\n\n private async localAccountSimulate(\n name: string,\n from: Account | `0x${string}`,\n args: any[],\n txparams: any,\n ) {\n try {\n await this.client.public.simulateContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n } catch (err) {\n throw new ContractSimulationError(\n `Error Simulating contract call \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n return true\n }\n\n private async localAccountSend(\n name: string,\n from: Account | `0x${string}`,\n args: any[],\n txparams: any,\n progress: ((data: any) => void) | undefined,\n _contractAbi?: Abi,\n _contractAddress?: Address,\n _contractName?: string,\n ) {\n const abi = _contractAbi || this.contract.abi\n const contractAddress = _contractAddress || this.address\n const contractName = _contractName || this.contractName\n\n const functionInputs = getInputsOfFunctionFormatted(abi, name, args)\n // Uncomment to debug contract calls\n // if (name === 'order') {\n // const functionSignature = getSignatureOfFunction(this.contract.abi, name, args)\n // this.logger.info(`Making contract call ....: ${name} - ${from}`)\n // this.logger.info(`With args: `, JSON.stringify(args, jsonReplacer))\n // this.logger.info(`And signature: ${JSON.stringify(functionSignature, jsonReplacer)}`)\n // this.logger.info('And amount: ', txparams.value)\n // }\n // abi.filter(({name, inputs}) => name === 'closeSignals' && inputs.length === 1)\n // const abiFilter = this.contract.abi.filter((abi) => abi.name === name && abi.inputs.length === args.length)\n // const abiFilter = this.contract.abi.filter((abi) => abi.name === name && abi.type === 'function')\n // console.debug('abi', this.contract.abi.filter((abi) => abi.name === name))\n // console.debug('abiFilter', abiFilter)\n // if (!abiFilter)\n // throw new ContractsError(\n // `No ABI found for method \"${name}\" with ${args.length} arguments on contract \"${this.contractName}\"`,\n // )\n\n const { gasLimit, value } = txparams\n // make the call\n if (progress) {\n progress({\n stage: 'sending',\n args: functionInputs,\n method: name,\n from,\n value,\n contractName,\n contractAddress,\n gasLimit,\n })\n }\n\n let txHash: `0x${string}` | undefined\n try {\n const { request } = await this.client.public.simulateContract({\n address: contractAddress,\n abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n\n // Resolve gas ourselves so `writeContract` never falls back to its own\n // `eth_estimateGas`. An explicit caller `gasLimit` always wins; otherwise\n // we estimate, apply the block-limit sanity check, and pin the result.\n // If estimation itself fails we still honour any explicit cap.\n let resolvedGas: bigint | undefined = gasLimit\n if (resolvedGas === undefined) {\n try {\n const estimate = await this.client.public.estimateContractGas({\n address: contractAddress,\n abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n resolvedGas = capForBogusEstimate(estimate, this.logger)\n } catch (estErr) {\n this.logger.warn(\n `estimateContractGas for \"${name}\" on \"${contractName}\" failed (${estErr}); ` +\n `falling back to ${GAS_FALLBACK_CAP} to avoid a bogus RPC re-estimate in writeContract.`,\n )\n resolvedGas = GAS_FALLBACK_CAP\n }\n }\n\n txHash = await this.client.wallet.writeContract({\n ...request,\n account: from,\n gas: resolvedGas,\n })\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n\n if (progress) {\n progress({\n stage: 'sent',\n args: functionInputs,\n txHash,\n method: name,\n from,\n value,\n contractName,\n contractAddress,\n gasLimit,\n })\n }\n const txReceipt = getTransactionReceipt({ txHash, publicClient: this.client.public })\n\n if (progress) {\n progress({\n stage: 'receipt',\n args: functionInputs,\n txReceipt,\n method: name,\n from,\n value,\n contractName,\n contractAddress,\n gasLimit,\n })\n }\n\n return txReceipt\n }\n\n private async localAccountMulticall(\n calls: MulticallEntry[],\n from: Account,\n txparams: any,\n progress: ((data: any) => void) | undefined,\n ): Promise<TransactionReceipt> {\n const receipts: TransactionReceipt[] = []\n for (const call of calls) {\n receipts.push(\n await this.localAccountSend(\n call.functionName,\n from,\n call.args,\n txparams,\n progress,\n call.abi,\n call.contractAddress,\n call.contractName,\n ),\n )\n }\n if (receipts.length > 0) return receipts.pop() as TransactionReceipt\n else throw new ContractsError(`No receipts found for multicall`)\n }\n\n private async localAccountSimulateMulticall(\n calls: SimulateMulticallEntry[],\n from: Account,\n txparams: any,\n ) {\n try {\n const { results } = await this.client.public.simulateCalls({\n calls,\n account: from,\n })\n this.logger.debug(`Simulated multicall - ${results}`)\n return true\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(`Error simulating multicall - ${err}`)\n }\n }\n\n private async internalSimulateMulticallSmartAccount(\n calls: SimulateMulticallEntry[],\n from: SmartAccount,\n txparams: any,\n ) {\n try {\n const kernelClient = createKernelAccountClient({\n account: from,\n chain: getChain(this.config.chainId),\n bundlerTransport: http(this.getBundlerRPC()),\n client: this.client.public,\n ...this.getPaymasterConfig(),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, this.client.public)\n },\n },\n })\n\n const encodedCalls = []\n for (const call of calls) {\n encodedCalls.push({\n to: call.to,\n value: call.value || 0n,\n data: encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args,\n }),\n })\n }\n\n // DONT DELETE THE COMMENTED LINES - ARE NECESSARY FOR F***ING ZERODEV DEBUGGING\n\n // this.logger.info(`Encoded multicall - ${JSON.stringify(encodedCalls, jsonReplacer)}`)\n // const code = await this.client.public.getCode({ address: from.address })\n // const isDeployed = code !== undefined && code !== '0x'\n // this.logger.info(`++++++ Smart account ${from.address} deployment status: ${isDeployed ? 'DEPLOYED' : 'NOT DEPLOYED'}`)\n\n // // Log account details\n // this.logger.info(`Account type: ${from.type}`)\n // this.logger.info(`Account address: ${from.address}`)\n\n // // Log the calls being made\n // this.logger.info(`Number of calls: ${encodedCalls.length}`)\n // encodedCalls.forEach((call, index) => {\n // this.logger.info(`Call ${index}: to=${call.to}, value=${call.value}, data=${call.data.slice(0, 10)}...`)\n // })\n\n await kernelClient.prepareUserOperation({\n callData: await kernelClient.account.encodeCalls(encodedCalls),\n })\n\n return true\n } catch (err) {\n this.logger.error(`Error details: ${JSON.stringify(err, null, 2)}`)\n if (err instanceof BaseError) {\n const revertError = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (revertError) {\n this.logger.error(`Revert error: ${String(revertError)}`)\n }\n }\n throw new ContractSimulationError(`Error Simulating Multicalls - ${err}`)\n }\n }\n\n private getOrCreatePaymaster() {\n if (!this._zeroDevPaymaster) {\n this._zeroDevPaymaster = createZeroDevPaymasterClient({\n chain: getChain(this.config.chainId),\n transport: http(this.getPaymasterRPC()),\n })\n }\n return this._zeroDevPaymaster\n }\n\n /**\n * Builds the `paymaster` partial for `createKernelAccountClient`. In relayer\n * mode (e.g. local `ultra-relay` for tests) returns an empty object so the\n * kernel client submits UserOps without paymaster fields and the bundler\n * pays gas via its executor key. In production returns the ZeroDev paymaster\n * sponsorship callback.\n */\n private getPaymasterConfig() {\n if (isRelayerMode()) return {}\n const zerodevPaymaster = this.getOrCreatePaymaster()\n return {\n paymaster: {\n getPaymasterData: (userOperation: any) =>\n zerodevPaymaster.sponsorUserOperation({ userOperation }),\n },\n }\n }\n\n protected getBundlerRPC(): string {\n // In relayer mode `getBundlerRpcUrl` reads `BUNDLER_RPC_URL_OVERRIDE`\n // and never touches the project id, so an empty value is harmless. In\n // production callers must pass a project id — surface a clear error if\n // the SDK was instantiated without one and we need it.\n const projectId = this.config.zeroDevProjectId\n if (!projectId && !isRelayerMode()) {\n throw new ContractsError(\n 'getBundlerRPC: zeroDevProjectId is required for non-relayer (production) mode',\n )\n }\n return getBundlerRpcUrl(projectId ?? '', this.config.chainId, this.config.useUltraRelay)\n }\n\n private getPaymasterRPC(): string {\n // Only ever consulted when `getPaymasterConfig` decides to attach a\n // paymaster, which is gated on `!isRelayerMode()`. A missing project\n // id at this point is a configuration bug worth surfacing.\n const projectId = this.config.zeroDevProjectId\n if (!projectId) {\n throw new ContractsError(\n 'getPaymasterRPC: zeroDevProjectId is required to build the paymaster URL',\n )\n }\n return getPaymasterRpcUrl(projectId, this.config.chainId)\n }\n}\n"],"names":["createKernelAccountClient","createZeroDevPaymasterClient","estimateUserOperationFees","getBundlerRpcUrl","getPaymasterRpcUrl","isRelayerMode","BaseError","ContractFunctionRevertedError","encodeFunctionData","getContract","http","parseAbi","parseEventLogs","createBundlerClient","getUserOperationHash","ContractsError","ContractSimulationError","Instantiable","getInputsOfFunctionFormatted","getTransactionReceipt","getRandomBigInt","getChain","GAS_SANITY_THRESHOLD","GAS_FALLBACK_CAP","ZERODEV_NONCE_KEY_BITS","USEROP_RECEIPT_TIMEOUT_MS","capForBogusEstimate","estimatedGas","logger","warn","ContractBase","contractName","address","_zeroDevPaymaster","init","config","contractConfig","setInstanceConfig","contract","abi","client","public","publicClient","wallet","walletClient","call","functionName","args","from","readContract","account","err","txHash","hash","receipt","transactionHash","Error","getTransactionLogs","txReceipt","eventName","logs","strict","multicall","calls","params","type","debug","localAccountMulticall","progress","internalMulticallSmartAccount","simulateMulticall","localAccountSimulateMulticall","internalSimulateMulticallSmartAccount","simulate","localAccountSimulate","internalSimulateSmartAccount","send","localAccountSend","internalSendSmartAccount","getUserOperationReceipt","bundlerClient","chain","chainId","transport","getBundlerRPC","message","String","test","safeMessage","replace","txparams","stage","method","contractAddress","kernelClient","bundlerTransport","getPaymasterConfig","userOperation","estimateFeesPerGas","encodedCalls","map","push","to","value","data","userOpHash","nonce","getNonce","key","sendUserOperation","callData","encodeCalls","waitForUserOperationReceipt","timeout","assertUserOpSucceeded","revertError","walk","error","hashSuffix","success","reason","name","functionInputs","gasLimit","simulateContract","preparedUserOp","preparedHash","prepareUserOperation","entryPointAddress","entryPoint","entryPointVersion","version","prepErr","undefined","signature","_contractAbi","_contractAddress","_contractName","request","resolvedGas","estimate","estimateContractGas","estErr","writeContract","gas","receipts","length","pop","results","simulateCalls","JSON","stringify","e","getOrCreatePaymaster","getPaymasterRPC","zerodevPaymaster","paymaster","getPaymasterData","sponsorUserOperation","projectId","zeroDevProjectId","useUltraRelay"],"mappings":"AAAA,SAASA,yBAAyB,EAAEC,4BAA4B,QAAQ,eAAc;AACtF,SACEC,yBAAyB,EACzBC,gBAAgB,EAChBC,kBAAkB,EAClBC,aAAa,QACR,6CAA4C;AACnD,SAIEC,SAAS,EACTC,6BAA6B,EAC7BC,kBAAkB,EAClBC,WAAW,EACXC,IAAI,EACJC,QAAQ,EACRC,cAAc,QAET,OAAM;AACb,SACEC,mBAAmB,EACnBC,oBAAoB,QAGf,2BAA0B;AACjC,SAASC,cAAc,EAAEC,uBAAuB,QAAQ,qBAAoB;AAC5E,SAASC,YAAY,QAA4B,8BAA6B;AAE9E,SAASC,4BAA4B,EAAEC,qBAAqB,QAAQ,yBAAwB;AAC5F,SAASC,eAAe,QAAQ,sBAAqB;AACrD,SAASC,QAAQ,QAAQ,sBAAqB;AAU9C;;;;;;;;;;;;CAYC,GACD,MAAMC,uBAAuB,WAAW;AACxC,MAAMC,mBAAmB,UAAU;AAEnC,2FAA2F;AAC3F,uFAAuF;AACvF,qFAAqF;AACrF,qFAAqF;AACrF,MAAMC,yBAAyB;AAE/B,yFAAyF;AACzF,yFAAyF;AACzF,yFAAyF;AACzF,0EAA0E;AAC1E,MAAMC,4BAA4B;AAElC,SAASC,oBACPC,YAAoB,EACpBC,MAAuC;IAEvC,IAAID,eAAeL,sBAAsB,OAAOK;IAChDC,OAAOC,IAAI,CACT,CAAC,eAAe,EAAEF,aAAa,2BAA2B,CAAC,GACzD,CAAC,CAAC,EAAEL,qBAAqB,mBAAmB,EAAEC,iBAAiB,oCAAoC,CAAC;IAExG,OAAOA;AACT;AAUA,OAAO,MAAeO,qBAAqBb;IAMzC,YAAYc,YAAoB,EAAEC,OAAgB,CAAE;QAClD,KAAK,SAHCC,oBAA4E;QAIlF,IAAI,CAACF,YAAY,GAAGA;QACpB,IAAI,CAACC,OAAO,GAAGA;IACjB;IAEA,MAAgBE,KACdC,MAA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BG,oBAAoB,CAAC;wBAAE7D;oBAAc;YAC1D;QACF;IACF;IAEUb,gBAAwB;QAChC,sEAAsE;QACtE,sEAAsE;QACtE,uEAAuE;QACvE,uDAAuD;QACvD,MAAM2E,YAAY,IAAI,CAAC5H,MAAM,CAAC6H,gBAAgB;QAC9C,IAAI,CAACD,aAAa,CAAC1J,iBAAiB;YAClC,MAAM,IAAIU,eACR;QAEJ;QACA,OAAOZ,iBAAiB4J,aAAa,IAAI,IAAI,CAAC5H,MAAM,CAAC+C,OAAO,EAAE,IAAI,CAAC/C,MAAM,CAAC8H,aAAa;IACzF;IAEQP,kBAA0B;QAChC,oEAAoE;QACpE,qEAAqE;QACrE,2DAA2D;QAC3D,MAAMK,YAAY,IAAI,CAAC5H,MAAM,CAAC6H,gBAAgB;QAC9C,IAAI,CAACD,WAAW;YACd,MAAM,IAAIhJ,eACR;QAEJ;QACA,OAAOX,mBAAmB2J,WAAW,IAAI,CAAC5H,MAAM,CAAC+C,OAAO;IAC1D;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/contracts/ContractBase.ts"],"sourcesContent":["import { createKernelAccountClient, createZeroDevPaymasterClient } from '@zerodev/sdk'\nimport {\n applyTempoVerificationGasFloor,\n estimateUserOperationFees,\n getBundlerRpcUrl,\n getPaymasterRpcUrl,\n isRelayerMode,\n} from '../nevermined/utils/BlockchainViemUtils.js'\nimport {\n Abi,\n Account,\n Address,\n BaseError,\n ContractFunctionRevertedError,\n encodeFunctionData,\n getContract,\n http,\n parseAbi,\n parseEventLogs,\n TransactionReceipt,\n} from 'viem'\nimport {\n createBundlerClient,\n getUserOperationHash,\n SmartAccount,\n UserOperationReceipt,\n} from 'viem/account-abstraction'\nimport { ContractsError, ContractSimulationError } from '../errors/index.js'\nimport { Instantiable, InstantiableConfig } from '../Instantiable.abstract.js'\nimport { TxParameters } from '../models/Transactions.js'\nimport { getInputsOfFunctionFormatted, getTransactionReceipt } from '../nevermined/index.js'\nimport { getRandomBigInt } from '../utils/helpers.js'\nimport { getChain } from '../utils/Network.js'\n\nexport interface MulticallEntry {\n contractName?: string\n contractAddress: Address\n abi: Abi\n functionName: string\n args: any[]\n}\n\n/**\n * When a testnet RPC (Base Sepolia) fails internally, some providers return\n * `eth_estimateGas` values equal to — or even above — the block gas limit\n * instead of a real error. Using that value causes the node to reject the tx\n * with `intrinsic gas too high` before it ever reaches the mempool.\n *\n * `writeContract` in viem re-estimates gas internally when `gas` isn't\n * already set on the request (viem's `simulateContract` only performs\n * `eth_call`, not `eth_estimateGas`). That means the naïve path has no\n * chance to intercept a bogus estimate. We run the estimation ourselves\n * here, sanity-check the result, and always pass an explicit gas value\n * into `writeContract` so it doesn't re-query the misbehaving RPC.\n */\nconst GAS_SANITY_THRESHOLD = 25_000_000n\nconst GAS_FALLBACK_CAP = 5_000_000n\n\n// EntryPoint v0.7: ZeroDev's `toKernelPluginManager` rejects `customNonceKey > maxUint16`.\n// 16 bits = 65 536 channels — collision probability for the SDK's expected concurrency\n// (k=2–5 parallel sends from one SCA) is negligible (< 0.02 %). High-fan-out callers\n// (k > 50) should consider a per-process monotonic counter instead. See issue #1579.\nconst ZERODEV_NONCE_KEY_BITS = 16\n\n// Client-side cap on `waitForUserOperationReceipt`. The userOp is already in the bundler\n// mempool when this fires — a client-side timeout does NOT cancel it. Callers that catch\n// the resulting `ContractsError` MUST poll `bundlerClient.getUserOperationReceipt(hash)`\n// before retrying; otherwise a retry can produce a duplicate on-chain op.\nconst USEROP_RECEIPT_TIMEOUT_MS = 90_000\n\nfunction capForBogusEstimate(\n estimatedGas: bigint,\n logger: { warn: (msg: string) => void },\n): bigint {\n if (estimatedGas < GAS_SANITY_THRESHOLD) return estimatedGas\n logger.warn(\n `Estimated gas (${estimatedGas}) exceeds sanity threshold ` +\n `(${GAS_SANITY_THRESHOLD}); overriding with ${GAS_FALLBACK_CAP} to bypass misbehaving RPC estimate.`,\n )\n return GAS_FALLBACK_CAP\n}\n\nexport interface SimulateMulticallEntry {\n functionName: string\n value?: bigint\n abi: Abi\n args: any[]\n to: Address\n}\n\nexport abstract class ContractBase extends Instantiable {\n public readonly contractName: string\n public contract: any\n public address: Address\n private _zeroDevPaymaster: ReturnType<typeof createZeroDevPaymasterClient> | null = null\n\n constructor(contractName: string, address: Address) {\n super()\n this.contractName = contractName\n this.address = address\n }\n\n protected async init(\n config: InstantiableConfig,\n contractConfig: { address: `0x${string}`; abi: Abi },\n ) {\n this.setInstanceConfig(config)\n this.address = contractConfig.address\n\n this.contract = getContract({\n address: contractConfig.address,\n abi: contractConfig.abi,\n client: { public: this.publicClient, wallet: this.walletClient },\n })\n }\n\n public async call<T>(functionName: string, args: any[], from?: string): Promise<T> {\n try {\n return (await this.client.public.readContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: parseAbi([functionName]),\n args,\n ...(from && { account: from as `0x${string}` }),\n })) as T\n //return await this.contract[functionSignature](...args, { from })\n } catch (err) {\n throw new ContractsError(\n `Calling method \"${functionName}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n }\n\n public async getTransactionReceipt(\n txHash: UserOperationReceipt | TransactionReceipt,\n ): Promise<TransactionReceipt> {\n // Get the transaction receipt depending on the type of txHash\n if ('transactionHash' in txHash) {\n // txHash is TransactionReceipt\n return txHash\n } else if ('userOpHash' in txHash) {\n // txHash is UserOperationReceipt, fetch the actual receipt using the utility function with retry logic\n const hash = txHash.receipt.transactionHash\n return await getTransactionReceipt({\n txHash: hash,\n publicClient: this.client.public,\n })\n } else {\n throw new Error('Unknown transaction type')\n }\n }\n\n public getTransactionLogs(\n txReceipt: TransactionReceipt | UserOperationReceipt,\n eventName?: string,\n ) {\n return parseEventLogs({\n abi: this.contract.abi,\n logs: txReceipt.logs,\n eventName,\n strict: false,\n }) as any[]\n }\n\n public async multicall(\n calls: MulticallEntry[],\n from: Account | SmartAccount,\n params: TxParameters = {},\n ) {\n if (from.type === 'local') {\n this.logger.debug(`Blockchain Multicall using Local account`)\n return await this.localAccountMulticall(calls, from, params, params.progress)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Blockchain Multicall using JSON-RPC account`)\n return await this.localAccountMulticall(calls, from, params, params.progress)\n } else if (from.type === 'smart') {\n this.logger.debug(`Blockchain Multicall using ZeroDev account`)\n return await this.internalMulticallSmartAccount(calls, from, params, params.progress)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n public async simulateMulticall(\n calls: SimulateMulticallEntry[],\n from: Account | SmartAccount,\n params: TxParameters = {},\n ) {\n if (from.type === 'local') {\n this.logger.debug(`Simulating calls using Local account`)\n return await this.localAccountSimulateMulticall(calls, from, params)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Simulating calls using JSON-RPC account`)\n return await this.localAccountSimulateMulticall(calls, from, params)\n } else if (from.type === 'smart') {\n this.logger.debug(`Simulating calls using Smart Account account`)\n return await this.internalSimulateMulticallSmartAccount(calls, from, params)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n public async simulate(\n functionName: string,\n from: Account | SmartAccount,\n args: any[],\n params: TxParameters = {},\n ) {\n if (from.type === 'local') {\n this.logger.debug(`Simulating calls using Local account`)\n return await this.localAccountSimulate(functionName, from, args, params)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Simulating calls using JSON-RPC account`)\n return await this.localAccountSimulate(functionName, from, args, params)\n } else if (from.type === 'smart') {\n this.logger.debug(`Simulating calls using Smart Account account`)\n return await this.internalSimulateSmartAccount(functionName, from, args, params)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n public async send(\n functionName: string,\n from: Account | SmartAccount,\n args: any[],\n params: TxParameters = {},\n ): Promise<TransactionReceipt | UserOperationReceipt> {\n if (from.type === 'local') {\n this.logger.debug(\n `Blockchain Send using Local account with functionName: ${functionName} and following args: ${args}`,\n )\n return await this.localAccountSend(functionName, from, args, params, params.progress)\n } else if (from.type === 'json-rpc') {\n this.logger.debug(`Blockchain Send using JSON-RPC account to ${functionName}`)\n return await this.localAccountSend(functionName, from, args, params, params.progress)\n } else if (from.type === 'smart') {\n this.logger.debug(`Blockchain Send using ZeroDev account`)\n return await this.internalSendSmartAccount(functionName, from, args, params, params.progress)\n } else {\n throw new ContractsError(`Account not supported`)\n }\n }\n\n /**\n * Poll a previously-submitted UserOperation's receipt by hash WITHOUT\n * blocking. Returns the receipt once the bundler has mined it, or `null`\n * while it is still in the mempool / not yet known. A client-side\n * receipt-wait timeout does NOT cancel a submitted UserOp, so callers that\n * persist the hash (e.g. the onchain-mirror worker, nvm-monorepo#1508) use\n * this to confirm a prior submission instead of resubmitting a duplicate.\n */\n public async getUserOperationReceipt(hash: `0x${string}`): Promise<UserOperationReceipt | null> {\n try {\n const bundlerClient = createBundlerClient({\n chain: getChain(this.config.chainId),\n transport: http(this.getBundlerRPC()),\n client: this.client.public,\n })\n return (await bundlerClient.getUserOperationReceipt({ hash })) ?? null\n } catch (err) {\n // A genuinely-absent receipt (UserOp still in the mempool) is expected\n // and benign — some bundlers signal it by throwing rather than returning\n // null. Anything else (RPC/transport/config fault) must NOT masquerade as\n // \"still pending\": surface it at `warn` so a bundler outage is visible\n // instead of silently driving the caller's grace-window logic. Either\n // way we return null so the caller re-polls rather than consuming a retry.\n const message = err instanceof Error ? err.message : String(err)\n if (/not[\\s_]?found|UserOperationReceiptNotFound/i.test(message)) {\n this.logger.debug(`getUserOperationReceipt(${hash}): not yet mined`)\n } else {\n // Redact URLs before logging: the bundler RPC URL embeds the ZeroDev\n // project id, which should not leak into logs.\n const safeMessage = message.replace(/https?:\\/\\/[^\\s'\")]+/gi, '<redacted-url>')\n this.logger.warn(\n `getUserOperationReceipt(${hash}) lookup error (treating as not-yet-mined): ${safeMessage}`,\n )\n }\n return null\n }\n }\n\n private async internalMulticallSmartAccount(\n calls: MulticallEntry[],\n from: SmartAccount,\n txparams: any,\n progress: ((data: any) => void) | undefined,\n ) {\n if (progress) {\n progress({\n stage: 'multicall-sending',\n args: [],\n method: '',\n from: from,\n contractAddress: this.address,\n })\n }\n\n const kernelClient = createKernelAccountClient({\n account: from,\n chain: getChain(this.config.chainId),\n bundlerTransport: http(this.getBundlerRPC()),\n client: this.client.public,\n ...this.getPaymasterConfig(),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, this.client.public)\n },\n },\n })\n\n const encodedCalls: any[] = []\n calls.map((call) => {\n encodedCalls.push({\n to: call.contractAddress || this.address,\n value: txparams.value || 0n,\n data: encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args,\n }),\n })\n })\n\n let userOpHash: `0x${string}` | undefined\n try {\n // Random nonce key per send so concurrent userOps from the same SCA\n // hit distinct EntryPoint nonce channels instead of colliding on the\n // default `customNonceKey=0n`. See issue #1579.\n const nonce = await from.getNonce({ key: getRandomBigInt(ZERODEV_NONCE_KEY_BITS) })\n userOpHash = await kernelClient.sendUserOperation({\n callData: await kernelClient.account.encodeCalls(encodedCalls),\n nonce,\n })\n\n if (progress) {\n progress({\n stage: 'multicall-sent',\n args: [],\n method: '',\n from: from,\n contractAddress: this.address,\n })\n }\n\n // Wait for the transaction to be mined\n this.logger.debug(`Waiting for transaction to be mined... ${userOpHash}`)\n const txReceipt = await kernelClient.waitForUserOperationReceipt({\n hash: userOpHash,\n timeout: USEROP_RECEIPT_TIMEOUT_MS,\n })\n this.logger.debug(`Transaction mined - UserOperationHash: ${userOpHash}`)\n this.logger.debug(\n `Transaction receipt - TransactionHash: ${txReceipt.receipt.transactionHash}`,\n )\n this.assertUserOpSucceeded(txReceipt, 'multicall', userOpHash)\n return txReceipt.receipt\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n // Surface userOpHash so callers can poll for eventual inclusion before\n // retrying — a client-side receipt-wait timeout does NOT cancel the userOp.\n const hashSuffix = userOpHash ? ` userOpHash=${userOpHash}` : ''\n throw new ContractsError(`Multicall failed:${hashSuffix} ${err}`)\n }\n }\n\n private assertUserOpSucceeded(\n txReceipt: UserOperationReceipt,\n method: string,\n userOpHash: string,\n ): void {\n if (txReceipt.success) return\n throw new ContractsError(\n `UserOp inner call reverted for \"${method}\" on \"${this.contractName}\". ` +\n `userOpHash=${userOpHash} txHash=${txReceipt.receipt.transactionHash} ` +\n `reason=${txReceipt.reason ?? 'unknown'}`,\n )\n }\n\n private async internalSendSmartAccount(\n name: string,\n from: SmartAccount,\n args: any[],\n txparams: any,\n progress: ((data: any) => void) | undefined,\n ): Promise<UserOperationReceipt> {\n const functionInputs = getInputsOfFunctionFormatted(this.contract.abi, name, args)\n\n const { gasLimit, value } = txparams\n if (progress) {\n progress({\n stage: 'sending',\n args: functionInputs,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n }\n\n try {\n await this.client.public.simulateContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n\n const kernelClient = createKernelAccountClient({\n account: from,\n chain: getChain(this.config.chainId),\n bundlerTransport: http(this.getBundlerRPC()),\n client: this.client.public,\n ...this.getPaymasterConfig(),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, this.client.public)\n },\n },\n })\n const data = encodeFunctionData({ abi: this.contract.abi, functionName: name, args })\n\n let userOpHash\n try {\n // Random nonce key per send so concurrent userOps from the same SCA\n // hit distinct EntryPoint nonce channels instead of colliding on the\n // default `customNonceKey=0n`. See issue #1579.\n const nonce = await from.getNonce({ key: getRandomBigInt(ZERODEV_NONCE_KEY_BITS) })\n const callData = await kernelClient.account.encodeCalls([\n {\n to: this.address,\n value: txparams.value || 0n,\n data,\n },\n ])\n\n // When a caller supplies a `progress` callback it may need the UserOp\n // hash BEFORE the send completes — the onchain-mirror worker races the\n // send against a per-tick deadline and must persist the hash even if the\n // send is cut off mid-flight, otherwise it resubmits and double-burns\n // (#1508/#1904). So prepare the UserOp here, surface its hash via\n // `progress({stage:'prepared'})`, and send that exact prepared op so the\n // bundler-returned hash matches. Best-effort and GATED ON `progress`:\n // any failure falls back to the normal send, and callers that pass no\n // progress callback keep the original send path byte-for-byte.\n let preparedUserOp: Awaited<ReturnType<typeof kernelClient.prepareUserOperation>> | undefined\n let preparedHash: `0x${string}` | undefined\n if (progress) {\n try {\n preparedUserOp = await kernelClient.prepareUserOperation({ callData, nonce })\n preparedHash = getUserOperationHash({\n chainId: this.config.chainId,\n entryPointAddress: from.entryPoint.address,\n entryPointVersion: from.entryPoint.version,\n userOperation: preparedUserOp,\n })\n progress({\n stage: 'prepared',\n args: functionInputs,\n userOpHash: preparedHash,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n } catch (prepErr) {\n this.logger.warn(\n `prepareUserOperation (pre-send hash) failed for \"${name}\"; ` +\n `sending without an early hash: ${prepErr}`,\n )\n preparedUserOp = undefined\n preparedHash = undefined\n }\n }\n\n userOpHash = await kernelClient.sendUserOperation(\n // Re-send the exact prepared op (stripping the estimation stub\n // signature so the kernel re-signs) so the bundler hash matches the one\n // emitted above. Falls back to the original {callData, nonce} path\n // (which prepares internally) when no early hash was prepared.\n preparedUserOp\n ? ({ ...preparedUserOp, signature: undefined } as Parameters<\n typeof kernelClient.sendUserOperation\n >[0])\n : { callData, nonce },\n )\n\n // Determinism guard: the 'prepared' hash should equal the bundler's. If a\n // paymaster re-request changed the op it won't — a caller that persisted\n // the 'prepared' hash then just fails to find it and reconciles safely\n // (never a double-burn), but we log so we can see whether the early-hash\n // path is actually holding in practice.\n if (preparedHash && userOpHash !== preparedHash) {\n this.logger.warn(\n `UserOp 'prepared' hash ${preparedHash} != sent hash ${userOpHash} for \"${name}\"; ` +\n `early-hash callers will reconcile via receipt-not-found`,\n )\n }\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n\n if (progress) {\n progress({\n stage: 'sent',\n args: functionInputs,\n userOpHash,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n }\n\n let txReceipt: UserOperationReceipt\n try {\n txReceipt = await kernelClient.waitForUserOperationReceipt({\n hash: userOpHash,\n timeout: USEROP_RECEIPT_TIMEOUT_MS,\n })\n } catch (err) {\n // The userOp is already in the bundler mempool — a client-side timeout\n // does NOT cancel it. Surface userOpHash so callers can poll for eventual\n // inclusion before retrying, otherwise a retry can produce a duplicate\n // on-chain op. Wrap symmetric to `internalMulticallSmartAccount`.\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${this.contractName}\" timed out ` +\n `waiting for UserOp receipt. userOpHash=${userOpHash} — confirm on-chain ` +\n `inclusion before retrying. Underlying: ${err}`,\n )\n }\n\n this.assertUserOpSucceeded(txReceipt, name, userOpHash)\n\n if (progress) {\n progress({\n stage: 'receipt',\n args: functionInputs,\n txReceipt,\n method: name,\n from: from,\n value,\n contractName: this.contractName,\n contractAddress: this.address,\n gasLimit,\n })\n }\n\n return txReceipt\n }\n\n private async internalSimulateSmartAccount(\n name: string,\n from: SmartAccount,\n args: any[],\n txparams: any,\n ) {\n try {\n await this.client.public.simulateContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: name,\n args,\n account: from.address,\n ...(txparams.value && { value: txparams.value }),\n })\n return true\n } catch (err) {\n throw new ContractSimulationError(\n `Error Simulating contract call \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n }\n\n private async localAccountSimulate(\n name: string,\n from: Account | `0x${string}`,\n args: any[],\n txparams: any,\n ) {\n try {\n await this.client.public.simulateContract({\n address: this.address,\n abi: this.contract.abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n } catch (err) {\n throw new ContractSimulationError(\n `Error Simulating contract call \"${name}\" on contract \"${this.contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n return true\n }\n\n private async localAccountSend(\n name: string,\n from: Account | `0x${string}`,\n args: any[],\n txparams: any,\n progress: ((data: any) => void) | undefined,\n _contractAbi?: Abi,\n _contractAddress?: Address,\n _contractName?: string,\n ) {\n const abi = _contractAbi || this.contract.abi\n const contractAddress = _contractAddress || this.address\n const contractName = _contractName || this.contractName\n\n const functionInputs = getInputsOfFunctionFormatted(abi, name, args)\n // Uncomment to debug contract calls\n // if (name === 'order') {\n // const functionSignature = getSignatureOfFunction(this.contract.abi, name, args)\n // this.logger.info(`Making contract call ....: ${name} - ${from}`)\n // this.logger.info(`With args: `, JSON.stringify(args, jsonReplacer))\n // this.logger.info(`And signature: ${JSON.stringify(functionSignature, jsonReplacer)}`)\n // this.logger.info('And amount: ', txparams.value)\n // }\n // abi.filter(({name, inputs}) => name === 'closeSignals' && inputs.length === 1)\n // const abiFilter = this.contract.abi.filter((abi) => abi.name === name && abi.inputs.length === args.length)\n // const abiFilter = this.contract.abi.filter((abi) => abi.name === name && abi.type === 'function')\n // console.debug('abi', this.contract.abi.filter((abi) => abi.name === name))\n // console.debug('abiFilter', abiFilter)\n // if (!abiFilter)\n // throw new ContractsError(\n // `No ABI found for method \"${name}\" with ${args.length} arguments on contract \"${this.contractName}\"`,\n // )\n\n const { gasLimit, value } = txparams\n // make the call\n if (progress) {\n progress({\n stage: 'sending',\n args: functionInputs,\n method: name,\n from,\n value,\n contractName,\n contractAddress,\n gasLimit,\n })\n }\n\n let txHash: `0x${string}` | undefined\n try {\n const { request } = await this.client.public.simulateContract({\n address: contractAddress,\n abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n\n // Resolve gas ourselves so `writeContract` never falls back to its own\n // `eth_estimateGas`. An explicit caller `gasLimit` always wins; otherwise\n // we estimate, apply the block-limit sanity check, and pin the result.\n // If estimation itself fails we still honour any explicit cap.\n let resolvedGas: bigint | undefined = gasLimit\n if (resolvedGas === undefined) {\n try {\n const estimate = await this.client.public.estimateContractGas({\n address: contractAddress,\n abi,\n functionName: name,\n args,\n account: from,\n ...(txparams.value && { value: txparams.value }),\n })\n resolvedGas = capForBogusEstimate(estimate, this.logger)\n } catch (estErr) {\n this.logger.warn(\n `estimateContractGas for \"${name}\" on \"${contractName}\" failed (${estErr}); ` +\n `falling back to ${GAS_FALLBACK_CAP} to avoid a bogus RPC re-estimate in writeContract.`,\n )\n resolvedGas = GAS_FALLBACK_CAP\n }\n }\n\n txHash = await this.client.wallet.writeContract({\n ...request,\n account: from,\n gas: resolvedGas,\n })\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(\n `Calling method \"${name}\" on contract \"${contractName}\" failed. Args: ${args} - ${err}`,\n )\n }\n\n if (progress) {\n progress({\n stage: 'sent',\n args: functionInputs,\n txHash,\n method: name,\n from,\n value,\n contractName,\n contractAddress,\n gasLimit,\n })\n }\n const txReceipt = getTransactionReceipt({ txHash, publicClient: this.client.public })\n\n if (progress) {\n progress({\n stage: 'receipt',\n args: functionInputs,\n txReceipt,\n method: name,\n from,\n value,\n contractName,\n contractAddress,\n gasLimit,\n })\n }\n\n return txReceipt\n }\n\n private async localAccountMulticall(\n calls: MulticallEntry[],\n from: Account,\n txparams: any,\n progress: ((data: any) => void) | undefined,\n ): Promise<TransactionReceipt> {\n const receipts: TransactionReceipt[] = []\n for (const call of calls) {\n receipts.push(\n await this.localAccountSend(\n call.functionName,\n from,\n call.args,\n txparams,\n progress,\n call.abi,\n call.contractAddress,\n call.contractName,\n ),\n )\n }\n if (receipts.length > 0) return receipts.pop() as TransactionReceipt\n else throw new ContractsError(`No receipts found for multicall`)\n }\n\n private async localAccountSimulateMulticall(\n calls: SimulateMulticallEntry[],\n from: Account,\n txparams: any,\n ) {\n try {\n const { results } = await this.client.public.simulateCalls({\n calls,\n account: from,\n })\n this.logger.debug(`Simulated multicall - ${results}`)\n return true\n } catch (err) {\n if (err instanceof BaseError) {\n const revertError = err.walk((err) => err instanceof ContractFunctionRevertedError)\n this.logger.error(`revertError: ${String(revertError)}`)\n }\n throw new ContractsError(`Error simulating multicall - ${err}`)\n }\n }\n\n private async internalSimulateMulticallSmartAccount(\n calls: SimulateMulticallEntry[],\n from: SmartAccount,\n txparams: any,\n ) {\n try {\n const kernelClient = createKernelAccountClient({\n account: from,\n chain: getChain(this.config.chainId),\n bundlerTransport: http(this.getBundlerRPC()),\n client: this.client.public,\n ...this.getPaymasterConfig(),\n userOperation: {\n estimateFeesPerGas: async ({ bundlerClient }) => {\n return estimateUserOperationFees(bundlerClient, this.client.public)\n },\n },\n })\n\n const encodedCalls = []\n for (const call of calls) {\n encodedCalls.push({\n to: call.to,\n value: call.value || 0n,\n data: encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args,\n }),\n })\n }\n\n // DONT DELETE THE COMMENTED LINES - ARE NECESSARY FOR F***ING ZERODEV DEBUGGING\n\n // this.logger.info(`Encoded multicall - ${JSON.stringify(encodedCalls, jsonReplacer)}`)\n // const code = await this.client.public.getCode({ address: from.address })\n // const isDeployed = code !== undefined && code !== '0x'\n // this.logger.info(`++++++ Smart account ${from.address} deployment status: ${isDeployed ? 'DEPLOYED' : 'NOT DEPLOYED'}`)\n\n // // Log account details\n // this.logger.info(`Account type: ${from.type}`)\n // this.logger.info(`Account address: ${from.address}`)\n\n // // Log the calls being made\n // this.logger.info(`Number of calls: ${encodedCalls.length}`)\n // encodedCalls.forEach((call, index) => {\n // this.logger.info(`Call ${index}: to=${call.to}, value=${call.value}, data=${call.data.slice(0, 10)}...`)\n // })\n\n await kernelClient.prepareUserOperation({\n callData: await kernelClient.account.encodeCalls(encodedCalls),\n })\n\n return true\n } catch (err) {\n this.logger.error(`Error details: ${JSON.stringify(err, null, 2)}`)\n if (err instanceof BaseError) {\n const revertError = err.walk((e) => e instanceof ContractFunctionRevertedError)\n if (revertError) {\n this.logger.error(`Revert error: ${String(revertError)}`)\n }\n }\n throw new ContractSimulationError(`Error Simulating Multicalls - ${err}`)\n }\n }\n\n private getOrCreatePaymaster() {\n if (!this._zeroDevPaymaster) {\n this._zeroDevPaymaster = createZeroDevPaymasterClient({\n chain: getChain(this.config.chainId),\n transport: http(this.getPaymasterRPC()),\n })\n }\n return this._zeroDevPaymaster\n }\n\n /**\n * Builds the `paymaster` partial for `createKernelAccountClient`. In relayer\n * mode (e.g. local `ultra-relay` for tests) returns an empty object so the\n * kernel client submits UserOps without paymaster fields and the bundler\n * pays gas via its executor key. In production returns the ZeroDev paymaster\n * sponsorship callback.\n */\n private getPaymasterConfig() {\n if (isRelayerMode()) return {}\n const zerodevPaymaster = this.getOrCreatePaymaster()\n return {\n paymaster: {\n getPaymasterData: (userOperation: any) =>\n zerodevPaymaster.sponsorUserOperation({\n userOperation: applyTempoVerificationGasFloor(userOperation, this.config.chainId),\n }),\n },\n }\n }\n\n protected getBundlerRPC(): string {\n // In relayer mode `getBundlerRpcUrl` reads `BUNDLER_RPC_URL_OVERRIDE`\n // and never touches the project id, so an empty value is harmless. In\n // production callers must pass a project id — surface a clear error if\n // the SDK was instantiated without one and we need it.\n const projectId = this.config.zeroDevProjectId\n if (!projectId && !isRelayerMode()) {\n throw new ContractsError(\n 'getBundlerRPC: zeroDevProjectId is required for non-relayer (production) mode',\n )\n }\n return getBundlerRpcUrl(projectId ?? '', this.config.chainId, this.config.useUltraRelay)\n }\n\n private getPaymasterRPC(): string {\n // Only ever consulted when `getPaymasterConfig` decides to attach a\n // paymaster, which is gated on `!isRelayerMode()`. A missing project\n // id at this point is a configuration bug worth surfacing.\n const projectId = this.config.zeroDevProjectId\n if (!projectId) {\n throw new ContractsError(\n 'getPaymasterRPC: zeroDevProjectId is required to build the paymaster URL',\n )\n }\n return getPaymasterRpcUrl(projectId, this.config.chainId)\n }\n}\n"],"names":["createKernelAccountClient","createZeroDevPaymasterClient","applyTempoVerificationGasFloor","estimateUserOperationFees","getBundlerRpcUrl","getPaymasterRpcUrl","isRelayerMode","BaseError","ContractFunctionRevertedError","encodeFunctionData","getContract","http","parseAbi","parseEventLogs","createBundlerClient","getUserOperationHash","ContractsError","ContractSimulationError","Instantiable","getInputsOfFunctionFormatted","getTransactionReceipt","getRandomBigInt","getChain","GAS_SANITY_THRESHOLD","GAS_FALLBACK_CAP","ZERODEV_NONCE_KEY_BITS","USEROP_RECEIPT_TIMEOUT_MS","capForBogusEstimate","estimatedGas","logger","warn","ContractBase","contractName","address","_zeroDevPaymaster","init","config","contractConfig","setInstanceConfig","contract","abi","client","public","publicClient","wallet","walletClient","call","functionName","args","from","readContract","account","err","txHash","hash","receipt","transactionHash","Error","getTransactionLogs","txReceipt","eventName","logs","strict","multicall","calls","params","type","debug","localAccountMulticall","progress","internalMulticallSmartAccount","simulateMulticall","localAccountSimulateMulticall","internalSimulateMulticallSmartAccount","simulate","localAccountSimulate","internalSimulateSmartAccount","send","localAccountSend","internalSendSmartAccount","getUserOperationReceipt","bundlerClient","chain","chainId","transport","getBundlerRPC","message","String","test","safeMessage","replace","txparams","stage","method","contractAddress","kernelClient","bundlerTransport","getPaymasterConfig","userOperation","estimateFeesPerGas","encodedCalls","map","push","to","value","data","userOpHash","nonce","getNonce","key","sendUserOperation","callData","encodeCalls","waitForUserOperationReceipt","timeout","assertUserOpSucceeded","revertError","walk","error","hashSuffix","success","reason","name","functionInputs","gasLimit","simulateContract","preparedUserOp","preparedHash","prepareUserOperation","entryPointAddress","entryPoint","entryPointVersion","version","prepErr","undefined","signature","_contractAbi","_contractAddress","_contractName","request","resolvedGas","estimate","estimateContractGas","estErr","writeContract","gas","receipts","length","pop","results","simulateCalls","JSON","stringify","e","getOrCreatePaymaster","getPaymasterRPC","zerodevPaymaster","paymaster","getPaymasterData","sponsorUserOperation","projectId","zeroDevProjectId","useUltraRelay"],"mappings":"AAAA,SAASA,yBAAyB,EAAEC,4BAA4B,QAAQ,eAAc;AACtF,SACEC,8BAA8B,EAC9BC,yBAAyB,EACzBC,gBAAgB,EAChBC,kBAAkB,EAClBC,aAAa,QACR,6CAA4C;AACnD,SAIEC,SAAS,EACTC,6BAA6B,EAC7BC,kBAAkB,EAClBC,WAAW,EACXC,IAAI,EACJC,QAAQ,EACRC,cAAc,QAET,OAAM;AACb,SACEC,mBAAmB,EACnBC,oBAAoB,QAGf,2BAA0B;AACjC,SAASC,cAAc,EAAEC,uBAAuB,QAAQ,qBAAoB;AAC5E,SAASC,YAAY,QAA4B,8BAA6B;AAE9E,SAASC,4BAA4B,EAAEC,qBAAqB,QAAQ,yBAAwB;AAC5F,SAASC,eAAe,QAAQ,sBAAqB;AACrD,SAASC,QAAQ,QAAQ,sBAAqB;AAU9C;;;;;;;;;;;;CAYC,GACD,MAAMC,uBAAuB,WAAW;AACxC,MAAMC,mBAAmB,UAAU;AAEnC,2FAA2F;AAC3F,uFAAuF;AACvF,qFAAqF;AACrF,qFAAqF;AACrF,MAAMC,yBAAyB;AAE/B,yFAAyF;AACzF,yFAAyF;AACzF,yFAAyF;AACzF,0EAA0E;AAC1E,MAAMC,4BAA4B;AAElC,SAASC,oBACPC,YAAoB,EACpBC,MAAuC;IAEvC,IAAID,eAAeL,sBAAsB,OAAOK;IAChDC,OAAOC,IAAI,CACT,CAAC,eAAe,EAAEF,aAAa,2BAA2B,CAAC,GACzD,CAAC,CAAC,EAAEL,qBAAqB,mBAAmB,EAAEC,iBAAiB,oCAAoC,CAAC;IAExG,OAAOA;AACT;AAUA,OAAO,MAAeO,qBAAqBb;IAMzC,YAAYc,YAAoB,EAAEC,OAAgB,CAAE;QAClD,KAAK,SAHCC,oBAA4E;QAIlF,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M,cAAc,
|
|
1
|
+
{"version":3,"file":"Logger.d.ts","sourceRoot":"","sources":["../../src/models/Logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,MAAM,IAAI,UAAU,EAAE,MAAM,MAAM,CAAA;AAEjD,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAA;AAEzF,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,EAAE,QAAQ,CAAA;IAChB,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAID,eAAO,MAAM,YAAY,GAAI,SAAQ,YAAiB,+BAgBrD,CAAA;AAED,eAAO,MAAM,cAAc,kBAW1B,CAAA"}
|
package/dist/models/Logger.js
CHANGED
|
@@ -16,9 +16,12 @@ export const createLogger = (config = {})=>{
|
|
|
16
16
|
};
|
|
17
17
|
export const LoggerInstance = ()=>{
|
|
18
18
|
if (!loggerInstance) {
|
|
19
|
+
// pretty:false → no pino-pretty transport, which is not bundle-safe and
|
|
20
|
+
// crashed the bundled apps/api (PR #2279). Keep it off so a stray core-kit
|
|
21
|
+
// log can never take down the API again.
|
|
19
22
|
loggerInstance = createLogger({
|
|
20
23
|
level: 'debug',
|
|
21
|
-
pretty:
|
|
24
|
+
pretty: false
|
|
22
25
|
});
|
|
23
26
|
}
|
|
24
27
|
return loggerInstance;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/models/Logger.ts"],"sourcesContent":["import { pino, Logger as PinoLogger } from 'pino'\n\nexport type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'\n\nexport interface LoggerConfig {\n level?: LogLevel\n pretty?: boolean\n}\n\nlet loggerInstance: PinoLogger | undefined\n\nexport const createLogger = (config: LoggerConfig = {}) => {\n const { level = 'info', pretty = false } = config\n\n return pino({\n level,\n transport: pretty\n ? {\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss',\n ignore: 'pid,hostname',\n },\n }\n : undefined,\n })\n}\n\nexport const LoggerInstance = () => {\n if (!loggerInstance) {\n loggerInstance = createLogger({\n level: 'debug',\n pretty:
|
|
1
|
+
{"version":3,"sources":["../../src/models/Logger.ts"],"sourcesContent":["import { pino, Logger as PinoLogger } from 'pino'\n\nexport type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'\n\nexport interface LoggerConfig {\n level?: LogLevel\n pretty?: boolean\n}\n\nlet loggerInstance: PinoLogger | undefined\n\nexport const createLogger = (config: LoggerConfig = {}) => {\n const { level = 'info', pretty = false } = config\n\n return pino({\n level,\n transport: pretty\n ? {\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'HH:MM:ss',\n ignore: 'pid,hostname',\n },\n }\n : undefined,\n })\n}\n\nexport const LoggerInstance = () => {\n if (!loggerInstance) {\n // pretty:false → no pino-pretty transport, which is not bundle-safe and\n // crashed the bundled apps/api (PR #2279). Keep it off so a stray core-kit\n // log can never take down the API again.\n loggerInstance = createLogger({\n level: 'debug',\n pretty: false,\n })\n }\n return loggerInstance\n}\n"],"names":["pino","loggerInstance","createLogger","config","level","pretty","transport","target","options","colorize","translateTime","ignore","undefined","LoggerInstance"],"mappings":"AAAA,SAASA,IAAI,QAA8B,OAAM;AASjD,IAAIC;AAEJ,OAAO,MAAMC,eAAe,CAACC,SAAuB,CAAC,CAAC;IACpD,MAAM,EAAEC,QAAQ,MAAM,EAAEC,SAAS,KAAK,EAAE,GAAGF;IAE3C,OAAOH,KAAK;QACVI;QACAE,WAAWD,SACP;YACEE,QAAQ;YACRC,SAAS;gBACPC,UAAU;gBACVC,eAAe;gBACfC,QAAQ;YACV;QACF,IACAC;IACN;AACF,EAAC;AAED,OAAO,MAAMC,iBAAiB;IAC5B,IAAI,CAACZ,gBAAgB;QACnB,wEAAwE;QACxE,2EAA2E;QAC3E,yCAAyC;QACzCA,iBAAiBC,aAAa;YAC5BE,OAAO;YACPC,QAAQ;QACV;IACF;IACA,OAAOJ;AACT,EAAC"}
|
|
@@ -7,6 +7,14 @@ export interface NeverminedOptions {
|
|
|
7
7
|
* It's possible to use a public available provider or a private/paid one like Infura, Alchemy, etc.
|
|
8
8
|
*/
|
|
9
9
|
web3ProviderUri?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Optional secondary Web3 Provider URL used as an automatic failover (#2206).
|
|
12
|
+
* When set, the SDK wraps both endpoints in a viem `fallback()` transport so a
|
|
13
|
+
* primary-endpoint outage transparently falls over to this one — no restart.
|
|
14
|
+
* Prefer a DIFFERENT provider than the primary for real outage coverage. When
|
|
15
|
+
* unset, behaviour is identical to a single-endpoint client.
|
|
16
|
+
*/
|
|
17
|
+
web3ProviderUriFallback?: string;
|
|
10
18
|
/**
|
|
11
19
|
* The Nevermined App URL.
|
|
12
20
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NeverminedOptions.d.ts","sourceRoot":"","sources":["../../src/models/NeverminedOptions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAE9B,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAA;IACf;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IAExB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IAEjB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IAEpB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B"}
|
|
1
|
+
{"version":3,"file":"NeverminedOptions.d.ts","sourceRoot":"","sources":["../../src/models/NeverminedOptions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAE9B,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAA;IACf;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IAExB;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAEhC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IAEjB,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAA;IAEpB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAEzB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IAEvB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/models/NeverminedOptions.ts"],"sourcesContent":["import { Account } from 'viem'\n\nexport interface NeverminedOptions {\n chainId: number\n /**\n * Ethereum Web3 Provider URL. This Url allows the SDK to connect to a blockchain.\n * This provider depends on the network where you want to connect (Ethereum Mainnet, Rinkeby, Polygon Matic, etc).\n * It's possible to use a public available provider or a private/paid one like Infura, Alchemy, etc.\n */\n web3ProviderUri?: string\n\n /**\n * The Nevermined App URL.\n */\n appUrl?: string\n\n backendUrl?: string\n\n agentsProxy?: string\n\n /**\n * Log level. Defaults to `'info'` when consumed by `Instantiable.abstract.ts`.\n */\n logLevel?: string\n\n accounts?: Account[]\n\n /**\n * ZeroDev project id\n */\n zeroDevProjectId?: string\n\n /**\n * Route the production bundler through ZeroDev's UltraRelay\n * (`?provider=ULTRA_RELAY`). No effect when `BUNDLER_RPC_URL_OVERRIDE` is set.\n */\n useUltraRelay?: boolean\n\n /**\n * Contracts version\n */\n contractsVersion?: string\n}\n"],"names":[],"mappings":"AAEA,
|
|
1
|
+
{"version":3,"sources":["../../src/models/NeverminedOptions.ts"],"sourcesContent":["import { Account } from 'viem'\n\nexport interface NeverminedOptions {\n chainId: number\n /**\n * Ethereum Web3 Provider URL. This Url allows the SDK to connect to a blockchain.\n * This provider depends on the network where you want to connect (Ethereum Mainnet, Rinkeby, Polygon Matic, etc).\n * It's possible to use a public available provider or a private/paid one like Infura, Alchemy, etc.\n */\n web3ProviderUri?: string\n\n /**\n * Optional secondary Web3 Provider URL used as an automatic failover (#2206).\n * When set, the SDK wraps both endpoints in a viem `fallback()` transport so a\n * primary-endpoint outage transparently falls over to this one — no restart.\n * Prefer a DIFFERENT provider than the primary for real outage coverage. When\n * unset, behaviour is identical to a single-endpoint client.\n */\n web3ProviderUriFallback?: string\n\n /**\n * The Nevermined App URL.\n */\n appUrl?: string\n\n backendUrl?: string\n\n agentsProxy?: string\n\n /**\n * Log level. Defaults to `'info'` when consumed by `Instantiable.abstract.ts`.\n */\n logLevel?: string\n\n accounts?: Account[]\n\n /**\n * ZeroDev project id\n */\n zeroDevProjectId?: string\n\n /**\n * Route the production bundler through ZeroDev's UltraRelay\n * (`?provider=ULTRA_RELAY`). No effect when `BUNDLER_RPC_URL_OVERRIDE` is set.\n */\n useUltraRelay?: boolean\n\n /**\n * Contracts version\n */\n contractsVersion?: string\n}\n"],"names":[],"mappings":"AAEA,WAiDC"}
|
|
@@ -20,9 +20,17 @@ export declare class NvmApiKey implements JWTPayload {
|
|
|
20
20
|
*/
|
|
21
21
|
ver: string;
|
|
22
22
|
/**
|
|
23
|
-
* The ZeroDev session key
|
|
23
|
+
* The ZeroDev session key (primary network). Kept for back-compat and as the
|
|
24
|
+
* fallback when `zsks` has no entry for the requested network.
|
|
24
25
|
*/
|
|
25
26
|
zsk?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Per-network ZeroDev session keys (#1929), keyed by chainId. Each carries
|
|
29
|
+
* that network's chain-bound enable signature, so a single API key works on
|
|
30
|
+
* every supported network. The backend selects the entry for the operation's
|
|
31
|
+
* chain; absent → fall back to `zsk`.
|
|
32
|
+
*/
|
|
33
|
+
zsks?: Record<string, string>;
|
|
26
34
|
/**
|
|
27
35
|
* The Marketplace auth token
|
|
28
36
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NvmApiKey.d.ts","sourceRoot":"","sources":["../../src/models/NvmApiKey.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAa,MAAM,MAAM,CAAA;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC9B,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAIvD,OAAO,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAA;AAGtE,qBAAa,SAAU,YAAW,UAAU;IAC1C;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;OAEG;IACH,GAAG,SAAO;IAEV
|
|
1
|
+
{"version":3,"file":"NvmApiKey.d.ts","sourceRoot":"","sources":["../../src/models/NvmApiKey.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAa,MAAM,MAAM,CAAA;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAC9B,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAIvD,OAAO,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAA;AAGtE,qBAAa,SAAU,YAAW,UAAU;IAC1C;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;OAEG;I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AAM,GAAG,SAAS;IAKnD;;;;OAIG;WACW,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS;IAIjD;;;OAGG;IACI,SAAS,IAAI,MAAM;IAI1B;;;OAGG;IACI,QAAQ,IAAI,MAAM;IAIzB;;;;OAIG;WACW,SAAS,CAAC,GAAG,EAAE,MAAM;IAInC;;;OAGG;IACI,IAAI;IAIX;;;;OAIG;IACH,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,MAAM;CAG/B"}
|
package/dist/models/NvmApiKey.js
CHANGED
|
@@ -76,6 +76,12 @@ export class NvmApiKey {
|
|
|
76
76
|
if (now.getTime() > Number(this.exp) * 1000) return false;
|
|
77
77
|
}
|
|
78
78
|
if (chainId !== 0) {
|
|
79
|
+
// #1929: a multi-network key's real per-network validity lives in `zsks`
|
|
80
|
+
// (keyed by chainId); `aud` is only the primary-network hint. Consult
|
|
81
|
+
// `zsks` first — otherwise `isValid(secondaryChain)` wrongly returns false
|
|
82
|
+
// for a valid key (e.g. aud=8453, zsks={8453,4217} → isValid(4217)). Fall
|
|
83
|
+
// back to the `aud` check for legacy single-network keys.
|
|
84
|
+
if (this.zsks?.[String(chainId)]) return true;
|
|
79
85
|
if (Number(this.aud) !== chainId) return false;
|
|
80
86
|
}
|
|
81
87
|
return true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/models/NvmApiKey.ts"],"sourcesContent":["import { JWTPayload, decodeJwt } from 'jose'\nimport { Account } from 'viem'\nimport { SmartAccount } from 'viem/account-abstraction'\nimport { bytesToHex } from 'viem/utils'\nimport { getChecksumAddress } from '../nevermined/utils/BlockchainViemUtils.js'\nimport { EthSignJWT } from '../nevermined/utils/JwtUtils.js'\nimport { SignatureUtils } from '../nevermined/utils/SignatureUtils.js'\nimport { decryptMessage, encryptMessage, urlSafeBase64Decode } from '../utils/helpers.js'\n\nexport class NvmApiKey implements JWTPayload {\n /**\n * The public address of the account issuing the key.\n */\n iss?: string\n\n /**\n * The chain id of the network the key is valid for. If zero the key is not having any network limitation\n */\n aud?: string\n\n /**\n * The public address of the account the key is issued for.\n */\n sub?: string\n\n /**\n * The version of the key\n */\n ver = 'v1'\n\n /**\n * The ZeroDev session key\n */\n zsk?: string\n\n /**\n * The Marketplace auth token\n */\n // nvt?: string\n\n /**\n * JWT Expiration Time\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4}\n */\n exp?: number\n\n /**\n * JWT Issued At\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6}\n */\n iat?: number;\n\n /**\n * Additional attributes\n */\n [propName: string]: any\n\n /**\n * It generates a new serialized and encrypted NvmApiKey including the ZeroDev session key and the Marketplace auth token.\n * The string representing this key can be used to authenticate against the Nevermined API.\n * @param signatureUtils The SignatureUtils instance\n * @param issuerAccount The account issuing the key\n * @param zeroDevSessionKey The ZeroDev session key\n * @param receiverAddress The address of the account the key is issued for\n * @param receiverPublicKey The public key of the account the key is issued for\n * @param chainId The chain id of the network the key is valid for\n * @param additionalParams Addintional params to be added to the Key generated\n * @returns The encrypted string representing the @see {@link NvmApiKey}\n */\n public static async generate(\n signatureUtils: SignatureUtils,\n issuerAccount: Account | SmartAccount,\n zeroDevSessionKey: string | undefined,\n receiverAddress: string,\n receiverPublicKey: string,\n expirationTime: number | string = '1y',\n additionalParams = {},\n nvmApiKeyVersion = 'v1',\n ): Promise<string> {\n const issuerAddress = getChecksumAddress(issuerAccount.address)\n const chainId = signatureUtils.client.chain?.id || 0\n const sub = getChecksumAddress(receiverAddress)\n\n const eip712Data = {\n message: 'Sign this message to generate the Encrypted Nevermined API Key',\n ...(chainId > 0 && { chainId }),\n }\n const params = {\n iss: issuerAddress,\n aud: chainId.toString(),\n sub,\n ver: nvmApiKeyVersion,\n zsk: zeroDevSessionKey,\n eip712Data,\n ...additionalParams,\n }\n\n const signedJWT = await new EthSignJWT(params)\n .setProtectedHeader({ alg: 'ES256K' })\n .setIssuedAt()\n .setExpirationTime(expirationTime)\n .ethSign(signatureUtils, issuerAccount)\n\n return encryptMessage(signedJWT, receiverPublicKey)\n }\n\n /**\n * Given an encrypted JWT and a private key, it decrypts and decodes the JWT into a NvmApiKey\n * @param encryptedJwt The encrypted JWT\n * @param privateKey The private key representing the account\n * @returns The @see {@link NvmApiKey}\n */\n public static async decryptAndDecode(encryptedJwt: string, privateKey: string) {\n const decrypted = await decryptMessage(encryptedJwt, privateKey)\n return NvmApiKey.fromJWT(decrypted)\n }\n\n /**\n * Given a signed JWT, it recovers the signer address\n * @param jwtString The signed JWT\n * @returns The signer address\n */\n public static async getSignerAddress(jwtString: string): Promise<string> {\n try {\n const tokens = jwtString.split('.')\n const signature = bytesToHex(urlSafeBase64Decode(tokens[2]))\n return SignatureUtils.recoverSignerAddress(`${tokens[0]}.${tokens[1]}`, signature)\n } catch (e) {\n if (e instanceof Error) {\n throw new Error(`Error recovering signer address: ${e.message}`)\n } else {\n throw new Error(`Error recovering signer address`)\n }\n }\n }\n\n /**\n * It checks if the NVM API Key attributes are valid\n * @param chainId The chain id of the network the key is valid for\n * @returns true if the key is valid, false otherwise\n */\n public isValid(chainId = 0): boolean {\n if (this.exp) {\n const now = new Date()\n if (now.getTime() > Number(this.exp) * 1000) return false\n }\n if (chainId !== 0) {\n if (Number(this.aud) !== chainId) return false\n }\n return true\n }\n\n /**\n * It generates a signed JWT from the NvmApiKey\n * @param signatureUtils The SignatureUtils instance\n * @param issuerAccount The account issuing the key\n * @returns the string in JWT format represeting the NvmApiKey\n */\n public async toJWT(\n signatureUtils: SignatureUtils,\n issuerAccount: Account | SmartAccount,\n ): Promise<string> {\n const params: Record<string, any> = {}\n Object.keys(this)\n .filter((val) => val !== undefined)\n .forEach((key) => {\n if (!key.startsWith('_')) params[key] = this[key]\n })\n\n const jwt = new EthSignJWT(params).setProtectedHeader({ alg: 'ES256K' }).setIssuedAt(this.iat)\n if (this.exp) jwt.setExpirationTime(this.exp)\n return jwt.ethSign(signatureUtils, issuerAccount)\n }\n\n /**\n * It generates the hash in JWT format of the NvmApiKey\n * @param signatureUtils the SignatureUtils instance\n * @param issuerAccount the account issuing the key\n * @returns a JWT string representing the hash of the NvmApiKey\n */\n public async hashJWT(\n signatureUtils: SignatureUtils,\n issuerAccount: Account | SmartAccount,\n heliconeApiKey?: string,\n ): Promise<string> {\n const issuerAddress = getChecksumAddress(issuerAccount.address)\n\n return (\n new EthSignJWT({\n iss: issuerAddress, // the account generating the hash (node/provider, etc) is the issuer of the hash\n sub: this.iss, // the issuer of the NVMApiKey (the user) is the subject of the hash\n jti: this.hash(),\n exp: this.exp,\n o11y: heliconeApiKey,\n })\n .setProtectedHeader({ alg: 'ES256K' })\n // .setIssuedAt() // WARNING: If enabled, the hash will change for the same NvmApiKey\n .ethSign(signatureUtils, issuerAccount)\n )\n }\n\n /**\n * It regenerates the NvmApiKey from a JSON object\n * @param jwt JWTPayload in JSON format\n * @returns the @see {@link NvmApiKey}\n */\n public static fromJSON(jwt: JWTPayload): NvmApiKey {\n const nvmKey = new NvmApiKey()\n const str = JSON.stringify(jwt)\n const _obj = JSON.parse(str)\n Object.keys(_obj)\n .filter((val) => val !== undefined)\n .forEach((key) => {\n nvmKey[key] = _obj[key]\n })\n return nvmKey\n }\n\n /**\n * It regenerates the NvmApiKey from a JWT\n * @param jwtString the string in JWT format represeting the NvmApiKey\n * @returns the @see {@link NvmApiKey}\n */\n public static fromJWT(jwtString: string): NvmApiKey {\n const jwt = NvmApiKey.decodeJWT(jwtString)\n return NvmApiKey.fromJSON(jwt)\n }\n\n /**\n * It regenerates the NvmApiKey from a string\n * @param str the string represeting the NvmApiKey\n * @returns the @see {@link NvmApiKey}\n */\n public static deserialize(str: string): NvmApiKey {\n return NvmApiKey.fromJSON(JSON.parse(str))\n }\n\n /**\n * It serializes the NVM Api Key into a string\n * @returns a string representing the NVM API Key\n */\n public serialize(): string {\n return this.toString()\n }\n\n /**\n * It serializes the NVM Api Key into a string\n * @returns a string representing the NVM API Key\n */\n public toString(): string {\n return JSON.stringify(this)\n }\n\n /**\n * It decodes a string JWT into a JWTPayload\n * @param str jwt string\n * @returns the JWTPayload\n */\n public static decodeJWT(str: string) {\n return decodeJwt(str)\n }\n\n /**\n * It generates the hash of the NvmApiKey\n * @returns a string representing the hash of the NvmApiKey\n */\n public hash() {\n return SignatureUtils.hash(this.serialize())\n }\n\n /**\n * Given a serialized string, it generates the hash\n * @param serialized the serialized string\n * @returns the hash\n */\n static hash(serialized: string) {\n return SignatureUtils.hash(serialized)\n }\n}\n"],"names":["decodeJwt","bytesToHex","getChecksumAddress","EthSignJWT","SignatureUtils","decryptMessage","encryptMessage","urlSafeBase64Decode","NvmApiKey","generate","signatureUtils","issuerAccount","zeroDevSessionKey","receiverAddress","receiverPublicKey","expirationTime","additionalParams","nvmApiKeyVersion","issuerAddress","address","chainId","client","chain","id","sub","eip712Data","message","params","iss","aud","toString","ver","zsk","signedJWT","setProtectedHeader","alg","setIssuedAt","setExpirationTime","ethSign","decryptAndDecode","encryptedJwt","privateKey","decrypted","fromJWT","getSignerAddress","jwtString","tokens","split","signature","recoverSignerAddress","e","Error","isValid","exp","now","Date","getTime","Number","toJWT","Object","keys","filter","val","undefined","forEach","key","startsWith","jwt","iat","hashJWT","heliconeApiKey","jti","hash","o11y","fromJSON","nvmKey","str","JSON","stringify","_obj","parse","decodeJWT","deserialize","serialize","serialized"],"mappings":"AAAA,SAAqBA,SAAS,QAAQ,OAAM;AAG5C,SAASC,UAAU,QAAQ,aAAY;AACvC,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,UAAU,QAAQ,kCAAiC;AAC5D,SAASC,cAAc,QAAQ,wCAAuC;AACtE,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,QAAQ,sBAAqB;AAEzF,OAAO,MAAMC;IAkDX;;;;;;;;;;;GAWC,GACD,aAAoBC,SAClBC,cAA8B,EAC9BC,aAAqC,EACrCC,iBAAqC,EACrCC,e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BC;IAE/B;IAEA;;;;GAIC,GACD,OAAc+D,SAASP,GAAe,EAAa;QACjD,MAAMQ,SAAS,IAAInE;QACnB,MAAMoE,MAAMC,KAAKC,SAAS,CAACX;QAC3B,MAAMY,OAAOF,KAAKG,KAAK,CAACJ;QACxBjB,OAAOC,IAAI,CAACmB,MACTlB,MAAM,CAAC,CAACC,MAAQA,QAAQC,WACxBC,OAAO,CAAC,CAACC;YACRU,MAAM,CAACV,IAAI,GAAGc,IAAI,CAACd,IAAI;QACzB;QACF,OAAOU;IACT;IAEA;;;;GAIC,GACD,OAAchC,QAAQE,SAAiB,EAAa;QAClD,MAAMsB,MAAM3D,UAAUyE,SAAS,CAACpC;QAChC,OAAOrC,UAAUkE,QAAQ,CAACP;IAC5B;IAEA;;;;GAIC,GACD,OAAce,YAAYN,GAAW,EAAa;QAChD,OAAOpE,UAAUkE,QAAQ,CAACG,KAAKG,KAAK,CAACJ;IACvC;IAEA;;;GAGC,GACD,AAAOO,YAAoB;QACzB,OAAO,IAAI,CAACrD,QAAQ;IACtB;IAEA;;;GAGC,GACD,AAAOA,WAAmB;QACxB,OAAO+C,KAAKC,SAAS,CAAC,IAAI;IAC5B;IAEA;;;;GAIC,GACD,OAAcG,UAAUL,GAAW,EAAE;QACnC,OAAO5E,UAAU4E;IACnB;IAEA;;;GAGC,GACD,AAAOJ,OAAO;QACZ,OAAOpE,eAAeoE,IAAI,CAAC,IAAI,CAACW,SAAS;IAC3C;IAEA;;;;GAIC,GACD,OAAOX,KAAKY,UAAkB,EAAE;QAC9B,OAAOhF,eAAeoE,IAAI,CAACY;IAC7B;;QA9PA;;GAEC,QACDrD,MAAM;;AA4PR"}
|
|
1
|
+
{"version":3,"sources":["../../src/models/NvmApiKey.ts"],"sourcesContent":["import { JWTPayload, decodeJwt } from 'jose'\nimport { Account } from 'viem'\nimport { SmartAccount } from 'viem/account-abstraction'\nimport { bytesToHex } from 'viem/utils'\nimport { getChecksumAddress } from '../nevermined/utils/BlockchainViemUtils.js'\nimport { EthSignJWT } from '../nevermined/utils/JwtUtils.js'\nimport { SignatureUtils } from '../nevermined/utils/SignatureUtils.js'\nimport { decryptMessage, encryptMessage, urlSafeBase64Decode } from '../utils/helpers.js'\n\nexport class NvmApiKey implements JWTPayload {\n /**\n * The public address of the account issuing the key.\n */\n iss?: string\n\n /**\n * The chain id of the network the key is valid for. If zero the key is not having any network limitation\n */\n aud?: string\n\n /**\n * The public address of the account the key is issued for.\n */\n sub?: string\n\n /**\n * The version of the key\n */\n ver = 'v1'\n\n /**\n * The ZeroDev session key (primary network). Kept for back-compat and as the\n * fallback when `zsks` has no entry for the requested network.\n */\n zsk?: string\n\n /**\n * Per-network ZeroDev session keys (#1929), keyed by chainId. Each carries\n * that network's chain-bound enable signature, so a single API key works on\n * every supported network. The backend selects the entry for the operation's\n * chain; absent → fall back to `zsk`.\n */\n zsks?: Record<string, string>\n\n /**\n * The Marketplace auth token\n */\n // nvt?: string\n\n /**\n * JWT Expiration Time\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4}\n */\n exp?: number\n\n /**\n * JWT Issued At\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6}\n */\n iat?: number;\n\n /**\n * Additional attributes\n */\n [propName: string]: any\n\n /**\n * It generates a new serialized and encrypted NvmApiKey including the ZeroDev session key and the Marketplace auth token.\n * The string representing this key can be used to authenticate against the Nevermined API.\n * @param signatureUtils The SignatureUtils instance\n * @param issuerAccount The account issuing the key\n * @param zeroDevSessionKey The ZeroDev session key\n * @param receiverAddress The address of the account the key is issued for\n * @param receiverPublicKey The public key of the account the key is issued for\n * @param chainId The chain id of the network the key is valid for\n * @param additionalParams Addintional params to be added to the Key generated\n * @returns The encrypted string representing the @see {@link NvmApiKey}\n */\n public static async generate(\n signatureUtils: SignatureUtils,\n issuerAccount: Account | SmartAccount,\n zeroDevSessionKey: string | undefined,\n receiverAddress: string,\n receiverPublicKey: string,\n expirationTime: number | string = '1y',\n additionalParams = {},\n nvmApiKeyVersion = 'v1',\n ): Promise<string> {\n const issuerAddress = getChecksumAddress(issuerAccount.address)\n const chainId = signatureUtils.client.chain?.id || 0\n const sub = getChecksumAddress(receiverAddress)\n\n const eip712Data = {\n message: 'Sign this message to generate the Encrypted Nevermined API Key',\n ...(chainId > 0 && { chainId }),\n }\n const params = {\n iss: issuerAddress,\n aud: chainId.toString(),\n sub,\n ver: nvmApiKeyVersion,\n zsk: zeroDevSessionKey,\n eip712Data,\n ...additionalParams,\n }\n\n const signedJWT = await new EthSignJWT(params)\n .setProtectedHeader({ alg: 'ES256K' })\n .setIssuedAt()\n .setExpirationTime(expirationTime)\n .ethSign(signatureUtils, issuerAccount)\n\n return encryptMessage(signedJWT, receiverPublicKey)\n }\n\n /**\n * Given an encrypted JWT and a private key, it decrypts and decodes the JWT into a NvmApiKey\n * @param encryptedJwt The encrypted JWT\n * @param privateKey The private key representing the account\n * @returns The @see {@link NvmApiKey}\n */\n public static async decryptAndDecode(encryptedJwt: string, privateKey: string) {\n const decrypted = await decryptMessage(encryptedJwt, privateKey)\n return NvmApiKey.fromJWT(decrypted)\n }\n\n /**\n * Given a signed JWT, it recovers the signer address\n * @param jwtString The signed JWT\n * @returns The signer address\n */\n public static async getSignerAddress(jwtString: string): Promise<string> {\n try {\n const tokens = jwtString.split('.')\n const signature = bytesToHex(urlSafeBase64Decode(tokens[2]))\n return SignatureUtils.recoverSignerAddress(`${tokens[0]}.${tokens[1]}`, signature)\n } catch (e) {\n if (e instanceof Error) {\n throw new Error(`Error recovering signer address: ${e.message}`)\n } else {\n throw new Error(`Error recovering signer address`)\n }\n }\n }\n\n /**\n * It checks if the NVM API Key attributes are valid\n * @param chainId The chain id of the network the key is valid for\n * @returns true if the key is valid, false otherwise\n */\n public isValid(chainId = 0): boolean {\n if (this.exp) {\n const now = new Date()\n if (now.getTime() > Number(this.exp) * 1000) return false\n }\n if (chainId !== 0) {\n // #1929: a multi-network key's real per-network validity lives in `zsks`\n // (keyed by chainId); `aud` is only the primary-network hint. Consult\n // `zsks` first — otherwise `isValid(secondaryChain)` wrongly returns false\n // for a valid key (e.g. aud=8453, zsks={8453,4217} → isValid(4217)). Fall\n // back to the `aud` check for legacy single-network keys.\n if (this.zsks?.[String(chainId)]) return true\n if (Number(this.aud) !== chainId) return false\n }\n return true\n }\n\n /**\n * It generates a signed JWT from the NvmApiKey\n * @param signatureUtils The SignatureUtils instance\n * @param issuerAccount The account issuing the key\n * @returns the string in JWT format represeting the NvmApiKey\n */\n public async toJWT(\n signatureUtils: SignatureUtils,\n issuerAccount: Account | SmartAccount,\n ): Promise<string> {\n const params: Record<string, any> = {}\n Object.keys(this)\n .filter((val) => val !== undefined)\n .forEach((key) => {\n if (!key.startsWith('_')) params[key] = this[key]\n })\n\n const jwt = new EthSignJWT(params).setProtectedHeader({ alg: 'ES256K' }).setIssuedAt(this.iat)\n if (this.exp) jwt.setExpirationTime(this.exp)\n return jwt.ethSign(signatureUtils, issuerAccount)\n }\n\n /**\n * It generates the hash in JWT format of the NvmApiKey\n * @param signatureUtils the SignatureUtils instance\n * @param issuerAccount the account issuing the key\n * @returns a JWT string representing the hash of the NvmApiKey\n */\n public async hashJWT(\n signatureUtils: SignatureUtils,\n issuerAccount: Account | SmartAccount,\n heliconeApiKey?: string,\n ): Promise<string> {\n const issuerAddress = getChecksumAddress(issuerAccount.address)\n\n return (\n new EthSignJWT({\n iss: issuerAddress, // the account generating the hash (node/provider, etc) is the issuer of the hash\n sub: this.iss, // the issuer of the NVMApiKey (the user) is the subject of the hash\n jti: this.hash(),\n exp: this.exp,\n o11y: heliconeApiKey,\n })\n .setProtectedHeader({ alg: 'ES256K' })\n // .setIssuedAt() // WARNING: If enabled, the hash will change for the same NvmApiKey\n .ethSign(signatureUtils, issuerAccount)\n )\n }\n\n /**\n * It regenerates the NvmApiKey from a JSON object\n * @param jwt JWTPayload in JSON format\n * @returns the @see {@link NvmApiKey}\n */\n public static fromJSON(jwt: JWTPayload): NvmApiKey {\n const nvmKey = new NvmApiKey()\n const str = JSON.stringify(jwt)\n const _obj = JSON.parse(str)\n Object.keys(_obj)\n .filter((val) => val !== undefined)\n .forEach((key) => {\n nvmKey[key] = _obj[key]\n })\n return nvmKey\n }\n\n /**\n * It regenerates the NvmApiKey from a JWT\n * @param jwtString the string in JWT format represeting the NvmApiKey\n * @returns the @see {@link NvmApiKey}\n */\n public static fromJWT(jwtString: string): NvmApiKey {\n const jwt = NvmApiKey.decodeJWT(jwtString)\n return NvmApiKey.fromJSON(jwt)\n }\n\n /**\n * It regenerates the NvmApiKey from a string\n * @param str the string represeting the NvmApiKey\n * @returns the @see {@link NvmApiKey}\n */\n public static deserialize(str: string): NvmApiKey {\n return NvmApiKey.fromJSON(JSON.parse(str))\n }\n\n /**\n * It serializes the NVM Api Key into a string\n * @returns a string representing the NVM API Key\n */\n public serialize(): string {\n return this.toString()\n }\n\n /**\n * It serializes the NVM Api Key into a string\n * @returns a string representing the NVM API Key\n */\n public toString(): string {\n return JSON.stringify(this)\n }\n\n /**\n * It decodes a string JWT into a JWTPayload\n * @param str jwt string\n * @returns the JWTPayload\n */\n public static decodeJWT(str: string) {\n return decodeJwt(str)\n }\n\n /**\n * It generates the hash of the NvmApiKey\n * @returns a string representing the hash of the NvmApiKey\n */\n public hash() {\n return SignatureUtils.hash(this.serialize())\n }\n\n /**\n * Given a serialized string, it generates the hash\n * @param serialized the serialized string\n * @returns the hash\n */\n static hash(serialized: string) {\n return SignatureUtils.hash(serialized)\n }\n}\n"],"names":["decodeJwt","bytesToHex","getChecksumAddress","EthSignJWT","SignatureUtils","decryptMessage","encryptMessage","urlSafeBase64Decode","NvmApiKey","generate","signatureUtils","issuerAccount","zeroDevSessionKey","receiverAddress","receiverPublicKey","expirationTime","additionalParams","nvmApiKeyVersion","issuerAddress","address","chainId","client","chain","id","sub","eip712Data","message","params","iss","aud","toString","ver","zsk","signedJWT","setProtectedHeader","alg","setIssuedAt","setExpirationTime","ethSign","decryptAndDecode","encryptedJwt","privateKey","decrypted","fromJWT","getSignerAddress","jwtString","tokens","split","signature","recoverSignerAddress","e","Error","isValid","exp","now","Date","getTime","Number","zsks","String","toJWT","Object","keys","filter","val","undefined","forEach","key","startsWith","jwt","iat","hashJWT","heliconeApiKey","jti","hash","o11y","fromJSON","nvmKey","str","JSON","stringify","_obj","parse","decodeJWT","deserialize","serialize","serialized"],"mappings":"AAAA,SAAqBA,SAAS,QAAQ,OAAM;AAG5C,SAASC,UAAU,QAAQ,aAAY;AACvC,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,UAAU,QAAQ,kCAAiC;AAC5D,SAASC,cAAc,QAAQ,wCAAuC;AACtE,SAASC,cAAc,EAAEC,cAAc,EAAEC,mBAAmB,QAAQ,sBAAqB;AAEzF,OAAO,MAAMC;IA2DX;;;;;;;;;;;GAWC,GACD,aAAoBC,SAClBC,cAA8B,EAC9BC,aAAqC,EACrCC,iBAAqC,EACrCC,eAAuB,EACvBC,iBAAyB,EACzBC,iBAAkC,IAAI,EACtCC,mBAAmB,CAAC,CAAC,EACrBC,mBAAmB,IAAI,EACN;QACjB,MAAMC,gBAAgBhB,mBAAmBS,cAAcQ,OAAO;QAC9D,MAAMC,UAAUV,eAAeW,MAAM,CAACC,KAAK,EAAEC,MAAM;QACnD,MAAMC,MAAMtB,mBAAmBW;QAE/B,MAAMY,aAAa;YACjBC,SAAS;YACT,GAAIN,UAAU,KAAK;gBAAEA;YAAQ,CAAC;QAChC;QACA,MAAMO,SAAS;YACbC,KAAKV;YACLW,KAAKT,QAAQU,QAAQ;YACrBN;YACAO,KAAKd;YACLe,KAAKpB;YACLa;YACA,GAAGT,gBAAgB;QACrB;QAEA,MAAMiB,YAAY,MAAM,IAAI9B,WAAWwB,QACpCO,kBAAkB,CAAC;YAAEC,KAAK;QAAS,GACnCC,WAAW,GACXC,iBAAiB,CAACtB,gBAClBuB,OAAO,CAAC5B,gBAAgBC;QAE3B,OAAOL,eA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