@zkp2p/sdk 0.12.2-rc.3 → 0.13.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/index.mjs CHANGED
@@ -2,15 +2,15 @@ import { IntentGuardianOperations } from './chunk-YA67SM3A.mjs';
2
2
  export { ZERO_RATE_MANAGER_ID, classifyDelegationState, classifyIntentGuardianError, getDelegationRoute, isZeroRateManagerId, normalizeRateManagerId, normalizeRegistry } from './chunk-YA67SM3A.mjs';
3
3
  import { NetworkError, ValidationError, APIError } from './chunk-3J4FPMPW.mjs';
4
4
  export { APIError, ContractError, ErrorCode, NetworkError, ValidationError, ZKP2PError } from './chunk-3J4FPMPW.mjs';
5
- import { OrchestratorRegistry_default, DISPUTE_PROTECTION_POLICY_ABI, DisputeProtectionPolicy_default, METHOD_NAME_TO_HASH, matchesQuotePaymentMethod, matchesPaymentMethodNameAndHash, getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, SUPPORTED_PAYMENT_METHOD_HASHES, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash, OrchestratorV3_default, MultiAttestationVerifier_default, DisputeNullifierRegistry_default, DisputeVerifier_default, WhitelistPolicy_default, StakeVault_default, IntentLifecycleHookV1_default } from './chunk-RVINERIL.mjs';
6
- export { DISPUTE_PROTECTION_POLICY_ABI2 as DISPUTE_PROTECTION_POLICY_ABI, ORCHESTRATOR_V3_ABI, PAYMENT_PLATFORMS, STAKE_VAULT_ABI, asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getContracts, getDisputeProtectionPolicyContract, getGatingServiceAddress, getIntentGuardianContract, getOrchestratorV3Contract, getPaymentMethodsCatalog, getRateManagerContracts, getStakeVaultContract, hasIntentGuardian, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-RVINERIL.mjs';
5
+ import { OrchestratorRegistry_default, DISPUTE_PROTECTION_POLICY_ABI, DisputeProtectionPolicy_default, METHOD_NAME_TO_HASH, matchesQuotePaymentMethod, matchesPaymentMethodNameAndHash, MultiAttestationVerifier_default, getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, SUPPORTED_PAYMENT_METHOD_HASHES, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash, OrchestratorV3_default, DisputeNullifierRegistry_default, DisputeVerifier_default, WhitelistPolicy_default, StakeVault_default, IntentLifecycleHookV1_default } from './chunk-MQYPXD7D.mjs';
6
+ export { DISPUTE_PROTECTION_POLICY_ABI2 as DISPUTE_PROTECTION_POLICY_ABI, ORCHESTRATOR_V3_ABI, PAYMENT_PLATFORMS, STAKE_VAULT_ABI, asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getContracts, getDisputeProtectionPolicyContract, getGatingServiceAddress, getIntentGuardianContract, getOrchestratorV3Contract, getPaymentMethodsCatalog, getRateManagerContracts, getStakeVaultContract, hasIntentGuardian, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-MQYPXD7D.mjs';
7
7
  import { Currency, currencyKeccak256 } from './chunk-ZB22BZLZ.mjs';
8
8
  export { Currency, currencyInfo, getCurrencyCodeFromHash, getCurrencyInfoFromCountryCode, getCurrencyInfoFromHash, isSupportedCurrencyHash, mapConversionRatesToOnchainMinRate } from './chunk-ZB22BZLZ.mjs';
9
- import { define_ZKP2P_SDK_BUILD_METADATA_default } from './chunk-FYCYFFYS.mjs';
9
+ import { define_ZKP2P_SDK_BUILD_METADATA_default } from './chunk-EHLMW7OM.mjs';
10
10
  import { keccak256, concatHex, encodeFunctionData, encodeAbiParameters, createPublicClient, http, isAddress, zeroAddress, formatUnits } from 'viem';
11
11
  import { hardhat, base } from 'viem/chains';
12
12
  import { createEncryptedBuyerTeeSessionMaterial as createEncryptedBuyerTeeSessionMaterial$1, createEncryptedSellerCredentialUpload } from '@zkp2p/zkp2p-attestation';
13
- export { createNitroAttestationClient } from '@zkp2p/zkp2p-attestation';
13
+ export { createNitroAttestationClient, verifyDisputeAttestation } from '@zkp2p/zkp2p-attestation';
14
14
  import { AbiCoder } from 'ethers';
15
15
  import { Attribution } from 'ox/erc8021';
16
16
 
@@ -352,12 +352,12 @@ function parseAPIError(response, responseText) {
352
352
  }
353
353
  return new APIError(message, response.status, { url: response.url, responseBody: parsedBody });
354
354
  }
355
- async function withRetry(fn, maxRetries = 3, delayMs = 1e3, timeoutMs) {
355
+ async function withRetry(fn, maxRetries = 3, delayMs = 1e3, timeoutMs, shouldRetry) {
356
356
  let lastErr;
357
357
  for (let i = 0; i < maxRetries; i++) {
358
358
  try {
359
359
  if (timeoutMs) {
360
- const { withTimeout } = await import('./timeout-TJYY2GX6.mjs');
360
+ const { withTimeout } = await import('./timeout-WA3MYQQ5.mjs');
361
361
  return await withTimeout(fn(), timeoutMs, `Operation timed out after ${timeoutMs}ms`);
362
362
  }
363
363
  return await fn();
@@ -365,7 +365,7 @@ async function withRetry(fn, maxRetries = 3, delayMs = 1e3, timeoutMs) {
365
365
  lastErr = err;
366
366
  const isNetwork = err instanceof NetworkError;
367
367
  const isRateLimit = err instanceof APIError && err.status === 429;
368
- const retryable = isNetwork || isRateLimit;
368
+ const retryable = isNetwork || isRateLimit || shouldRetry?.(err) === true;
369
369
  if (!retryable || i === maxRetries - 1) throw err;
370
370
  const base2 = isRateLimit ? delayMs * Math.pow(2, i) : delayMs;
371
371
  const jitter = Math.floor(Math.random() * Math.min(1e3, base2));
@@ -377,6 +377,8 @@ async function withRetry(fn, maxRetries = 3, delayMs = 1e3, timeoutMs) {
377
377
 
378
378
  // src/adapters/verification.ts
379
379
  var ENFORCED_ON_CHAIN_MESSAGE = /enforced on-chain/i;
380
+ var RETRYABLE_SIGN_INTENT_STATUSES = /* @__PURE__ */ new Set([500, 502, 503, 504]);
381
+ var isRetryableSignIntentError = (error) => error instanceof APIError && error.status !== void 0 && RETRYABLE_SIGN_INTENT_STATUSES.has(error.status);
380
382
  var readCuratorMessage = (body) => {
381
383
  try {
382
384
  const parsed = JSON.parse(body);
@@ -418,7 +420,8 @@ async function apiSignIntentV3Raw(request, opts) {
418
420
  },
419
421
  3,
420
422
  1e3,
421
- opts.timeoutMs
423
+ opts.timeoutMs,
424
+ isRetryableSignIntentError
422
425
  );
423
426
  }
424
427
  async function apiSignIntentV3(request, opts) {
@@ -860,7 +863,7 @@ async function sendTransactionWithAttribution(walletClient, request, referrer, o
860
863
  // src/utils/constants.ts
861
864
  var DEFAULT_BASE_API_URL = "https://api.zkp2p.xyz";
862
865
 
863
- // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.4.3/node_modules/@zkp2p/contracts-v2/oracleFeeds/chainlink.json
866
+ // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.5.4/node_modules/@zkp2p/contracts-v2/oracleFeeds/chainlink.json
864
867
  var chainlink_default = {
865
868
  feeds: [
866
869
  {
@@ -1906,7 +1909,7 @@ var ProtocolViewerReader = class {
1906
1909
  if (inputCount === null) {
1907
1910
  throw new Error("Configured ProtocolViewer ABI does not expose getDeposit");
1908
1911
  }
1909
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-YYBBYCEJ.mjs');
1912
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-DBVBXRYN.mjs');
1910
1913
  if (inputCount >= 3) {
1911
1914
  return tryContexts(
1912
1915
  protocolViewerContexts,
@@ -1992,7 +1995,7 @@ var ProtocolViewerReader = class {
1992
1995
  return Promise.all(ids.map((id) => this.config.host.getPvDepositById(id)));
1993
1996
  }
1994
1997
  const bn = ids.map((id) => typeof id === "bigint" ? id : parseRawDepositId(id));
1995
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-YYBBYCEJ.mjs');
1998
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-DBVBXRYN.mjs');
1996
1999
  if (inputCount >= 2) {
1997
2000
  const requests = ids.map((id, index) => ({
1998
2001
  index,
@@ -2097,7 +2100,7 @@ var ProtocolViewerReader = class {
2097
2100
  if (!protocolViewerAddress || !protocolViewerAbi || inputCount === null) {
2098
2101
  return this.config.host.getPvAccountDepositsFromIndexer(owner);
2099
2102
  }
2100
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-YYBBYCEJ.mjs');
2103
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-DBVBXRYN.mjs');
2101
2104
  const { address, abi } = this.config.host.requireProtocolViewer();
2102
2105
  if (inputCount >= 2) {
2103
2106
  const readAndFilter = async (raw2) => {
@@ -2168,7 +2171,7 @@ var ProtocolViewerReader = class {
2168
2171
  if (protocolViewerEntries.length === 0) {
2169
2172
  throw new Error("ProtocolViewer not available for this network");
2170
2173
  }
2171
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-YYBBYCEJ.mjs');
2174
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-DBVBXRYN.mjs');
2172
2175
  const intentsByHash = /* @__PURE__ */ new Map();
2173
2176
  let attemptedRead = false;
2174
2177
  let hadSuccessfulRead = false;
@@ -2276,7 +2279,7 @@ var ProtocolViewerReader = class {
2276
2279
  if (protocolViewerEntries.length === 0) {
2277
2280
  throw new Error("ProtocolViewer not available for this network");
2278
2281
  }
2279
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-YYBBYCEJ.mjs');
2282
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-DBVBXRYN.mjs');
2280
2283
  let lastError;
2281
2284
  for (const pvEntry of protocolViewerEntries) {
2282
2285
  const inputCount = this.pvEntryFunctionInputCount(pvEntry, "getIntent");
@@ -4668,7 +4671,8 @@ var PaymentPlatform = {
4668
4671
  PAYPAL: "paypal",
4669
4672
  MONZO: "monzo",
4670
4673
  N26: "n26",
4671
- ALIPAY: "alipay"
4674
+ ALIPAY: "alipay",
4675
+ UPI: "upi"
4672
4676
  };
4673
4677
  [...Object.values(PaymentPlatform)];
4674
4678
  var encodeZelleRecipientId = (recipientId) => {
@@ -4931,8 +4935,7 @@ genericZelleBankRoutes.map(({ sendConfig, verifyConfig }) => ({
4931
4935
  }));
4932
4936
  var DISPUTE_PROTECTION_STAKE_PLATFORMS = [
4933
4937
  PaymentPlatform.VENMO,
4934
- PaymentPlatform.PAYPAL,
4935
- PaymentPlatform.CASHAPP
4938
+ PaymentPlatform.PAYPAL
4936
4939
  ];
4937
4940
  new Set(
4938
4941
  DISPUTE_PROTECTION_STAKE_PLATFORMS
@@ -6037,6 +6040,11 @@ var getRateManagerReadFunction = (abi, functionName) => Array.isArray(abi) && ab
6037
6040
  );
6038
6041
 
6039
6042
  // src/client/AccessPolicyOperations.ts
6043
+ var PEER_PAY_MERCHANT_GROUP_ID_BY_ENVIRONMENT = {
6044
+ production: "0x174b8a29536721a3eae290bfd55651b85a53fc334b971d993fa93ed8dde15e48",
6045
+ preproduction: "0x174b8a29536721a3eae290bfd55651b85a53fc334b971d993fa93ed8dde15e48",
6046
+ staging: "0xc82c20c00033046a2f017b65532d7148a337282f17c73296663a530e49ba00f7"
6047
+ };
6040
6048
  var AccessPolicyUnsupportedError = class extends Error {
6041
6049
  constructor(contract) {
6042
6050
  super(`${contract} is not deployed for this environment.`);
@@ -6135,31 +6143,24 @@ var AccessPolicyOperations = class {
6135
6143
  txOverrides
6136
6144
  });
6137
6145
  }
6138
- prepareConfigureDeposit(params) {
6146
+ /** Configure the fixed Peer Pay merchant default while creating a sell deposit. */
6147
+ prepareConfigurePeerPayMerchantDeposit(params) {
6148
+ const runtimeEnv = this.config.getRuntimeEnv?.();
6149
+ if (!runtimeEnv) {
6150
+ throw new Error("Runtime environment is required to configure the Peer Pay merchant policy.");
6151
+ }
6152
+ const merchantGroupId = PEER_PAY_MERCHANT_GROUP_ID_BY_ENVIRONMENT[runtimeEnv];
6139
6153
  return this.preparePolicyCall(
6140
6154
  "configureDeposit",
6141
- [
6142
- params.escrow,
6143
- params.depositId,
6144
- params.paymentMethod,
6145
- params.enabled,
6146
- params.groupIds,
6147
- params.takers
6148
- ],
6155
+ [params.escrow, params.depositId, params.paymentMethod, true, [merchantGroupId], []],
6149
6156
  params.txOverrides
6150
6157
  );
6151
6158
  }
6152
- prepareSetEnabled(params) {
6159
+ /** Fail open before removing historical policy entries. */
6160
+ prepareDisable(params) {
6153
6161
  return this.preparePolicyCall(
6154
6162
  "setEnabled",
6155
- [params.escrow, params.depositId, params.paymentMethod, params.enabled],
6156
- params.txOverrides
6157
- );
6158
- }
6159
- prepareAddAllowedGroups(params) {
6160
- return this.preparePolicyCall(
6161
- "addAllowedGroups",
6162
- [params.escrow, params.depositId, params.paymentMethod, params.groupIds],
6163
+ [params.escrow, params.depositId, params.paymentMethod, false],
6163
6164
  params.txOverrides
6164
6165
  );
6165
6166
  }
@@ -6170,13 +6171,6 @@ var AccessPolicyOperations = class {
6170
6171
  params.txOverrides
6171
6172
  );
6172
6173
  }
6173
- prepareAddWhitelistedAddresses(params) {
6174
- return this.preparePolicyCall(
6175
- "addWhitelistedAddresses",
6176
- [params.escrow, params.depositId, params.takers],
6177
- params.txOverrides
6178
- );
6179
- }
6180
6174
  prepareRemoveWhitelistedAddresses(params) {
6181
6175
  return this.preparePolicyCall(
6182
6176
  "removeWhitelistedAddresses",
@@ -6184,78 +6178,6 @@ var AccessPolicyOperations = class {
6184
6178
  params.txOverrides
6185
6179
  );
6186
6180
  }
6187
- /** Encodes one planner step. */
6188
- preparePlanStep(params) {
6189
- const { escrow, depositId, paymentMethod, step, txOverrides } = params;
6190
- switch (step.kind) {
6191
- case "configureDeposit":
6192
- return this.prepareConfigureDeposit({
6193
- escrow,
6194
- depositId,
6195
- paymentMethod,
6196
- enabled: step.enabled,
6197
- groupIds: step.groupIds,
6198
- takers: step.takers,
6199
- txOverrides
6200
- });
6201
- case "setEnabled":
6202
- return this.prepareSetEnabled({
6203
- escrow,
6204
- depositId,
6205
- paymentMethod,
6206
- enabled: step.enabled,
6207
- txOverrides
6208
- });
6209
- case "addAllowedGroups":
6210
- return this.prepareAddAllowedGroups({
6211
- escrow,
6212
- depositId,
6213
- paymentMethod,
6214
- groupIds: step.groupIds,
6215
- txOverrides
6216
- });
6217
- case "removeAllowedGroups":
6218
- return this.prepareRemoveAllowedGroups({
6219
- escrow,
6220
- depositId,
6221
- paymentMethod,
6222
- groupIds: step.groupIds,
6223
- txOverrides
6224
- });
6225
- case "addWhitelistedAddresses":
6226
- return this.prepareAddWhitelistedAddresses({
6227
- escrow,
6228
- depositId,
6229
- takers: step.takers,
6230
- txOverrides
6231
- });
6232
- case "removeWhitelistedAddresses":
6233
- return this.prepareRemoveWhitelistedAddresses({
6234
- escrow,
6235
- depositId,
6236
- takers: step.takers,
6237
- txOverrides
6238
- });
6239
- }
6240
- }
6241
- /**
6242
- * Encodes a whole plan, in order.
6243
- *
6244
- * A plan with violations encodes to nothing: an invalid draft must be
6245
- * rejected before a wallet is ever opened.
6246
- */
6247
- preparePlan(params) {
6248
- if (params.plan.violations.length > 0) return [];
6249
- return params.plan.steps.map(
6250
- (step) => this.preparePlanStep({
6251
- escrow: params.escrow,
6252
- depositId: params.depositId,
6253
- paymentMethod: params.paymentMethod,
6254
- step,
6255
- txOverrides: params.txOverrides
6256
- })
6257
- );
6258
- }
6259
6181
  };
6260
6182
  var StakeOperations = class {
6261
6183
  constructor(config) {
@@ -7732,10 +7654,10 @@ var IndexerStakingService = class {
7732
7654
  }
7733
7655
  };
7734
7656
 
7735
- // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.4.3/node_modules/@zkp2p/contracts-v2/_esm/index.js
7657
+ // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.5.4/node_modules/@zkp2p/contracts-v2/_esm/index.js
7736
7658
  var version = "0.4.1-rc.9";
7737
7659
 
7738
- // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.4.3/node_modules/@zkp2p/contracts-v2/_esm/disputeStack/base.js
7660
+ // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.5.4/node_modules/@zkp2p/contracts-v2/_esm/disputeStack/base.js
7739
7661
  var data = {
7740
7662
  "schemaVersion": 2,
7741
7663
  "network": "base",
@@ -7905,7 +7827,7 @@ var data = {
7905
7827
  };
7906
7828
  var base_default = data;
7907
7829
 
7908
- // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.4.3/node_modules/@zkp2p/contracts-v2/_esm/disputeStack/baseStaging.js
7830
+ // ../../node_modules/.pnpm/@zkp2p+contracts-v2@0.4.1-rc.9_ethers@6.16.0_bufferutil@4.1.0_utf-8-validate@5.0.10__typescript@5.9.3_zod@4.5.4/node_modules/@zkp2p/contracts-v2/_esm/disputeStack/baseStaging.js
7909
7831
  var data2 = {
7910
7832
  "schemaVersion": 2,
7911
7833
  "network": "base_staging",
@@ -8217,6 +8139,55 @@ function replayAddressAuthorizations(label, events, addressField, enabledField)
8217
8139
  function manifestForEnvironment(environment) {
8218
8140
  return environment === "staging" ? baseStaging_default : base_default;
8219
8141
  }
8142
+ async function readDisputeAttestationConfig({
8143
+ publicClient,
8144
+ chainId,
8145
+ environment = "production"
8146
+ }) {
8147
+ const manifest = manifestForEnvironment(environment);
8148
+ if (manifest.chainId !== chainId) {
8149
+ throw new Error(
8150
+ `Dispute attestation is unavailable for chainId=${chainId}, env=${environment}`
8151
+ );
8152
+ }
8153
+ const asOfBlock = await publicClient.getBlockNumber();
8154
+ const attestationVerifier = manifest.runtimeIdentities.MultiAttestationVerifier.address;
8155
+ const [rawRequiredSignatures, rawTrustedSigners] = await publicClient.multicall({
8156
+ allowFailure: false,
8157
+ blockNumber: asOfBlock,
8158
+ contracts: [
8159
+ {
8160
+ address: attestationVerifier,
8161
+ abi: MultiAttestationVerifier_default,
8162
+ functionName: "requiredSignatures"
8163
+ },
8164
+ {
8165
+ address: attestationVerifier,
8166
+ abi: MultiAttestationVerifier_default,
8167
+ functionName: "witnesses"
8168
+ }
8169
+ ]
8170
+ });
8171
+ const requiredSignatures = typeof rawRequiredSignatures === "bigint" ? Number(rawRequiredSignatures) : Number.NaN;
8172
+ if (!Number.isSafeInteger(requiredSignatures) || requiredSignatures < 1) {
8173
+ throw new Error("Dispute attestation verifier has an invalid signature threshold");
8174
+ }
8175
+ const trustedSigners = normalizeAddressSet(
8176
+ "MultiAttestationVerifier.witnesses",
8177
+ rawTrustedSigners
8178
+ );
8179
+ if (trustedSigners.length < requiredSignatures) {
8180
+ throw new Error("Dispute attestation verifier has fewer witnesses than required signatures");
8181
+ }
8182
+ return {
8183
+ asOfBlock,
8184
+ chainId: manifest.chainId,
8185
+ policyAddress: manifest.runtimeIdentities.DisputeProtectionPolicy.address,
8186
+ verifierAddress: manifest.runtimeIdentities.DisputeVerifier.address,
8187
+ trustedSigners,
8188
+ requiredSignatures
8189
+ };
8190
+ }
8220
8191
  function validatePackagedIdentity(config) {
8221
8192
  const { buildMetadata, chainId, contractsPackageVersion, manifest } = config;
8222
8193
  if (!buildMetadata.source.distributable) return "SDK build metadata is not distributable";
@@ -9101,6 +9072,26 @@ function assertCatalogPaymentMethods(paymentMethods, chainId, runtimeEnv, field)
9101
9072
  }
9102
9073
  });
9103
9074
  }
9075
+ function assertCatalogCurrencies(paymentMethods, currencies, chainId, runtimeEnv, field) {
9076
+ const catalogByHash = new Map(
9077
+ Object.values(getPaymentMethodsCatalog(chainId, runtimeEnv)).map((entry) => [
9078
+ entry.paymentMethodHash.toLowerCase(),
9079
+ new Set(entry.currencies?.map((currency) => currency.toLowerCase()) ?? [])
9080
+ ])
9081
+ );
9082
+ paymentMethods.forEach((paymentMethod, paymentMethodIndex) => {
9083
+ const allowedCurrencies = catalogByHash.get(paymentMethod.toLowerCase());
9084
+ if (!allowedCurrencies?.size) return;
9085
+ currencies[paymentMethodIndex]?.forEach((currency, currencyIndex) => {
9086
+ if (!allowedCurrencies.has(currency.code.toLowerCase())) {
9087
+ throw new ValidationError(
9088
+ `Unsupported currency hash ${currency.code} for payment method ${paymentMethod}`,
9089
+ `${field}[${paymentMethodIndex}][${currencyIndex}].code`
9090
+ );
9091
+ }
9092
+ });
9093
+ });
9094
+ }
9104
9095
  var Zkp2pClient = class {
9105
9096
  /**
9106
9097
  * Creates a new Zkp2pClient instance.
@@ -10214,6 +10205,7 @@ var Zkp2pClient = class {
10214
10205
  });
10215
10206
  this._accessPolicyOps = new AccessPolicyOperations({
10216
10207
  getPublicClient: () => this.publicClient,
10208
+ getRuntimeEnv: () => this.runtimeEnv,
10217
10209
  getPolicyAddress: () => this.whitelistPolicyAddress,
10218
10210
  getPolicyAbi: () => this.whitelistPolicyAbi,
10219
10211
  getRegistryAddress: () => this.addressGroupRegistryAddress,
@@ -11403,6 +11395,13 @@ var Zkp2pClient = class {
11403
11395
  this.runtimeEnv,
11404
11396
  "paymentMethodsOverride"
11405
11397
  );
11398
+ assertCatalogCurrencies(
11399
+ params.paymentMethodsOverride,
11400
+ params.currenciesOverride,
11401
+ this.chainId,
11402
+ this.runtimeEnv,
11403
+ "currenciesOverride"
11404
+ );
11406
11405
  paymentMethods = params.paymentMethodsOverride;
11407
11406
  paymentMethodData = params.paymentMethodDataOverride;
11408
11407
  currencies = params.currenciesOverride;
@@ -11448,7 +11447,7 @@ var Zkp2pClient = class {
11448
11447
  }
11449
11448
  }
11450
11449
  });
11451
- const { mapConversionRatesToOnchainMinRate: mapConversionRatesToOnchainMinRate2 } = await import('./currency-CTXWPQTT.mjs');
11450
+ const { mapConversionRatesToOnchainMinRate: mapConversionRatesToOnchainMinRate2 } = await import('./currency-5W2J2RG5.mjs');
11452
11451
  currencies = mapConversionRatesToOnchainMinRate2(
11453
11452
  params.conversionRates,
11454
11453
  paymentMethods.length
@@ -12147,162 +12146,6 @@ function selectRiskMode(amount, freeStake, disputeProtected) {
12147
12146
  throw new RangeError("insufficient free stake for dispute-protected admission");
12148
12147
  }
12149
12148
 
12150
- // src/client/accessPolicyPlan.ts
12151
- var MAX_GROUPS_PER_DEPOSIT_PAYMENT_METHOD = 10;
12152
- var MAX_ADDRESSES_PER_CALL = 50;
12153
- var MAX_WHITELISTED_ADDRESSES = 500;
12154
- var chunk = (values, size) => {
12155
- if (values.length <= size) return values.length > 0 ? [values] : [];
12156
- const batches = [];
12157
- for (let index = 0; index < values.length; index += size) {
12158
- batches.push(values.slice(index, index + size));
12159
- }
12160
- return batches;
12161
- };
12162
- var normalizeList = (values) => {
12163
- const seen = /* @__PURE__ */ new Set();
12164
- const normalized = [];
12165
- for (const value of values) {
12166
- if (typeof value !== "string") continue;
12167
- const trimmed = value.trim().toLowerCase();
12168
- if (!trimmed || seen.has(trimmed)) continue;
12169
- seen.add(trimmed);
12170
- normalized.push(trimmed);
12171
- }
12172
- return normalized;
12173
- };
12174
- var normalizeAccessPolicyState = (state) => ({
12175
- enabled: Boolean(state.enabled),
12176
- groupIds: normalizeList(state.groupIds),
12177
- addresses: normalizeList(state.addresses)
12178
- });
12179
- var difference = (left, right) => {
12180
- const exclude = new Set(right);
12181
- return left.filter((value) => !exclude.has(value));
12182
- };
12183
- var diffAccessPolicy = (persistedInput, draftInput) => {
12184
- const persisted = normalizeAccessPolicyState(persistedInput);
12185
- const draft = normalizeAccessPolicyState(draftInput);
12186
- return {
12187
- addedGroupIds: difference(draft.groupIds, persisted.groupIds),
12188
- removedGroupIds: difference(persisted.groupIds, draft.groupIds),
12189
- addedAddresses: difference(draft.addresses, persisted.addresses),
12190
- removedAddresses: difference(persisted.addresses, draft.addresses),
12191
- enabledChanged: persisted.enabled !== draft.enabled
12192
- };
12193
- };
12194
- var planAccessPolicyUpdate = (persistedInput, draftInput) => {
12195
- const persisted = normalizeAccessPolicyState(persistedInput);
12196
- const draft = normalizeAccessPolicyState(draftInput);
12197
- const diff = diffAccessPolicy(persisted, draft);
12198
- const hasChanges = diff.enabledChanged || diff.addedGroupIds.length > 0 || diff.removedGroupIds.length > 0 || diff.addedAddresses.length > 0 || diff.removedAddresses.length > 0;
12199
- const violations = [];
12200
- if (draft.enabled && draft.groupIds.length === 0 && draft.addresses.length === 0) {
12201
- violations.push("empty-restricted-policy");
12202
- }
12203
- if (draft.groupIds.length > MAX_GROUPS_PER_DEPOSIT_PAYMENT_METHOD) {
12204
- violations.push("group-cap-exceeded");
12205
- }
12206
- if (draft.addresses.length > MAX_WHITELISTED_ADDRESSES) {
12207
- violations.push("address-cap-exceeded");
12208
- }
12209
- if (!hasChanges || violations.length > 0) {
12210
- return {
12211
- diff,
12212
- steps: [],
12213
- hasChanges,
12214
- ordering: hasChanges ? "additions-first" : "no-changes",
12215
- violations,
12216
- resultingGroupCount: draft.groupIds.length
12217
- };
12218
- }
12219
- const peakIfAddingFirst = (/* @__PURE__ */ new Set([...persisted.groupIds, ...diff.addedGroupIds])).size;
12220
- const mustRemoveGroupsFirst = peakIfAddingFirst > MAX_GROUPS_PER_DEPOSIT_PAYMENT_METHOD;
12221
- const ordering = !draft.enabled ? "disable-first" : mustRemoveGroupsFirst ? "removals-first" : "additions-first";
12222
- const steps = [];
12223
- const additionSteps = () => {
12224
- const collected = [];
12225
- if (diff.addedGroupIds.length > 0) {
12226
- collected.push({
12227
- kind: "addAllowedGroups",
12228
- groupIds: diff.addedGroupIds
12229
- });
12230
- }
12231
- for (const batch of chunk(diff.addedAddresses, MAX_ADDRESSES_PER_CALL)) {
12232
- collected.push({ kind: "addWhitelistedAddresses", takers: batch });
12233
- }
12234
- return collected;
12235
- };
12236
- const removalSteps = () => {
12237
- const collected = [];
12238
- if (diff.removedGroupIds.length > 0) {
12239
- collected.push({
12240
- kind: "removeAllowedGroups",
12241
- groupIds: diff.removedGroupIds
12242
- });
12243
- }
12244
- for (const batch of chunk(diff.removedAddresses, MAX_ADDRESSES_PER_CALL)) {
12245
- collected.push({ kind: "removeWhitelistedAddresses", takers: batch });
12246
- }
12247
- return collected;
12248
- };
12249
- if (ordering === "disable-first") {
12250
- if (diff.enabledChanged) {
12251
- steps.push({ kind: "setEnabled", enabled: false });
12252
- }
12253
- steps.push(...removalSteps(), ...additionSteps());
12254
- return {
12255
- diff,
12256
- steps,
12257
- hasChanges,
12258
- ordering,
12259
- violations,
12260
- resultingGroupCount: draft.groupIds.length
12261
- };
12262
- }
12263
- if (ordering === "removals-first") {
12264
- if (persisted.enabled) {
12265
- steps.push({ kind: "setEnabled", enabled: false });
12266
- }
12267
- steps.push(...removalSteps(), ...additionSteps());
12268
- steps.push({ kind: "setEnabled", enabled: true });
12269
- return {
12270
- diff,
12271
- steps,
12272
- hasChanges,
12273
- ordering,
12274
- violations,
12275
- resultingGroupCount: draft.groupIds.length
12276
- };
12277
- }
12278
- if (diff.enabledChanged) {
12279
- const [firstBatch = [], ...overflowBatches] = chunk(
12280
- diff.addedAddresses,
12281
- MAX_ADDRESSES_PER_CALL
12282
- );
12283
- steps.push({
12284
- kind: "configureDeposit",
12285
- enabled: true,
12286
- groupIds: diff.addedGroupIds,
12287
- takers: firstBatch
12288
- });
12289
- for (const batch of overflowBatches) {
12290
- steps.push({ kind: "addWhitelistedAddresses", takers: batch });
12291
- }
12292
- } else {
12293
- steps.push(...additionSteps());
12294
- }
12295
- steps.push(...removalSteps());
12296
- return {
12297
- diff,
12298
- steps,
12299
- hasChanges,
12300
- ordering,
12301
- violations,
12302
- resultingGroupCount: draft.groupIds.length
12303
- };
12304
- };
12305
-
12306
- export { AccessPolicyOperations, AccessPolicyUnsupportedError, BASE_BUILDER_CODE, CHAINLINK_ORACLE_ADAPTER, CHAINLINK_ORACLE_FEEDS, ContractRouter, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, IndexerClient, IndexerDepositService, IndexerRateManagerService, IndexerStakingService, MAX_ADDRESSES_PER_CALL, MAX_GROUPS_PER_DEPOSIT_PAYMENT_METHOD, MAX_WHITELISTED_ADDRESSES, Zkp2pClient as OfframpClient, PEER_EXTENSION_CHROME_URL, PLATFORM_METADATA, PYTH_CONTRACT_BASE, PYTH_ORACLE_ADAPTER, PYTH_ORACLE_FEEDS, REFERRAL_SIGNATURE_DOMAIN, REFERRAL_SIGNATURE_TYPES, RISK_BPS_DENOMINATOR, SDK_BUILD_METADATA, SPREAD_ORACLE_FEEDS, SUPPORTED_CHAIN_IDS, TOKEN_METADATA, ZKP2P_ANDROID_REFERRER, ZKP2P_IOS_REFERRER, Zkp2pClient, apiCreateReferralCode, apiCreateSellerCredentialBundle, apiGetDepositBundle, apiGetOrderbook, apiGetOrderbookTable, apiGetOwnerDeposits, apiGetPayeeDetails, apiGetQuote, apiGetQuotesBestByPlatform, apiGetReferralDashboard, apiGetReferralEarnings, apiLookupReferralCode, apiPostDepositDetails, apiRedeemReferralCode, apiRequestIdentityAttestation, apiSignIntentV3, apiSignIntentV3Raw, apiUpdateReferralCode, apiUploadGoogleOAuthSellerCredential, apiUploadSellerCredentialBundle, apiValidatePayeeDetails, apiVerifyBuyerTeePayment, appendAttributionToCalldata, assertValidReferrerFeeConfig, buildStakingEntityIds, calculateRequiredCoverage, calculateStakeBackedCapacity, compareEventCursorIdsByRecency, convertDepositsForLiquidity, convertIndexerDepositToEscrowView, convertIndexerIntentsToEscrowViews, createCompositeDepositId, createEncryptedBuyerTeeSessionMaterial, createPeerExtensionSdk, defaultIndexerEndpoint, diffAccessPolicy, encodePythAdapterConfig, encodeSpreadOracleAdapterConfig, encodeWithAttribution, fetchFulfillmentAndPayment as fetchIndexerFulfillmentAndPayment, getAttributionDataSuffix, getPeerExtensionState, getSpreadOracleConfig, isPeerExtensionAvailable, isValidReferralCode, isValidReferrerFeeBps, isValidReferrerFeeRecipient, logger, normalizeAccessPolicyState, normalizeReferralCode, openPeerExtensionInstallPage, parseReferrerFeeConfig, peerExtensionSdk, planAccessPolicyUpdate, referrerFeeConfigToPreciseUnits, selectRiskMode, sendTransactionWithAttribution, setLogLevel, validateOracleFeedsOnChain };
12149
+ export { AccessPolicyOperations, AccessPolicyUnsupportedError, BASE_BUILDER_CODE, CHAINLINK_ORACLE_ADAPTER, CHAINLINK_ORACLE_FEEDS, ContractRouter, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, IndexerClient, IndexerDepositService, IndexerRateManagerService, IndexerStakingService, Zkp2pClient as OfframpClient, PEER_EXTENSION_CHROME_URL, PLATFORM_METADATA, PYTH_CONTRACT_BASE, PYTH_ORACLE_ADAPTER, PYTH_ORACLE_FEEDS, REFERRAL_SIGNATURE_DOMAIN, REFERRAL_SIGNATURE_TYPES, RISK_BPS_DENOMINATOR, SDK_BUILD_METADATA, SPREAD_ORACLE_FEEDS, SUPPORTED_CHAIN_IDS, TOKEN_METADATA, ZKP2P_ANDROID_REFERRER, ZKP2P_IOS_REFERRER, Zkp2pClient, apiCreateReferralCode, apiCreateSellerCredentialBundle, apiGetDepositBundle, apiGetOrderbook, apiGetOrderbookTable, apiGetOwnerDeposits, apiGetPayeeDetails, apiGetQuote, apiGetQuotesBestByPlatform, apiGetReferralDashboard, apiGetReferralEarnings, apiLookupReferralCode, apiPostDepositDetails, apiRedeemReferralCode, apiRequestIdentityAttestation, apiSignIntentV3, apiSignIntentV3Raw, apiUpdateReferralCode, apiUploadGoogleOAuthSellerCredential, apiUploadSellerCredentialBundle, apiValidatePayeeDetails, apiVerifyBuyerTeePayment, appendAttributionToCalldata, assertValidReferrerFeeConfig, buildStakingEntityIds, calculateRequiredCoverage, calculateStakeBackedCapacity, compareEventCursorIdsByRecency, convertDepositsForLiquidity, convertIndexerDepositToEscrowView, convertIndexerIntentsToEscrowViews, createCompositeDepositId, createEncryptedBuyerTeeSessionMaterial, createPeerExtensionSdk, defaultIndexerEndpoint, encodePythAdapterConfig, encodeSpreadOracleAdapterConfig, encodeWithAttribution, fetchFulfillmentAndPayment as fetchIndexerFulfillmentAndPayment, getAttributionDataSuffix, getPeerExtensionState, getSpreadOracleConfig, isPeerExtensionAvailable, isValidReferralCode, isValidReferrerFeeBps, isValidReferrerFeeRecipient, logger, normalizeReferralCode, openPeerExtensionInstallPage, parseReferrerFeeConfig, peerExtensionSdk, readDisputeAttestationConfig, referrerFeeConfigToPreciseUnits, selectRiskMode, sendTransactionWithAttribution, setLogLevel, validateOracleFeedsOnChain };
12307
12150
  //# sourceMappingURL=index.mjs.map
12308
12151
  //# sourceMappingURL=index.mjs.map