@nevermined-io/core-kit 1.9.0 → 1.11.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.
@@ -56,6 +56,17 @@ export declare class AssetRegistry extends ContractBase {
56
56
  planExists(id: bigint): Promise<boolean>;
57
57
  addPlanToAgent(planId: bigint, agentId: string | bigint, owner: Account | SmartAccount, txParams?: TxParameters): Promise<TransactionReceipt | UserOperationReceipt>;
58
58
  removePlanFromAgent(planId: bigint, agentId: string | bigint, owner: Account | SmartAccount, txParams?: TxParameters): Promise<TransactionReceipt | UserOperationReceipt>;
59
+ /**
60
+ * Move an agent's on-chain ownership. Only the CURRENT owner can call it.
61
+ *
62
+ * Used by the EIP-7702 migration healing path (#2152): a user's pre-migration
63
+ * agents stay owned by their Kernel v3.1 SCA while every new write is signed by
64
+ * their 7702 EOA, so the SCA hands the agent over before the EOA can operate on
65
+ * it. Deliberately NOT part of the session-key CallPolicy (`REGISTER_GROUP_FNS`)
66
+ * — it is signed by the SCA's sudo validator, and the merkle is already at its
67
+ * Tempo enable-gas ceiling (#1929).
68
+ */
69
+ transferAgentOwnership(agentId: string | bigint, newOwner: `0x${string}`, owner: Account | SmartAccount, txParams?: TxParameters): Promise<TransactionReceipt | UserOperationReceipt>;
59
70
  planConfigPreFilter(priceConfig: PriceConfig, creditsConfig: CreditsConfig, includeFees?: boolean, organizationCryptoFee?: bigint, organizationCryptoWallet?: string): Promise<{
60
71
  priceConfig: {
61
72
  isCrypto: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"AssetRegistry.d.ts","sourceRoot":"","sources":["../../src/contracts/AssetRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AACnF,OAAO,EAAE,OAAO,EAAE,OAAO,EAAa,kBAAkB,EAAe,MAAM,MAAM,CAAA;AACnF,OAAO,EAAE,YAAY,EAAE,oB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C,EAAE,MAAM,EAC9B,wBAAwB,CAAC,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IA+CtB,UAAU,CACrB,YAAY,EAAE,WAAW,EACzB,cAAc,EAAE,aAAa,EAC7B,KAAK,EAAE,OAAO,EACd,OAAO,UAAO,EACd,KAAK,SAAK,EACV,qBAAqB,CAAC,EAAE,MAAM,EAC9B,wBAAwB,CAAC,EAAE,MAAM,GAChC,OAAO,CAAC,MAAM,CAAC;IAsClB;;;;OAIG;IACU,yBAAyB,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC;IAOlF;;;;;;;OAOG;IACU,iCAAiC,CAC5C,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,GAC3B,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IAQhC;;;;;;OAMG;IACU,6BAA6B,CACxC,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,GAC3B,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;CAOjC"}
@@ -106,6 +106,21 @@ export class AssetRegistry extends ContractBase {
106
106
  planId
107
107
  ], txParams);
108
108
  }
109
+ /**
110
+ * Move an agent's on-chain ownership. Only the CURRENT owner can call it.
111
+ *
112
+ * Used by the EIP-7702 migration healing path (#2152): a user's pre-migration
113
+ * agents stay owned by their Kernel v3.1 SCA while every new write is signed by
114
+ * their 7702 EOA, so the SCA hands the agent over before the EOA can operate on
115
+ * it. Deliberately NOT part of the session-key CallPolicy (`REGISTER_GROUP_FNS`)
116
+ * — it is signed by the SCA's sudo validator, and the merkle is already at its
117
+ * Tempo enable-gas ceiling (#1929).
118
+ */ async transferAgentOwnership(agentId, newOwner, owner, txParams) {
119
+ return this.send('transferAgentOwnership', owner, [
120
+ toAgentId(agentId),
121
+ newOwner
122
+ ], txParams);
123
+ }
109
124
  async planConfigPreFilter(priceConfig, creditsConfig, includeFees = true, organizationCryptoFee, organizationCryptoWallet) {
110
125
  const _priceConfig = {
111
126
  ...priceConfig
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/AssetRegistry.ts"],"sourcesContent":["import { CreditsConfig, DIDAgent, Plan, PriceConfig } from '@nevermined-io/commons'\nimport { Account, Address, isAddress, TransactionReceipt, zeroAddress } from 'viem'\nimport { SmartAccount, UserOperationReceipt } from 'viem/account-abstraction'\nimport {\n assetsRegistryConfig,\n nft1155CreditsAddress,\n nft1155ExpirableCreditsV2Address,\n oneTimeCreatorHookAddress,\n payAsYouGoTemplateAddress,\n protocolStandardFeesAddress,\n} from '../artifacts/generated.js'\nimport { AgentNotFound, PlanNotFound } from '../errors/NeverminedErrors.js'\nimport { InstantiableConfig } from '../Instantiable.abstract.js'\nimport { TxParameters } from '../models/Transactions.js'\nimport { toAgentId, zeroX } from '../utils/ConversionTypeHelpers.js'\nimport { ContractBase } from './ContractBase.js'\n\n/**\n * Loose structural type for the ABI items we filter in `hashPlanId` to\n * disambiguate the legacy 3-arg overload from the 4-arg one. Mirrors only\n * the fields we read, so it stays usable against the auto-generated tuple\n * type emitted by wagmi codegen without dragging in the full viem type.\n */\ntype AbiItemLike = {\n type: string\n name?: string\n inputs?: ReadonlyArray<unknown>\n}\n\nexport class AssetRegistry extends ContractBase {\n public static override async getInstance(config: InstantiableConfig): Promise<AssetRegistry> {\n const assetRegistry: AssetRegistry = new AssetRegistry(\n 'AssetRegistry',\n assetsRegistryConfig.address,\n )\n await assetRegistry.init(config, assetsRegistryConfig)\n return assetRegistry\n }\n\n public async hashAgentId(seed: string, owner: Address): Promise<bigint> {\n return this.contract.read.hashAgentId([seed, owner])\n }\n\n public async getAgent(agentId: string | bigint): Promise<DIDAgent> {\n const didAgent = await this.contract.read.getAgent([toAgentId(agentId)])\n if (didAgent.lastUpdated != 0) return didAgent\n else throw new AgentNotFound(`Agent with id ${agentId} not found`)\n }\n\n public async register({\n seed,\n url,\n plans,\n owner,\n txParams,\n }: {\n seed: string\n url: string\n plans: bigint[]\n owner: Account | SmartAccount\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n return this.send('register', owner, [zeroX(seed), url, plans], txParams)\n }\n\n public async createPayAsYouGoPlan({\n priceConfig,\n creditsConfig,\n owner,\n nonce = 0n,\n addFees = true,\n isTrialPlan = false,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n }: {\n priceConfig: PriceConfig\n creditsConfig: CreditsConfig\n owner: Account | SmartAccount\n nonce?: bigint\n addFees?: boolean\n isTrialPlan?: boolean\n organizationCryptoFee?: bigint\n organizationCryptoWallet?: string\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n priceConfig.templateAddress = payAsYouGoTemplateAddress\n return this.createPlan({\n priceConfig,\n creditsConfig,\n owner,\n nonce,\n addFees,\n isTrialPlan,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n })\n }\n\n public async createPlan({\n priceConfig,\n creditsConfig,\n owner,\n nonce = 0n,\n addFees = true,\n isTrialPlan = false,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n }: {\n priceConfig: PriceConfig\n creditsConfig: CreditsConfig\n owner: Account | SmartAccount\n nonce?: bigint\n addFees?: boolean\n isTrialPlan?: boolean\n organizationCryptoFee?: bigint\n organizationCryptoWallet?: string\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n const _config = await this.planConfigPreFilter(\n priceConfig,\n creditsConfig,\n addFees,\n organizationCryptoFee,\n organizationCryptoWallet,\n )\n\n if (isTrialPlan) {\n const hooks: Address[] = [oneTimeCreatorHookAddress]\n return this.send(\n 'createPlanWithHooks',\n owner,\n [_config.priceConfig, _config.creditsConfig, hooks, nonce],\n txParams,\n )\n } else {\n return this.send(\n 'createPlan',\n owner,\n [_config.priceConfig, _config.creditsConfig, nonce],\n txParams,\n )\n }\n }\n\n public async registerAgentAndPlan({\n seed,\n url,\n priceConfig,\n creditsConfig,\n owner,\n addFees = true,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n }: {\n seed: string\n url: string\n priceConfig: PriceConfig\n creditsConfig: CreditsConfig\n owner: Account | SmartAccount\n addFees?: boolean\n organizationCryptoFee?: bigint\n organizationCryptoWallet?: string\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n const _config = await this.planConfigPreFilter(\n priceConfig,\n creditsConfig,\n addFees,\n organizationCryptoFee,\n organizationCryptoWallet,\n )\n\n return this.send(\n 'registerAgentAndPlan',\n owner,\n [zeroX(seed), url, _config.priceConfig, _config.creditsConfig],\n txParams,\n )\n }\n\n public async getPlan(planId: bigint): Promise<Plan> {\n const plan = this.contract.read.getPlan([planId])\n if (plan.lastUpdated != 0) return plan\n else throw new PlanNotFound('Plan not registered')\n }\n\n public async getPlanTotalPrice({\n planId,\n plan,\n }: {\n planId?: bigint\n plan?: Plan\n }): Promise<bigint> {\n if (!plan && !planId) {\n throw new PlanNotFound('Plan not registered')\n }\n if (!plan) {\n plan = await this.getPlan(planId!)\n }\n\n if (plan.lastUpdated === 0n) throw new PlanNotFound('Plan not registered')\n return plan.price.amounts.reduce((a: bigint, b: bigint) => a + b, 0n)\n }\n\n public async planExists(id: bigint): Promise<boolean> {\n return this.contract.read.planExists([id])\n }\n\n public async addPlanToAgent(\n planId: bigint,\n agentId: string | bigint,\n owner: Account | SmartAccount,\n txParams?: TxParameters,\n ): Promise<TransactionReceipt | UserOperationReceipt> {\n return this.send('addPlanToAgent', owner, [toAgentId(agentId), planId], txParams)\n }\n\n public async removePlanFromAgent(\n planId: bigint,\n agentId: string | bigint,\n owner: Account | SmartAccount,\n txParams?: TxParameters,\n ): Promise<TransactionReceipt | UserOperationReceipt> {\n return this.send('removePlanFromAgent', owner, [toAgentId(agentId), planId], txParams)\n }\n\n public async planConfigPreFilter(\n priceConfig: PriceConfig,\n creditsConfig: CreditsConfig,\n includeFees = true,\n organizationCryptoFee?: bigint,\n organizationCryptoWallet?: string,\n ) {\n const _priceConfig = { ...priceConfig }\n // Compat shim: the contract ABI in `artifacts/generated.ts` still names\n // the credits-config slot `proofRequired` (legacy EIP-712 signed-burn\n // flag, see nvm-monorepo#1253). The TS interface renamed it to\n // `onchainMirror` in PR #1277. Viem looks up tuple components by name\n // when ABI-encoding, so without this alias every downstream\n // `contract.read.*([creditsConfig, ...])` call resolves the slot to\n // `undefined` and throws \"Invalid boolean value: 'undefined'\". Inject\n // the alias here so every method that runs through `planConfigPreFilter`\n // (`createPlan`, `hashPlanId`, `registerAgentAndPlan`,\n // `includeFeesInPaymentsDistribution` via line 244) sees a config\n // viem can encode. Drop once the contract artifact is regenerated.\n const _creditsConfig = {\n ...creditsConfig,\n proofRequired: creditsConfig.onchainMirror,\n }\n\n if (!priceConfig.feeController || !isAddress(priceConfig.feeController!))\n _priceConfig.feeController = protocolStandardFeesAddress\n\n if (!priceConfig.templateAddress || !isAddress(priceConfig.templateAddress!))\n _priceConfig.templateAddress = zeroAddress\n\n if (!creditsConfig.nftAddress || !isAddress(creditsConfig.nftAddress)) {\n if (creditsConfig.durationSecs > 0n) {\n _creditsConfig.nftAddress = nft1155ExpirableCreditsV2Address\n } else {\n _creditsConfig.nftAddress = nft1155CreditsAddress\n }\n }\n\n if (includeFees) {\n const fees = await this.includeFeesInPaymentsDistribution(_priceConfig, _creditsConfig)\n _priceConfig.amounts = fees[0]\n _priceConfig.receivers = fees[1]\n }\n\n if (organizationCryptoFee && organizationCryptoWallet) {\n _priceConfig.amounts.push(organizationCryptoFee)\n _priceConfig.receivers.push(organizationCryptoWallet)\n }\n\n return { priceConfig: _priceConfig, creditsConfig: _creditsConfig }\n }\n\n public async hashPlanId(\n _priceConfig: PriceConfig,\n _creditsConfig: CreditsConfig,\n owner: Address,\n addFees = true,\n nonce = 0n,\n organizationCryptoFee?: bigint,\n organizationCryptoWallet?: string,\n ): Promise<bigint> {\n const _config = await this.planConfigPreFilter(\n _priceConfig,\n _creditsConfig,\n addFees,\n organizationCryptoFee,\n organizationCryptoWallet,\n )\n // The generated ABI carries both the legacy 3-arg `hashPlanId(_priceConfig,\n // _creditsConfig, _creator)` overload and the new 4-arg\n // `hashPlanId(_priceConfig, _creditsConfig, _creator, _nonce)` overload.\n // Viem's `getContract().read.<name>` proxy resolves overloads by NAME\n // only — it picks the first matching ABI item without re-checking\n // arity — so the 4-arg call below was being encoded against the 3-arg\n // overload and erroring with `AbiEncodingLengthMismatchError: Expected\n // length 3, Given length 4` (CI run 25872339578, core-kit e2e).\n //\n // Drop directly to `readContract` with an ABI restricted to the 4-arg\n // function so there's only one possible match. Same effect as\n // dropping the legacy overload from the artifact, but local to this\n // call site (the artifact is regenerated by `pnpm generate:wagmi:*`\n // from the protocol submodule, so a tree-side artifact edit would be\n // wiped on the next codegen).\n const hashPlanIdAbi = (this.contract.abi as readonly AbiItemLike[]).filter(\n (item) =>\n item.type === 'function' &&\n item.name === 'hashPlanId' &&\n Array.isArray(item.inputs) &&\n item.inputs.length === 4,\n )\n return (await this.client.public.readContract({\n address: this.address,\n abi: hashPlanIdAbi,\n functionName: 'hashPlanId',\n args: [_config.priceConfig, _config.creditsConfig, owner, nonce],\n })) as bigint\n }\n\n /**\n * @notice Checks if Nevermined fees are included in the payment distribution\n * @param _planId The ID of the plan to check\n * @return bool True if Nevermined fees are properly included\n */\n public async areNeverminedFeesIncluded(priceConfig: PriceConfig): Promise<boolean> {\n return await this.contract.read.areNeverminedFeesIncluded([\n priceConfig.amounts,\n priceConfig.receivers,\n ])\n }\n\n /**\n * @notice Getting a payment distribution, it includes the Nevermined fees if not already included\n * This method subsctracts the fees from the original amounts and adds a new entry for the fee recipient\n * @param priceConfig The price configuration of the plan\n * @param creditsConfig The credits configuration of the plan\n * @return amounts Updated array of payment amounts including fees\n * @return receivers Updated array of payment receivers including fee recipient\n */\n public async includeFeesInPaymentsDistribution(\n priceConfig: PriceConfig,\n creditsConfig: CreditsConfig,\n ): Promise<[bigint[], string[]]> {\n const result = await this.contract.read.includeFeesInPaymentsDistribution([\n priceConfig,\n creditsConfig,\n ])\n return result\n }\n\n /**\n * @notice Adds Nevermined fees to the payment distribution if not already included\n * @param priceConfig The price configuration of the plan\n * @param creditsConfig The credits configuration of the plan\n * @return amounts Updated array of payment amounts including fees\n * @return receivers Updated array of payment receivers including fee recipient\n */\n public async addFeesToPaymentsDistribution(\n priceConfig: PriceConfig,\n creditsConfig: CreditsConfig,\n ): Promise<[bigint[], string[]]> {\n const result = await this.contract.read.addFeesToPaymentsDistribution([\n priceConfig,\n creditsConfig,\n ])\n return result\n }\n}\n"],"names":["isAddress","zeroAddress","assetsRegistryConfig","nft1155CreditsAddress","nft1155ExpirableCreditsV2Address","oneTimeCreatorHookAddress","payAsYouGoTemplateAddress","protocolStandardFeesAddress","AgentNotFound","PlanNotFound","toAgentId","zeroX","ContractBase","AssetRegistry","getInstance","config","assetRegistry","address","init","hashAgentId","seed","owner","contract","read","getAgent","agentId","didAgent","lastUpdated","register","url","plans","txParams","send","createPayAsYouGoPlan","priceConfig","creditsConfig","nonce","addFees","isTrialPlan","organizationCryptoFee","organizationCryptoWallet","templateAddress","createPlan","_config","planConfigPreFilter","hooks","registerAgentAndPlan","getPlan","planId","plan","getPlanTotalPrice","price","amounts","reduce","a","b","planExists","id","addPlanToAgent","removePlanFromAgent","includeFees","_priceConfig","_creditsConfig","proofRequired","onchainMirror","feeController","nftAddress","durationSecs","fees","includeFeesInPaymentsDistribution","receivers","push","hashPlanId","hashPlanIdAbi","abi","filter","item","type","name","Array","isArray","inputs","length","client","public","readContract","functionName","args","areNeverminedFeesIncluded","result","addFeesToPaymentsDistribution"],"mappings":"AACA,SAA2BA,SAAS,EAAsBC,WAAW,QAAQ,OAAM;AAEnF,SACEC,oBAAoB,EACpBC,qBAAqB,EACrBC,gCAAgC,EAChCC,yBAAyB,EACzBC,yBAAyB,EACzBC,2BAA2B,QACtB,4BAA2B;AAClC,SAASC,aAAa,EAAEC,YAAY,QAAQ,gCAA+B;AAG3E,SAASC,SAAS,EAAEC,KAAK,QA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AM,CAACC,MAAM,CAACC,YAAY,CAAC;YAC5CpE,SAAS,IAAI,CAACA,OAAO;YACrByD,KAAKD;YACLa,cAAc;YACdC,MAAM;gBAAC5C,QAAQT,WAAW;gBAAES,QAAQR,aAAa;gBAAEd;gBAAOe;aAAM;QAClE;IACF;IAEA;;;;GAIC,GACD,MAAaoD,0BAA0BtD,WAAwB,EAAoB;QACjF,OAAO,MAAM,IAAI,CAACZ,QAAQ,CAACC,IAAI,CAACiE,yBAAyB,CAAC;YACxDtD,YAAYkB,OAAO;YACnBlB,YAAYoC,SAAS;SACtB;IACH;IAEA;;;;;;;GAOC,GACD,MAAaD,kCACXnC,WAAwB,EACxBC,aAA4B,EACG;QAC/B,MAAMsD,SAAS,MAAM,IAAI,CAACnE,QAAQ,CAACC,IAAI,CAAC8C,iCAAiC,CAAC;YACxEnC;YACAC;SACD;QACD,OAAOsD;IACT;IAEA;;;;;;GAMC,GACD,MAAaC,8BACXxD,WAAwB,EACxBC,aAA4B,EACG;QAC/B,MAAMsD,SAAS,MAAM,IAAI,CAACnE,QAAQ,CAACC,IAAI,CAACmE,6BAA6B,CAAC;YACpExD;YACAC;SACD;QACD,OAAOsD;IACT;AACF"}
1
+ {"version":3,"sources":["../../src/contracts/AssetRegistry.ts"],"sourcesContent":["import { CreditsConfig, DIDAgent, Plan, PriceConfig } from '@nevermined-io/commons'\nimport { Account, Address, isAddress, TransactionReceipt, zeroAddress } from 'viem'\nimport { SmartAccount, UserOperationReceipt } from 'viem/account-abstraction'\nimport {\n assetsRegistryConfig,\n nft1155CreditsAddress,\n nft1155ExpirableCreditsV2Address,\n oneTimeCreatorHookAddress,\n payAsYouGoTemplateAddress,\n protocolStandardFeesAddress,\n} from '../artifacts/generated.js'\nimport { AgentNotFound, PlanNotFound } from '../errors/NeverminedErrors.js'\nimport { InstantiableConfig } from '../Instantiable.abstract.js'\nimport { TxParameters } from '../models/Transactions.js'\nimport { toAgentId, zeroX } from '../utils/ConversionTypeHelpers.js'\nimport { ContractBase } from './ContractBase.js'\n\n/**\n * Loose structural type for the ABI items we filter in `hashPlanId` to\n * disambiguate the legacy 3-arg overload from the 4-arg one. Mirrors only\n * the fields we read, so it stays usable against the auto-generated tuple\n * type emitted by wagmi codegen without dragging in the full viem type.\n */\ntype AbiItemLike = {\n type: string\n name?: string\n inputs?: ReadonlyArray<unknown>\n}\n\nexport class AssetRegistry extends ContractBase {\n public static override async getInstance(config: InstantiableConfig): Promise<AssetRegistry> {\n const assetRegistry: AssetRegistry = new AssetRegistry(\n 'AssetRegistry',\n assetsRegistryConfig.address,\n )\n await assetRegistry.init(config, assetsRegistryConfig)\n return assetRegistry\n }\n\n public async hashAgentId(seed: string, owner: Address): Promise<bigint> {\n return this.contract.read.hashAgentId([seed, owner])\n }\n\n public async getAgent(agentId: string | bigint): Promise<DIDAgent> {\n const didAgent = await this.contract.read.getAgent([toAgentId(agentId)])\n if (didAgent.lastUpdated != 0) return didAgent\n else throw new AgentNotFound(`Agent with id ${agentId} not found`)\n }\n\n public async register({\n seed,\n url,\n plans,\n owner,\n txParams,\n }: {\n seed: string\n url: string\n plans: bigint[]\n owner: Account | SmartAccount\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n return this.send('register', owner, [zeroX(seed), url, plans], txParams)\n }\n\n public async createPayAsYouGoPlan({\n priceConfig,\n creditsConfig,\n owner,\n nonce = 0n,\n addFees = true,\n isTrialPlan = false,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n }: {\n priceConfig: PriceConfig\n creditsConfig: CreditsConfig\n owner: Account | SmartAccount\n nonce?: bigint\n addFees?: boolean\n isTrialPlan?: boolean\n organizationCryptoFee?: bigint\n organizationCryptoWallet?: string\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n priceConfig.templateAddress = payAsYouGoTemplateAddress\n return this.createPlan({\n priceConfig,\n creditsConfig,\n owner,\n nonce,\n addFees,\n isTrialPlan,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n })\n }\n\n public async createPlan({\n priceConfig,\n creditsConfig,\n owner,\n nonce = 0n,\n addFees = true,\n isTrialPlan = false,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n }: {\n priceConfig: PriceConfig\n creditsConfig: CreditsConfig\n owner: Account | SmartAccount\n nonce?: bigint\n addFees?: boolean\n isTrialPlan?: boolean\n organizationCryptoFee?: bigint\n organizationCryptoWallet?: string\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n const _config = await this.planConfigPreFilter(\n priceConfig,\n creditsConfig,\n addFees,\n organizationCryptoFee,\n organizationCryptoWallet,\n )\n\n if (isTrialPlan) {\n const hooks: Address[] = [oneTimeCreatorHookAddress]\n return this.send(\n 'createPlanWithHooks',\n owner,\n [_config.priceConfig, _config.creditsConfig, hooks, nonce],\n txParams,\n )\n } else {\n return this.send(\n 'createPlan',\n owner,\n [_config.priceConfig, _config.creditsConfig, nonce],\n txParams,\n )\n }\n }\n\n public async registerAgentAndPlan({\n seed,\n url,\n priceConfig,\n creditsConfig,\n owner,\n addFees = true,\n organizationCryptoFee,\n organizationCryptoWallet,\n txParams,\n }: {\n seed: string\n url: string\n priceConfig: PriceConfig\n creditsConfig: CreditsConfig\n owner: Account | SmartAccount\n addFees?: boolean\n organizationCryptoFee?: bigint\n organizationCryptoWallet?: string\n txParams?: TxParameters\n }): Promise<TransactionReceipt | UserOperationReceipt> {\n const _config = await this.planConfigPreFilter(\n priceConfig,\n creditsConfig,\n addFees,\n organizationCryptoFee,\n organizationCryptoWallet,\n )\n\n return this.send(\n 'registerAgentAndPlan',\n owner,\n [zeroX(seed), url, _config.priceConfig, _config.creditsConfig],\n txParams,\n )\n }\n\n public async getPlan(planId: bigint): Promise<Plan> {\n const plan = this.contract.read.getPlan([planId])\n if (plan.lastUpdated != 0) return plan\n else throw new PlanNotFound('Plan not registered')\n }\n\n public async getPlanTotalPrice({\n planId,\n plan,\n }: {\n planId?: bigint\n plan?: Plan\n }): Promise<bigint> {\n if (!plan && !planId) {\n throw new PlanNotFound('Plan not registered')\n }\n if (!plan) {\n plan = await this.getPlan(planId!)\n }\n\n if (plan.lastUpdated === 0n) throw new PlanNotFound('Plan not registered')\n return plan.price.amounts.reduce((a: bigint, b: bigint) => a + b, 0n)\n }\n\n public async planExists(id: bigint): Promise<boolean> {\n return this.contract.read.planExists([id])\n }\n\n public async addPlanToAgent(\n planId: bigint,\n agentId: string | bigint,\n owner: Account | SmartAccount,\n txParams?: TxParameters,\n ): Promise<TransactionReceipt | UserOperationReceipt> {\n return this.send('addPlanToAgent', owner, [toAgentId(agentId), planId], txParams)\n }\n\n public async removePlanFromAgent(\n planId: bigint,\n agentId: string | bigint,\n owner: Account | SmartAccount,\n txParams?: TxParameters,\n ): Promise<TransactionReceipt | UserOperationReceipt> {\n return this.send('removePlanFromAgent', owner, [toAgentId(agentId), planId], txParams)\n }\n\n /**\n * Move an agent's on-chain ownership. Only the CURRENT owner can call it.\n *\n * Used by the EIP-7702 migration healing path (#2152): a user's pre-migration\n * agents stay owned by their Kernel v3.1 SCA while every new write is signed by\n * their 7702 EOA, so the SCA hands the agent over before the EOA can operate on\n * it. Deliberately NOT part of the session-key CallPolicy (`REGISTER_GROUP_FNS`)\n * — it is signed by the SCA's sudo validator, and the merkle is already at its\n * Tempo enable-gas ceiling (#1929).\n */\n public async transferAgentOwnership(\n agentId: string | bigint,\n newOwner: `0x${string}`,\n owner: Account | SmartAccount,\n txParams?: TxParameters,\n ): Promise<TransactionReceipt | UserOperationReceipt> {\n return this.send('transferAgentOwnership', owner, [toAgentId(agentId), newOwner], txParams)\n }\n\n public async planConfigPreFilter(\n priceConfig: PriceConfig,\n creditsConfig: CreditsConfig,\n includeFees = true,\n organizationCryptoFee?: bigint,\n organizationCryptoWallet?: string,\n ) {\n const _priceConfig = { ...priceConfig }\n // Compat shim: the contract ABI in `artifacts/generated.ts` still names\n // the credits-config slot `proofRequired` (legacy EIP-712 signed-burn\n // flag, see nvm-monorepo#1253). The TS interface renamed it to\n // `onchainMirror` in PR #1277. Viem looks up tuple components by name\n // when ABI-encoding, so without this alias every downstream\n // `contract.read.*([creditsConfig, ...])` call resolves the slot to\n // `undefined` and throws \"Invalid boolean value: 'undefined'\". Inject\n // the alias here so every method that runs through `planConfigPreFilter`\n // (`createPlan`, `hashPlanId`, `registerAgentAndPlan`,\n // `includeFeesInPaymentsDistribution` via line 244) sees a config\n // viem can encode. Drop once the contract artifact is regenerated.\n const _creditsConfig = {\n ...creditsConfig,\n proofRequired: creditsConfig.onchainMirror,\n }\n\n if (!priceConfig.feeController || !isAddress(priceConfig.feeController!))\n _priceConfig.feeController = protocolStandardFeesAddress\n\n if (!priceConfig.templateAddress || !isAddress(priceConfig.templateAddress!))\n _priceConfig.templateAddress = zeroAddress\n\n if (!creditsConfig.nftAddress || !isAddress(creditsConfig.nftAddress)) {\n if (creditsConfig.durationSecs > 0n) {\n _creditsConfig.nftAddress = nft1155ExpirableCreditsV2Address\n } else {\n _creditsConfig.nftAddress = nft1155CreditsAddress\n }\n }\n\n if (includeFees) {\n const fees = await this.includeFeesInPaymentsDistribution(_priceConfig, _creditsConfig)\n _priceConfig.amounts = fees[0]\n _priceConfig.receivers = fees[1]\n }\n\n if (organizationCryptoFee && organizationCryptoWallet) {\n _priceConfig.amounts.push(organizationCryptoFee)\n _priceConfig.receivers.push(organizationCryptoWallet)\n }\n\n return { priceConfig: _priceConfig, creditsConfig: _creditsConfig }\n }\n\n public async hashPlanId(\n _priceConfig: PriceConfig,\n _creditsConfig: CreditsConfig,\n owner: Address,\n addFees = true,\n nonce = 0n,\n organizationCryptoFee?: bigint,\n organizationCryptoWallet?: string,\n ): Promise<bigint> {\n const _config = await this.planConfigPreFilter(\n _priceConfig,\n _creditsConfig,\n addFees,\n organizationCryptoFee,\n organizationCryptoWallet,\n )\n // The generated ABI carries both the legacy 3-arg `hashPlanId(_priceConfig,\n // _creditsConfig, _creator)` overload and the new 4-arg\n // `hashPlanId(_priceConfig, _creditsConfig, _creator, _nonce)` overload.\n // Viem's `getContract().read.<name>` proxy resolves overloads by NAME\n // only — it picks the first matching ABI item without re-checking\n // arity — so the 4-arg call below was being encoded against the 3-arg\n // overload and erroring with `AbiEncodingLengthMismatchError: Expected\n // length 3, Given length 4` (CI run 25872339578, core-kit e2e).\n //\n // Drop directly to `readContract` with an ABI restricted to the 4-arg\n // function so there's only one possible match. Same effect as\n // dropping the legacy overload from the artifact, but local to this\n // call site (the artifact is regenerated by `pnpm generate:wagmi:*`\n // from the protocol submodule, so a tree-side artifact edit would be\n // wiped on the next codegen).\n const hashPlanIdAbi = (this.contract.abi as readonly AbiItemLike[]).filter(\n (item) =>\n item.type === 'function' &&\n item.name === 'hashPlanId' &&\n Array.isArray(item.inputs) &&\n item.inputs.length === 4,\n )\n return (await this.client.public.readContract({\n address: this.address,\n abi: hashPlanIdAbi,\n functionName: 'hashPlanId',\n args: [_config.priceConfig, _config.creditsConfig, owner, nonce],\n })) as bigint\n }\n\n /**\n * @notice Checks if Nevermined fees are included in the payment distribution\n * @param _planId The ID of the plan to check\n * @return bool True if Nevermined fees are properly included\n */\n public async areNeverminedFeesIncluded(priceConfig: PriceConfig): Promise<boolean> {\n return await this.contract.read.areNeverminedFeesIncluded([\n priceConfig.amounts,\n priceConfig.receivers,\n ])\n }\n\n /**\n * @notice Getting a payment distribution, it includes the Nevermined fees if not already included\n * This method subsctracts the fees from the original amounts and adds a new entry for the fee recipient\n * @param priceConfig The price configuration of the plan\n * @param creditsConfig The credits configuration of the plan\n * @return amounts Updated array of payment amounts including fees\n * @return receivers Updated array of payment receivers including fee recipient\n */\n public async includeFeesInPaymentsDistribution(\n priceConfig: PriceConfig,\n creditsConfig: CreditsConfig,\n ): Promise<[bigint[], string[]]> {\n const result = await this.contract.read.includeFeesInPaymentsDistribution([\n priceConfig,\n creditsConfig,\n ])\n return result\n }\n\n /**\n * @notice Adds Nevermined fees to the payment distribution if not already included\n * @param priceConfig The price configuration of the plan\n * @param creditsConfig The credits configuration of the plan\n * @return amounts Updated array of payment amounts including fees\n * @return receivers Updated array of payment receivers including fee recipient\n */\n public async addFeesToPaymentsDistribution(\n priceConfig: PriceConfig,\n creditsConfig: CreditsConfig,\n ): Promise<[bigint[], string[]]> {\n const result = await this.contract.read.addFeesToPaymentsDistribution([\n priceConfig,\n creditsConfig,\n ])\n return result\n }\n}\n"],"names":["isAddress","zeroAddress","assetsRegistryConfig","nft1155CreditsAddress","nft1155ExpirableCreditsV2Address","oneTimeCreatorHookAddress","payAsYouGoTemplateAddress","protocolStandardFeesAddress","AgentNotFound","PlanNotFound","toAgentId","zeroX","ContractBase","AssetRegistry","getInstance","config","assetRegistry","address","init","hashAgentId","seed","owner","contract","read","getAgent","agentId","didAgent","lastUpdated","register","url","plans","txParams","send","createPayAsYouGoPlan","priceConfig","creditsConfig","nonce","addFees","isTrialPlan","organizationCryptoFee","organizationCryptoWallet","templateAddress","createPlan","_config","planConfigPreFilter","hooks","registerAgentAndPlan","getPlan","planId","plan","getPlanTotalPrice","price","amounts","reduce","a","b","planExists","id","addPlanToAgent","removePlanFromAgent","transferAgentOwnership","newOwner","includeFees","_priceConfig","_creditsConfig","proofRequired","onchainMirror","feeController","nftAddress","durationSecs","fees","includeFeesInPaymentsDistribution","receivers","push","hashPlanId","hashPlanIdAbi","abi","filter","item","type","name","Array","isArray","inputs","length","client","public","readContract","functionName","args","areNeverminedFeesIncluded","result","addFeesToPaymentsDistribution"],"mappings":"AACA,SAA2BA,SAAS,EAAsBC,WAAW,QAAQ,OAAM;AAEnF,SACEC,oBAAoB,EACpBC,qBAAqB,EACrBC,gCAAgC,EAChCC,yBAAyB,EACzBC,yBAAyB,EACzBC,2BAA2B,QACtB,4BAA2B;AAClC,SAASC,aAAa,EAAEC,YAAY,QAAQ,gCAA+B;AAG3E,SAASC,SAAS,EAAEC,KAAK,QAAQ,oCAAmC;AACpE,SAASC,YAAY,QAAQ,oBAAmB;AAchD,OAAO,MAAMC,sBAAsBD;IACjC,aAA6BE,Y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OAAO,CAACJ,KAAKK,MAAM,KACzBL,KAAKK,MAAM,CAACC,MAAM,KAAK;QAE3B,OAAQ,MAAM,IAAI,CAACC,MAAM,CAACC,MAAM,CAACC,YAAY,CAAC;YAC5CtE,SAAS,IAAI,CAACA,OAAO;YACrB2D,KAAKD;YACLa,cAAc;YACdC,MAAM;gBAAC9C,QAAQT,WAAW;gBAAES,QAAQR,aAAa;gBAAEd;gBAAOe;aAAM;QAClE;IACF;IAEA;;;;GAIC,GACD,MAAasD,0BAA0BxD,WAAwB,EAAoB;QACjF,OAAO,MAAM,IAAI,CAACZ,QAAQ,CAACC,IAAI,CAACmE,yBAAyB,CAAC;YACxDxD,YAAYkB,OAAO;YACnBlB,YAAYsC,SAAS;SACtB;IACH;IAEA;;;;;;;GAOC,GACD,MAAaD,kCACXrC,WAAwB,EACxBC,aAA4B,EACG;QAC/B,MAAMwD,SAAS,MAAM,IAAI,CAACrE,QAAQ,CAACC,IAAI,CAACgD,iCAAiC,CAAC;YACxErC;YACAC;SACD;QACD,OAAOwD;IACT;IAEA;;;;;;GAMC,GACD,MAAaC,8BACX1D,WAAwB,EACxBC,aAA4B,EACG;QAC/B,MAAMwD,SAAS,MAAM,IAAI,CAACrE,QAAQ,CAACC,IAAI,CAACqE,6BAA6B,CAAC;YACpE1D;YACAC;SACD;QACD,OAAOwD;IACT;AACF"}
@@ -11,6 +11,15 @@ export declare class NvmApiKey implements JWTPayload {
11
11
  * The chain id of the network the key is valid for. If zero the key is not having any network limitation
12
12
  */
13
13
  aud?: string;
14
+ /**
15
+ * RFC 8707 resource indicator (the credential's audience) — the resource server this key is
16
+ * confined to, e.g. `https://api.<tier>.nevermined.app` (#2432). NVM uses `rsc` rather than the
17
+ * standard `aud` because `aud` already carries the chain id (above). Set only on the OAuth mint
18
+ * path from the AgentBinding's `resource`; absent ⇒ unrestricted (dashboard/CLI/legacy keys).
19
+ * MUST be left `undefined` (never `null`) when absent so it is omitted from `JSON.stringify(this)`
20
+ * and the key's `hash()` stays byte-identical to a pre-#2432 key.
21
+ */
22
+ rsc?: string;
14
23
  /**
15
24
  * The public address of the account the key is issued for.
16
25
  */
@@ -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;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;;;;OAKG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAE7B;;OAEG;IAGH;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IAEZ;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,CAAA;IAEvB;;;;;;;;;;;OAWG;WACiB,QAAQ,CAC1B,cAAc,EAAE,cAAc,EAC9B,aAAa,EAAE,OAAO,GAAG,YAAY,EACrC,iBAAiB,EAAE,MAAM,GAAG,SAAS,EACrC,eAAe,EAAE,MAAM,EACvB,iBAAiB,EAAE,MAAM,EACzB,cAAc,GAAE,MAAM,GAAG,MAAa,EACtC,gBAAgB,KAAK,EACrB,gBAAgB,SAAO,GACtB,OAAO,CAAC,MAAM,CAAC;IA4BlB;;;;;OAKG;WACiB,gB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,OAAO,GAAG,YAAY,EACrC,cAAc,CAAC,EAAE,MAAM,GACtB,OAAO,CAAC,MAAM,CAAC;IAkBlB;;;;OAIG;WACW,QAAQ,CAAC,GAAG,EAAE,UAAU,GAAG,SAAS;IAYlD;;;;OAIG;WACW,OAAO,CAAC,SAAS,EAAE,MAAM,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"}
@@ -114,7 +114,8 @@ export class NvmApiKey {
114
114
  sub: this.iss,
115
115
  jti: this.hash(),
116
116
  exp: this.exp,
117
- o11y: heliconeApiKey
117
+ o11y: heliconeApiKey,
118
+ rsc: this.rsc
118
119
  }).setProtectedHeader({
119
120
  alg: 'ES256K'
120
121
  })// .setIssuedAt() // WARNING: If enabled, the hash will change for the same NvmApiKey
@@ -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 (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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AAUL,GAAW,EAAE;QACnC,OAAO9E,UAAU8E;IACnB;IAEA;;;GAGC,GACD,AAAOJ,OAAO;QACZ,OAAOtE,eAAesE,IAAI,CAAC,IAAI,CAACW,SAAS;IAC3C;IAEA;;;;GAIC,GACD,OAAOX,KAAKY,UAAkB,EAAE;QAC9B,OAAOlF,eAAesE,IAAI,CAACY;IAC7B;;QA7QA;;GAEC,QACDvD,MAAM;;AA2QR"}
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 * RFC 8707 resource indicator (the credential's audience) — the resource server this key is\n * confined to, e.g. `https://api.<tier>.nevermined.app` (#2432). NVM uses `rsc` rather than the\n * standard `aud` because `aud` already carries the chain id (above). Set only on the OAuth mint\n * path from the AgentBinding's `resource`; absent ⇒ unrestricted (dashboard/CLI/legacy keys).\n * MUST be left `undefined` (never `null`) when absent so it is omitted from `JSON.stringify(this)`\n * and the key's `hash()` stays byte-identical to a pre-#2432 key.\n */\n rsc?: 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 rsc: this.rsc, // RFC 8707 resource/audience (#2432); undefined ⇒ omitted, token unchanged\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","rsc","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,S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AAOtE,eAAesE,IAAI,CAAC,IAAI,CAACY,SAAS;IAC3C;IAEA;;;;GAIC,GACD,OAAOZ,KAAKa,UAAkB,EAAE;QAC9B,OAAOnF,eAAesE,IAAI,CAACa;IAC7B;;QA9QA;;GAEC,QACDxD,MAAM;;AA4QR"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nevermined-io/core-kit",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",