@zkp2p/sdk 0.11.2 → 0.12.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,12 +2,12 @@ import { IntentGuardianOperations } from './chunk-FCOH36IX.mjs';
2
2
  export { ZERO_RATE_MANAGER_ID, classifyDelegationState, classifyIntentGuardianError, getDelegationRoute, isZeroRateManagerId, normalizeRateManagerId, normalizeRegistry } from './chunk-FCOH36IX.mjs';
3
3
  import { NetworkError, ValidationError, APIError } from './chunk-GHQK65J2.mjs';
4
4
  export { APIError, ContractError, ErrorCode, NetworkError, ValidationError, ZKP2PError } from './chunk-GHQK65J2.mjs';
5
- import { METHOD_NAME_TO_HASH, matchesQuotePaymentMethod, matchesPaymentMethodNameAndHash, getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, SUPPORTED_PAYMENT_METHOD_HASHES, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash } from './chunk-LPKFXAKY.mjs';
6
- export { PAYMENT_PLATFORMS, asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getContracts, getGatingServiceAddress, getIntentGuardianContract, getPaymentMethodsCatalog, getRateManagerContracts, hasIntentGuardian, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-LPKFXAKY.mjs';
5
+ import { METHOD_NAME_TO_HASH, matchesQuotePaymentMethod, matchesPaymentMethodNameAndHash, getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, SUPPORTED_PAYMENT_METHOD_HASHES, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash } from './chunk-RYBXFY6X.mjs';
6
+ export { CHARGEBACK_POLICY_ABI, ORCHESTRATOR_V3_ABI, PAYMENT_PLATFORMS, STAKE_VAULT_ABI, asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getChargebackPolicyContract, getContracts, getGatingServiceAddress, getIntentGuardianContract, getOrchestratorV3Contract, getPaymentMethodsCatalog, getRateManagerContracts, getStakeVaultContract, hasIntentGuardian, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-RYBXFY6X.mjs';
7
7
  import { Currency, currencyKeccak256 } from './chunk-ZFBH4HD7.mjs';
8
8
  export { Currency, currencyInfo, getCurrencyCodeFromHash, getCurrencyInfoFromCountryCode, getCurrencyInfoFromHash, isSupportedCurrencyHash, mapConversionRatesToOnchainMinRate } from './chunk-ZFBH4HD7.mjs';
9
9
  import './chunk-J5LGTIGS.mjs';
10
- import { concatHex, encodeFunctionData, encodeAbiParameters, createPublicClient, http, formatUnits } from 'viem';
10
+ import { 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
13
  export { createNitroAttestationClient } from '@zkp2p/zkp2p-attestation';
@@ -1898,7 +1898,7 @@ var ProtocolViewerReader = class {
1898
1898
  if (inputCount === null) {
1899
1899
  throw new Error("Configured ProtocolViewer ABI does not expose getDeposit");
1900
1900
  }
1901
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-M7C2ICV3.mjs');
1901
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-LCSRVC7F.mjs');
1902
1902
  if (inputCount >= 3) {
1903
1903
  return tryContexts(
1904
1904
  protocolViewerContexts,
@@ -1984,7 +1984,7 @@ var ProtocolViewerReader = class {
1984
1984
  return Promise.all(ids.map((id) => this.config.host.getPvDepositById(id)));
1985
1985
  }
1986
1986
  const bn = ids.map((id) => typeof id === "bigint" ? id : parseRawDepositId(id));
1987
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-M7C2ICV3.mjs');
1987
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-LCSRVC7F.mjs');
1988
1988
  if (inputCount >= 2) {
1989
1989
  const requests = ids.map((id, index) => ({
1990
1990
  index,
@@ -2089,7 +2089,7 @@ var ProtocolViewerReader = class {
2089
2089
  if (!protocolViewerAddress || !protocolViewerAbi || inputCount === null) {
2090
2090
  return this.config.host.getPvAccountDepositsFromIndexer(owner);
2091
2091
  }
2092
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-M7C2ICV3.mjs');
2092
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-LCSRVC7F.mjs');
2093
2093
  const { address, abi } = this.config.host.requireProtocolViewer();
2094
2094
  if (inputCount >= 2) {
2095
2095
  const readAndFilter = async (raw2) => {
@@ -2160,7 +2160,7 @@ var ProtocolViewerReader = class {
2160
2160
  if (protocolViewerEntries.length === 0) {
2161
2161
  throw new Error("ProtocolViewer not available for this network");
2162
2162
  }
2163
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-M7C2ICV3.mjs');
2163
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-LCSRVC7F.mjs');
2164
2164
  const intentsByHash = /* @__PURE__ */ new Map();
2165
2165
  let attemptedRead = false;
2166
2166
  let hadSuccessfulRead = false;
@@ -2268,7 +2268,7 @@ var ProtocolViewerReader = class {
2268
2268
  if (protocolViewerEntries.length === 0) {
2269
2269
  throw new Error("ProtocolViewer not available for this network");
2270
2270
  }
2271
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-M7C2ICV3.mjs');
2271
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-LCSRVC7F.mjs');
2272
2272
  let lastError;
2273
2273
  for (const pvEntry of protocolViewerEntries) {
2274
2274
  const inputCount = this.pvEntryFunctionInputCount(pvEntry, "getIntent");
@@ -3559,6 +3559,68 @@ var FULFILLMENT_AND_PAYMENT_QUERY = (
3559
3559
  }
3560
3560
  `
3561
3561
  );
3562
+ var STAKING_STATE_QUERY = (
3563
+ /* GraphQL */
3564
+ `
3565
+ query StakingState(
3566
+ $takerStateId: String!
3567
+ $stakeAccountId: String!
3568
+ $claimAccountId: String!
3569
+ $vaultConfigId: String!
3570
+ $chainId: Int!
3571
+ $vault: String!
3572
+ $taker: String!
3573
+ $policy: String!
3574
+ ) {
3575
+ TakerStakeState_by_pk(id: $takerStateId) {
3576
+ taker
3577
+ stakeOwner
3578
+ selectedStakeOwner
3579
+ selectionAuthorized
3580
+ updatedAtBlockNumber
3581
+ updatedAt
3582
+ }
3583
+ StakeAccountState_by_pk(id: $stakeAccountId) {
3584
+ stakeOwner
3585
+ totalStake
3586
+ lockedStake
3587
+ freeStake
3588
+ updatedAtBlockNumber
3589
+ updatedAt
3590
+ }
3591
+ ClaimAccountState_by_pk(id: $claimAccountId) {
3592
+ beneficiary
3593
+ claimableAmount
3594
+ updatedAtBlockNumber
3595
+ updatedAt
3596
+ }
3597
+ TakerStakeAuthorization(
3598
+ where: { chainId: { _eq: $chainId }, vaultAddress: { _eq: $vault }, taker: { _eq: $taker } }
3599
+ order_by: { updatedAt: desc }
3600
+ ) {
3601
+ stakeOwner
3602
+ authorized
3603
+ updatedAtBlockNumber
3604
+ updatedAt
3605
+ }
3606
+ ChargebackRiskWindow(
3607
+ where: { chainId: { _eq: $chainId }, policyAddress: { _eq: $policy } }
3608
+ order_by: { paymentMethod: asc }
3609
+ ) {
3610
+ paymentMethod
3611
+ riskWindow
3612
+ updatedAt
3613
+ }
3614
+ StakeVaultConfig_by_pk(id: $vaultConfigId) {
3615
+ controller
3616
+ pendingController
3617
+ pendingControllerValidAt
3618
+ updatedAtBlockNumber
3619
+ updatedAt
3620
+ }
3621
+ }
3622
+ `
3623
+ );
3562
3624
 
3563
3625
  // src/indexer/converters.ts
3564
3626
  var ZERO = "0x0000000000000000000000000000000000000000";
@@ -5453,6 +5515,110 @@ var AccessPolicyOperations = class {
5453
5515
  );
5454
5516
  }
5455
5517
  };
5518
+ var StakeOperations = class {
5519
+ constructor(config) {
5520
+ this.config = config;
5521
+ }
5522
+ getContract() {
5523
+ const address = this.config.getStakeVaultAddress();
5524
+ const abi = this.config.getStakeVaultAbi();
5525
+ const stakeToken = this.config.getStakeTokenAddress();
5526
+ if (!address || !abi || !stakeToken) {
5527
+ throw new Error("StakeVault not available for this chain/environment");
5528
+ }
5529
+ return { address, abi, stakeToken };
5530
+ }
5531
+ getPolicyContract() {
5532
+ const address = this.config.getChargebackPolicyAddress();
5533
+ const abi = this.config.getChargebackPolicyAbi();
5534
+ if (!address || !abi) {
5535
+ throw new Error("ChargebackPolicy not available for this chain/environment");
5536
+ }
5537
+ return { address, abi };
5538
+ }
5539
+ read(functionName, args = []) {
5540
+ const { address, abi } = this.getContract();
5541
+ return this.config.getPublicClient().readContract({
5542
+ address,
5543
+ abi,
5544
+ functionName,
5545
+ args
5546
+ });
5547
+ }
5548
+ readPolicy(functionName, args = []) {
5549
+ const { address, abi } = this.getPolicyContract();
5550
+ return this.config.getPublicClient().readContract({
5551
+ address,
5552
+ abi,
5553
+ functionName,
5554
+ args
5555
+ });
5556
+ }
5557
+ getStakeBalance(stakeOwner) {
5558
+ return this.read("stakeBalance", [stakeOwner]);
5559
+ }
5560
+ getLockedStake(stakeOwner) {
5561
+ return this.read("lockedStake", [stakeOwner]);
5562
+ }
5563
+ getFreeStake(stakeOwner) {
5564
+ return this.read("freeStake", [stakeOwner]);
5565
+ }
5566
+ getClaimable(beneficiary) {
5567
+ return this.read("claimable", [beneficiary]);
5568
+ }
5569
+ getStakeOwner(taker) {
5570
+ return this.read("stakeOwnerOf", [taker]);
5571
+ }
5572
+ getSelectedStakeOwner(taker) {
5573
+ return this.read("selectedStakeOwner", [taker]);
5574
+ }
5575
+ getTakerAuthorization(stakeOwner, taker) {
5576
+ return this.read("authorizedTakers", [stakeOwner, taker]);
5577
+ }
5578
+ /** Whether the policy is refusing new chargebackable admissions. */
5579
+ getAdmissionsPaused() {
5580
+ return this.readPolicy("admissionsPaused");
5581
+ }
5582
+ /**
5583
+ * Minimum collateral lock window for a payment method, in seconds. Zero
5584
+ * means intents on this method admit unbonded — no stake is locked at all.
5585
+ */
5586
+ getRiskWindow(paymentMethodHash) {
5587
+ return this.readPolicy("getRiskWindow", [paymentMethodHash]);
5588
+ }
5589
+ /** Whether a specific escrow deposit has opted into chargeback coverage. */
5590
+ isChargebackEnabled(escrow, depositId) {
5591
+ return this.readPolicy("isChargebackEnabled", [escrow, depositId]);
5592
+ }
5593
+ async getStakeVaultState(params) {
5594
+ const taker = params.taker ?? params.staker;
5595
+ const { stakeToken } = this.getContract();
5596
+ const [stakeOwner, rawSelection, staked, locked, free, claimable, admissionsPaused] = await Promise.all([
5597
+ this.getStakeOwner(taker),
5598
+ this.getSelectedStakeOwner(taker),
5599
+ this.getStakeBalance(params.staker),
5600
+ this.getLockedStake(params.staker),
5601
+ this.getFreeStake(params.staker),
5602
+ this.getClaimable(params.staker),
5603
+ this.getAdmissionsPaused()
5604
+ ]);
5605
+ const selectedStakeOwner = rawSelection === zeroAddress ? null : rawSelection;
5606
+ const selectionAuthorized = selectedStakeOwner ? await this.getTakerAuthorization(selectedStakeOwner, taker) : false;
5607
+ return {
5608
+ staker: params.staker,
5609
+ taker,
5610
+ stakeToken,
5611
+ stakeOwner,
5612
+ selectedStakeOwner,
5613
+ selectionAuthorized,
5614
+ staked,
5615
+ locked,
5616
+ free,
5617
+ claimable,
5618
+ admissionsPaused
5619
+ };
5620
+ }
5621
+ };
5456
5622
 
5457
5623
  // src/indexer/rateManagerService.ts
5458
5624
  var DEFAULT_LIMIT2 = 50;
@@ -6172,6 +6338,168 @@ var IndexerRateManagerService = class {
6172
6338
  }
6173
6339
  }
6174
6340
  };
6341
+ var ZERO_STAKE = {
6342
+ totalUsdc: "0",
6343
+ lockedUsdc: "0",
6344
+ freeUsdc: "0"
6345
+ };
6346
+ function normalizeAddress4(value, field) {
6347
+ if (!isAddress(value)) {
6348
+ throw new ValidationError(`${field} must be a valid Ethereum address`, field);
6349
+ }
6350
+ return value.toLowerCase();
6351
+ }
6352
+ function normalizeNullableAddress(value, field) {
6353
+ return value ? normalizeAddress4(value, field) : null;
6354
+ }
6355
+ function normalizeDecimal(value, field) {
6356
+ if (!/^\d+$/.test(value)) {
6357
+ throw new Error(`${field} must be an unsigned decimal string`);
6358
+ }
6359
+ return value;
6360
+ }
6361
+ function freshnessOf(row, field) {
6362
+ if (!row) return null;
6363
+ return {
6364
+ updatedAtBlockNumber: normalizeDecimal(
6365
+ row.updatedAtBlockNumber,
6366
+ `${field}.updatedAtBlockNumber`
6367
+ ),
6368
+ updatedAt: normalizeDecimal(row.updatedAt, `${field}.updatedAt`)
6369
+ };
6370
+ }
6371
+ function minimumBlockNumber(rows) {
6372
+ const blockNumbers = rows.filter((row) => row !== null).map((row) => BigInt(row.updatedAtBlockNumber));
6373
+ if (blockNumbers.length === 0) return null;
6374
+ return blockNumbers.reduce((minimum, block) => block < minimum ? block : minimum).toString();
6375
+ }
6376
+ function buildStakingEntityIds(params) {
6377
+ if (!Number.isInteger(params.chainId) || params.chainId <= 0) {
6378
+ throw new ValidationError("chainId must be a positive integer", "chainId");
6379
+ }
6380
+ const vaultAddress = normalizeAddress4(params.vaultAddress, "vaultAddress");
6381
+ const chargebackPolicyAddress = normalizeAddress4(
6382
+ params.chargebackPolicyAddress,
6383
+ "chargebackPolicyAddress"
6384
+ );
6385
+ const taker = normalizeAddress4(params.taker, "taker");
6386
+ const stakeOwner = normalizeAddress4(params.stakeOwner, "stakeOwner");
6387
+ return {
6388
+ takerStateId: `${params.chainId}_${vaultAddress}_${taker}`,
6389
+ stakeAccountId: `${params.chainId}_${vaultAddress}_${stakeOwner}`,
6390
+ claimAccountId: `${params.chainId}_${vaultAddress}_${taker}`,
6391
+ vaultConfigId: `${params.chainId}_${vaultAddress}`,
6392
+ policy: chargebackPolicyAddress
6393
+ };
6394
+ }
6395
+ var IndexerStakingService = class {
6396
+ constructor(client) {
6397
+ this.client = client;
6398
+ }
6399
+ async fetchStakingState(params, init) {
6400
+ const ids = buildStakingEntityIds(params);
6401
+ const vaultAddress = normalizeAddress4(params.vaultAddress, "vaultAddress");
6402
+ const taker = normalizeAddress4(params.taker, "taker");
6403
+ const requestedStakeOwner = normalizeAddress4(params.stakeOwner, "stakeOwner");
6404
+ const data = await this.client.query(
6405
+ {
6406
+ query: STAKING_STATE_QUERY,
6407
+ variables: {
6408
+ ...ids,
6409
+ chainId: params.chainId,
6410
+ vault: vaultAddress,
6411
+ taker
6412
+ }
6413
+ },
6414
+ init
6415
+ );
6416
+ const takerState = data.TakerStakeState_by_pk;
6417
+ const indexedStakeOwner = takerState ? normalizeAddress4(takerState.stakeOwner, "TakerStakeState.stakeOwner") : taker;
6418
+ const selectedStakeOwner = normalizeNullableAddress(
6419
+ takerState?.selectedStakeOwner,
6420
+ "TakerStakeState.selectedStakeOwner"
6421
+ );
6422
+ const stakeAccount = data.StakeAccountState_by_pk;
6423
+ const stakeAccountOwner = stakeAccount ? normalizeAddress4(stakeAccount.stakeOwner, "StakeAccountState.stakeOwner") : requestedStakeOwner;
6424
+ const stakeAccountMatchesEffectiveOwner = requestedStakeOwner === indexedStakeOwner && stakeAccountOwner === indexedStakeOwner;
6425
+ const claimAccount = data.ClaimAccountState_by_pk;
6426
+ if (claimAccount && normalizeAddress4(claimAccount.beneficiary, "ClaimAccountState.beneficiary") !== taker) {
6427
+ throw new Error("ClaimAccountState beneficiary does not match the requested taker");
6428
+ }
6429
+ const authorizations = data.TakerStakeAuthorization.map((authorization, index) => ({
6430
+ stakeOwner: normalizeAddress4(
6431
+ authorization.stakeOwner,
6432
+ `TakerStakeAuthorization[${index}].stakeOwner`
6433
+ ),
6434
+ authorized: authorization.authorized,
6435
+ freshness: freshnessOf(
6436
+ authorization,
6437
+ `TakerStakeAuthorization[${index}]`
6438
+ )
6439
+ }));
6440
+ const riskWindows = data.ChargebackRiskWindow.map((row, index) => ({
6441
+ paymentMethod: row.paymentMethod,
6442
+ riskWindowSeconds: normalizeDecimal(
6443
+ row.riskWindow,
6444
+ `ChargebackRiskWindow[${index}].riskWindow`
6445
+ ),
6446
+ updatedAt: normalizeDecimal(row.updatedAt, `ChargebackRiskWindow[${index}].updatedAt`)
6447
+ }));
6448
+ const takerFreshness = freshnessOf(takerState, "TakerStakeState");
6449
+ const stakeFreshness = freshnessOf(stakeAccount, "StakeAccountState");
6450
+ const claimFreshness = freshnessOf(claimAccount, "ClaimAccountState");
6451
+ const vaultFreshness = freshnessOf(data.StakeVaultConfig_by_pk, "StakeVaultConfig");
6452
+ const authorizationFreshness = authorizations.map((authorization) => authorization.freshness);
6453
+ return {
6454
+ chainId: params.chainId,
6455
+ environment: params.environment,
6456
+ taker,
6457
+ stakeOwner: indexedStakeOwner,
6458
+ selectedStakeOwner,
6459
+ selectionAuthorized: takerState?.selectionAuthorized ?? false,
6460
+ stake: stakeAccount && stakeAccountMatchesEffectiveOwner ? {
6461
+ totalUsdc: normalizeDecimal(stakeAccount.totalStake, "StakeAccountState.totalStake"),
6462
+ lockedUsdc: normalizeDecimal(
6463
+ stakeAccount.lockedStake,
6464
+ "StakeAccountState.lockedStake"
6465
+ ),
6466
+ freeUsdc: normalizeDecimal(stakeAccount.freeStake, "StakeAccountState.freeStake")
6467
+ } : { ...ZERO_STAKE },
6468
+ claimableUsdc: claimAccount ? normalizeDecimal(claimAccount.claimableAmount, "ClaimAccountState.claimableAmount") : "0",
6469
+ authorizations,
6470
+ riskWindows,
6471
+ vault: data.StakeVaultConfig_by_pk ? {
6472
+ controller: normalizeNullableAddress(
6473
+ data.StakeVaultConfig_by_pk.controller,
6474
+ "StakeVaultConfig.controller"
6475
+ ),
6476
+ pendingController: normalizeNullableAddress(
6477
+ data.StakeVaultConfig_by_pk.pendingController,
6478
+ "StakeVaultConfig.pendingController"
6479
+ ),
6480
+ pendingControllerValidAt: data.StakeVaultConfig_by_pk.pendingControllerValidAt ? normalizeDecimal(
6481
+ data.StakeVaultConfig_by_pk.pendingControllerValidAt,
6482
+ "StakeVaultConfig.pendingControllerValidAt"
6483
+ ) : null
6484
+ } : null,
6485
+ stakeAccountMatchesEffectiveOwner,
6486
+ freshness: {
6487
+ takerStakeState: takerFreshness,
6488
+ stakeAccountState: stakeFreshness,
6489
+ claimAccountState: claimFreshness,
6490
+ stakeVaultConfig: vaultFreshness,
6491
+ authorizations: authorizationFreshness,
6492
+ indexedBlockNumber: minimumBlockNumber([
6493
+ takerFreshness,
6494
+ stakeFreshness,
6495
+ claimFreshness,
6496
+ vaultFreshness,
6497
+ ...authorizationFreshness
6498
+ ])
6499
+ }
6500
+ };
6501
+ }
6502
+ };
6175
6503
 
6176
6504
  // src/indexer/intentVerification.ts
6177
6505
  async function fetchFulfillmentAndPayment(client, intentHash) {
@@ -6518,6 +6846,41 @@ var Zkp2pClient = class {
6518
6846
  * @throws Error if walletClient is missing an account
6519
6847
  */
6520
6848
  constructor(opts) {
6849
+ /** Deposit USDC stake owned by the transaction sender. */
6850
+ this.depositStake = this.buildStakeVaultMethod(
6851
+ "depositStake",
6852
+ (params) => [params.amount]
6853
+ );
6854
+ /** Withdraw the sender's free stake immediately; locked stake cannot move. */
6855
+ this.withdrawStake = this.buildStakeVaultMethod(
6856
+ "withdrawStake",
6857
+ (params) => [params.amount]
6858
+ );
6859
+ /** Withdraw the sender's complete claimable USDC balance. */
6860
+ this.claim = this.buildStakeVaultMethod("claim", () => []);
6861
+ /** Grant or revoke a taker's access to the sender's stake. */
6862
+ this.setTakerAuthorization = this.buildStakeVaultMethod("setTakerAuthorization", (params) => [params.taker, params.authorized]);
6863
+ /** Select the authorizing stake owner that backs the connected taker. */
6864
+ this.selectStakeOwner = this.buildStakeVaultMethod(
6865
+ "selectStakeOwner",
6866
+ (params) => [params.stakeOwner]
6867
+ );
6868
+ /** Clear the connected taker's selection and return to self-stake. */
6869
+ this.clearStakeOwner = this.buildStakeVaultMethod(
6870
+ "clearStakeOwner",
6871
+ () => []
6872
+ );
6873
+ /**
6874
+ * Release one chargeback intent whose risk window matured, unlocking its
6875
+ * stake cover. Permissionless once mature. Pass `chargebackPolicyAddress` to
6876
+ * pin the transaction to a snapshotted deployment.
6877
+ */
6878
+ this.releaseMaturedChargebackIntent = this.buildChargebackPolicyMethod("releaseMaturedChargebackIntent", (params) => [params.intentHash]);
6879
+ /**
6880
+ * Release multiple matured chargeback intents in one transaction.
6881
+ * Pass `chargebackPolicyAddress` to pin the transaction to a snapshotted deployment.
6882
+ */
6883
+ this.releaseMaturedChargebackIntents = this.buildChargebackPolicyMethod("releaseMaturedChargebackIntents", (params) => [params.intentHashes]);
6521
6884
  // ╔═══════════════════════════════════════════════════════════════════════════╗
6522
6885
  // ║ CORE: DEPOSIT MANAGEMENT ║
6523
6886
  // ╚═══════════════════════════════════════════════════════════════════════════╝
@@ -7450,6 +7813,10 @@ var Zkp2pClient = class {
7450
7813
  this.rateManagerControllerAbi = abis.rateManagerController;
7451
7814
  this.intentGuardianAddress = toAddress(addresses.intentGuardian);
7452
7815
  this.intentGuardianAbi = abis.intentGuardian;
7816
+ this.stakeVaultAddress = toAddress(addresses.stakeVault);
7817
+ this.stakeVaultAbi = abis.stakeVault;
7818
+ this.chargebackPolicyAddress = toAddress(addresses.chargebackPolicy);
7819
+ this.chargebackPolicyAbi = abis.chargebackPolicy;
7453
7820
  if (!this.rateManagerRegistryAddress || !this.rateManagerRegistryAbi) {
7454
7821
  try {
7455
7822
  const rateManagerContracts = getRateManagerContracts(this.chainId, this.runtimeEnv);
@@ -7493,6 +7860,7 @@ var Zkp2pClient = class {
7493
7860
  });
7494
7861
  this._indexerService = new IndexerDepositService(this._indexerClient);
7495
7862
  this._indexerRateManagerService = new IndexerRateManagerService(this._indexerClient);
7863
+ this._indexerStakingService = new IndexerStakingService(this._indexerClient);
7496
7864
  this.baseApiUrl = opts.baseApiUrl;
7497
7865
  this.apiKey = opts.apiKey;
7498
7866
  this.apiHeaders = opts.apiHeaders;
@@ -7533,6 +7901,14 @@ var Zkp2pClient = class {
7533
7901
  prepareContractTransaction: (tx) => this.prepareContractTransaction(tx)
7534
7902
  }
7535
7903
  });
7904
+ this._stakeOps = new StakeOperations({
7905
+ getPublicClient: () => this.publicClient,
7906
+ getStakeVaultAddress: () => this.stakeVaultAddress,
7907
+ getStakeVaultAbi: () => this.stakeVaultAbi,
7908
+ getStakeTokenAddress: () => this._usdcAddress,
7909
+ getChargebackPolicyAddress: () => this.chargebackPolicyAddress,
7910
+ getChargebackPolicyAbi: () => this.chargebackPolicyAbi
7911
+ });
7536
7912
  this._intentGuardianOps = new IntentGuardianOperations({
7537
7913
  getPublicClient: () => this.publicClient,
7538
7914
  getGuardianAddress: () => this.intentGuardianAddress,
@@ -7947,7 +8323,7 @@ var Zkp2pClient = class {
7947
8323
  buildContractMethod(resolveContract, functionName, buildArgs, buildValue) {
7948
8324
  return Object.assign(
7949
8325
  async (params) => {
7950
- const contract = resolveContract();
8326
+ const contract = resolveContract(params);
7951
8327
  if (!contract.address || !contract.abi) {
7952
8328
  throw new Error(`${contract.label} not available`);
7953
8329
  }
@@ -7963,7 +8339,7 @@ var Zkp2pClient = class {
7963
8339
  },
7964
8340
  {
7965
8341
  prepare: async (params) => {
7966
- const contract = resolveContract();
8342
+ const contract = resolveContract(params);
7967
8343
  if (!contract.address || !contract.abi) {
7968
8344
  throw new Error(`${contract.label} not available`);
7969
8345
  }
@@ -7985,6 +8361,28 @@ var Zkp2pClient = class {
7985
8361
  }
7986
8362
  );
7987
8363
  }
8364
+ buildStakeVaultMethod(functionName, buildArgs) {
8365
+ return this.buildContractMethod(
8366
+ () => ({
8367
+ address: this.stakeVaultAddress,
8368
+ abi: this.stakeVaultAbi,
8369
+ label: "StakeVault"
8370
+ }),
8371
+ functionName,
8372
+ buildArgs
8373
+ );
8374
+ }
8375
+ buildChargebackPolicyMethod(functionName, buildArgs) {
8376
+ return this.buildContractMethod(
8377
+ (params) => ({
8378
+ address: params.chargebackPolicyAddress ?? this.chargebackPolicyAddress,
8379
+ abi: this.chargebackPolicyAbi,
8380
+ label: "ChargebackPolicy"
8381
+ }),
8382
+ functionName,
8383
+ buildArgs
8384
+ );
8385
+ }
7988
8386
  buildIntentGuardianMethod(functionName, buildArgs) {
7989
8387
  return this.buildContractMethod(
7990
8388
  () => ({
@@ -8235,6 +8633,7 @@ var Zkp2pClient = class {
8235
8633
  get indexer() {
8236
8634
  const service = this._indexerService;
8237
8635
  const rateManagerService = this._indexerRateManagerService;
8636
+ const stakingService = this._indexerStakingService;
8238
8637
  const client = this._indexerClient;
8239
8638
  return {
8240
8639
  /** Raw GraphQL client for custom queries */
@@ -8371,6 +8770,16 @@ var Zkp2pClient = class {
8371
8770
  getOracleConfigUpdates: (rateManagerId, options) => {
8372
8771
  return rateManagerService.fetchOracleConfigUpdates(rateManagerId, options);
8373
8772
  },
8773
+ /**
8774
+ * Composes the hard-cut 0.14.0-rc.0 staking current-state rows. Pass the
8775
+ * caller's fresh stakeOwnerOf(taker) result so the account rows can be
8776
+ * fetched together and checked against indexed ownership.
8777
+ */
8778
+ getStakingState: (params, options) => {
8779
+ return stakingService.fetchStakingState(params, {
8780
+ signal: options?.signal
8781
+ });
8782
+ },
8374
8783
  /**
8375
8784
  * Fetches chronological fund activities for a specific deposit.
8376
8785
  */
@@ -8453,6 +8862,91 @@ var Zkp2pClient = class {
8453
8862
  });
8454
8863
  return { hadAllowance: false, hash };
8455
8864
  }
8865
+ // ╔═══════════════════════════════════════════════════════════════════════════╗
8866
+ // ║ CORE: TAKER STAKING ║
8867
+ // ╚═══════════════════════════════════════════════════════════════════════════╝
8868
+ /**
8869
+ * Return the resolved StakeVault coordinates for advanced wallet, relayer,
8870
+ * or reactive read integrations.
8871
+ */
8872
+ getStakeVaultContract() {
8873
+ return this._stakeOps.getContract();
8874
+ }
8875
+ /** Return the resolved OrchestratorV3 coordinates for advanced integrations. */
8876
+ getOrchestratorV3Contract() {
8877
+ if (!this.orchestratorV3Address || !this.orchestratorV3Abi) {
8878
+ throw new Error("OrchestratorV3 not available for this chain/environment");
8879
+ }
8880
+ return { address: this.orchestratorV3Address, abi: this.orchestratorV3Abi };
8881
+ }
8882
+ /** Return the resolved ChargebackPolicy coordinates for keeper integrations. */
8883
+ getChargebackPolicyContract() {
8884
+ if (!this.chargebackPolicyAddress || !this.chargebackPolicyAbi) {
8885
+ throw new Error("ChargebackPolicy not available for this chain/environment");
8886
+ }
8887
+ return { address: this.chargebackPolicyAddress, abi: this.chargebackPolicyAbi };
8888
+ }
8889
+ /**
8890
+ * Ensure the connected wallet has approved enough USDC for StakeVault.
8891
+ * If an approval is submitted, wait for it to confirm before depositing.
8892
+ */
8893
+ async ensureStakeAllowance(params) {
8894
+ const { address, stakeToken } = this._stakeOps.getContract();
8895
+ return this.ensureAllowance({
8896
+ token: stakeToken,
8897
+ spender: address,
8898
+ amount: params.amount,
8899
+ maxApprove: params.maxApprove,
8900
+ txOverrides: params.txOverrides
8901
+ });
8902
+ }
8903
+ /** Read total stake owned by an address directly from StakeVault. */
8904
+ getStakeBalance(stakeOwner) {
8905
+ return this._stakeOps.getStakeBalance(stakeOwner);
8906
+ }
8907
+ /** Read stake committed to active StakeVault locks. */
8908
+ getLockedStake(stakeOwner) {
8909
+ return this._stakeOps.getLockedStake(stakeOwner);
8910
+ }
8911
+ /** Read stake available for immediate withdrawal or a new lock. */
8912
+ getFreeStake(stakeOwner) {
8913
+ return this._stakeOps.getFreeStake(stakeOwner);
8914
+ }
8915
+ /** Read the non-stake USDC withdrawable by a beneficiary with `claim()`. */
8916
+ getClaimable(beneficiary) {
8917
+ return this._stakeOps.getClaimable(beneficiary);
8918
+ }
8919
+ /** Resolve the effective stake owner backing a taker. */
8920
+ getStakeOwner(taker) {
8921
+ return this._stakeOps.getStakeOwner(taker);
8922
+ }
8923
+ /** Read a taker's raw selection, which is stale once authorization is revoked. */
8924
+ getSelectedStakeOwner(taker) {
8925
+ return this._stakeOps.getSelectedStakeOwner(taker);
8926
+ }
8927
+ /** Read whether a stake owner currently authorizes a taker. */
8928
+ getTakerAuthorization(stakeOwner, taker) {
8929
+ return this._stakeOps.getTakerAuthorization(stakeOwner, taker);
8930
+ }
8931
+ /** Read the complete authoritative StakeVault state needed by a staking UI. */
8932
+ getStakeVaultState(params) {
8933
+ return this._stakeOps.getStakeVaultState(params);
8934
+ }
8935
+ /** Read whether the ChargebackPolicy is refusing new chargebackable admissions. */
8936
+ getAdmissionsPaused() {
8937
+ return this._stakeOps.getAdmissionsPaused();
8938
+ }
8939
+ /**
8940
+ * Read a payment method's minimum collateral lock window in seconds. Zero
8941
+ * means the method admits unbonded — no stake is locked at admission.
8942
+ */
8943
+ getRiskWindow(paymentMethodHash) {
8944
+ return this._stakeOps.getRiskWindow(paymentMethodHash);
8945
+ }
8946
+ /** Read whether an escrow deposit has opted into chargeback coverage. */
8947
+ isChargebackEnabled(escrow, depositId) {
8948
+ return this._stakeOps.isChargebackEnabled(escrow, depositId);
8949
+ }
8456
8950
  /**
8457
8951
  * Registers payee details with the curator API and returns hashed on-chain IDs.
8458
8952
  *
@@ -9249,6 +9743,8 @@ var Zkp2pClient = class {
9249
9743
  unifiedPaymentVerifier: this.unifiedPaymentVerifier,
9250
9744
  rateManagerV1: this.rateManagerV1Address,
9251
9745
  orchestratorRegistry: this.orchestratorRegistryAddress,
9746
+ stakeVault: this.stakeVaultAddress,
9747
+ chargebackPolicy: this.chargebackPolicyAddress,
9252
9748
  usdc: this._usdcAddress
9253
9749
  };
9254
9750
  }
@@ -9311,18 +9807,46 @@ var getPeerExtensionState = async (options) => {
9311
9807
  return "needs_connection";
9312
9808
  }
9313
9809
  };
9810
+ var sanitizePeerAuthenticateParams = (params) => {
9811
+ const sanitizedParams = { ...params };
9812
+ delete sanitizedParams.providerConfig;
9813
+ return sanitizedParams;
9814
+ };
9314
9815
  var createPeerExtensionSdk = (options = {}) => ({
9315
9816
  isAvailable: () => isPeerExtensionAvailable(options),
9316
9817
  requestConnection: () => requirePeer(options).requestConnection(),
9317
9818
  checkConnectionStatus: () => requirePeer(options).checkConnectionStatus(),
9318
9819
  getVersion: () => requirePeer(options).getVersion(),
9319
- authenticate: (params) => requirePeer(options).authenticate(params),
9820
+ authenticate: (params) => requirePeer(options).authenticate(sanitizePeerAuthenticateParams(params)),
9320
9821
  onMetadataMessage: (callback) => requirePeer(options).onMetadataMessage(callback),
9321
9822
  openInstallPage: () => openPeerExtensionInstallPage(options),
9322
9823
  getState: () => getPeerExtensionState(options)
9323
9824
  });
9324
9825
  var peerExtensionSdk = createPeerExtensionSdk();
9325
9826
 
9827
+ // src/riskMath.ts
9828
+ var RISK_BPS_DENOMINATOR = 10000n;
9829
+ function integer(value, label) {
9830
+ if (typeof value === "number" && (!Number.isSafeInteger(value) || value < 0)) {
9831
+ throw new RangeError(`${label} must be a non-negative safe integer`);
9832
+ }
9833
+ const parsed = BigInt(value.toString());
9834
+ if (parsed < 0n) throw new RangeError(`${label} must be non-negative`);
9835
+ return parsed;
9836
+ }
9837
+ function calculateRequiredCoverage(amount, chargebackable) {
9838
+ return chargebackable ? integer(amount, "amount") : 0n;
9839
+ }
9840
+ function calculateStakeBackedCapacity(freeStake) {
9841
+ return integer(freeStake, "freeStake");
9842
+ }
9843
+ function selectRiskMode(amount, freeStake, chargebackable) {
9844
+ const required = calculateRequiredCoverage(amount, chargebackable);
9845
+ if (!chargebackable) return "UNBONDED";
9846
+ if (integer(freeStake, "freeStake") >= required) return "STAKE_BACKED";
9847
+ throw new RangeError("insufficient free stake for chargebackable admission");
9848
+ }
9849
+
9326
9850
  // src/client/accessPolicyPlan.ts
9327
9851
  var MAX_GROUPS_PER_DEPOSIT = 10;
9328
9852
  var MAX_ADDRESSES_PER_CALL = 50;
@@ -9479,6 +10003,6 @@ var planAccessPolicyUpdate = (persistedInput, draftInput) => {
9479
10003
  };
9480
10004
  };
9481
10005
 
9482
- export { AccessPolicyOperations, AccessPolicyUnsupportedError, BASE_BUILDER_CODE, CHAINLINK_ORACLE_ADAPTER, CHAINLINK_ORACLE_FEEDS, ContractRouter, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, IndexerClient, IndexerDepositService, IndexerRateManagerService, MAX_ADDRESSES_PER_CALL, MAX_GROUPS_PER_DEPOSIT, 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, 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, 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, sendTransactionWithAttribution, setLogLevel, validateOracleFeedsOnChain };
10006
+ 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, 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, 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 };
9483
10007
  //# sourceMappingURL=index.mjs.map
9484
10008
  //# sourceMappingURL=index.mjs.map