@zkp2p/sdk 0.2.3 → 0.2.4

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/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  Stable TypeScript SDK for trustless fiat-to-crypto on Base. ZKP2P combines escrowed on-chain settlement, TLS attestations for payment verification, and API/indexer helpers so makers, takers, wallets, and embedded ramps can ship production-grade fiat liquidity flows without building their own contract or indexing stack.
8
8
 
9
- Current version: `0.1.0`
9
+ Current version: `0.2.3`
10
10
 
11
11
  ## Why This SDK
12
12
 
@@ -29,7 +29,7 @@ Current version: `0.1.0`
29
29
  - RPC-first reads: primary reads use ProtocolViewer and on-chain fallbacks, so `getDeposits()`, `getDeposit()`, `getIntents()`, `getIntent()`, and the `getPv*` methods are not blocked on indexer lag.
30
30
  - Indexer for history and filtering: use `client.indexer.*` for pagination, historical volumes, fund activities, daily snapshots, and vault analytics.
31
31
  - Current-stack routing: the client resolves against the upgraded escrow and orchestrator contracts, with historical escrow lookups available for reads and legacy deposits.
32
- - Modular internals: stable `0.1.0` extracted intent, vault, and ProtocolViewer logic into `IntentOperations`, `VaultOperations`, and `ProtocolViewerReader`, keeping `Zkp2pClient` focused on orchestration.
32
+ - Modular internals: intent, vault, and ProtocolViewer logic are extracted into `IntentOperations`, `VaultOperations`, and `ProtocolViewerReader`, keeping `Zkp2pClient` focused on orchestration.
33
33
  - App-level rollout control: the SDK is capability-based. Product gating and phase flags belong in your app layer, not inside transaction helpers.
34
34
 
35
35
  ## Installation
@@ -72,10 +72,14 @@ const client = new Zkp2pClient({
72
72
 
73
73
  - Supported runtime environments: `'production'`, `'preproduction'`, `'staging'`
74
74
  - `runtimeEnv` default: `'production'`
75
- - `apiKey`: optional curator API key for authenticated service endpoints
75
+ - `rpcUrl`: optional RPC URL override (defaults to wallet's chain RPC)
76
+ - `apiKey`: optional curator API key — enhances some responses (e.g. `getQuote` returns `depositData` when authenticated) but is **not required** for any SDK method
76
77
  - `authorizationToken` / `getAuthorizationToken`: optional bearer auth for hybrid client and indexer flows
77
78
  - `indexerApiKey`: optional `x-api-key` for indexer proxy auth
78
79
  - `indexerUrl` and `baseApiUrl`: override defaults when you are targeting custom deployments
80
+ - `timeouts`: `{ api?: number }` — API timeout in milliseconds (default 15000)
81
+
82
+ **No API key is required to get started.** `createDeposit`, `registerPayeeDetails`, `getQuote`, `getTakerTier`, and all other SDK methods work without `apiKey` or `authorizationToken`. Auth credentials are optional and only affect response richness (e.g. authenticated quotes include maker `depositData`).
79
83
 
80
84
  Indexer defaults by environment:
81
85
 
@@ -85,20 +89,20 @@ Indexer defaults by environment:
85
89
 
86
90
  ## Core Capabilities
87
91
 
88
- | Area | Stable surface |
89
- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
90
- | Deposits | `createDeposit`, `addFunds`, `removeFunds`, `withdrawDeposit`, `ensureAllowance`, `setAcceptingIntents`, `setIntentRange`, `setCurrencyMinRate`, `setRetainOnEmpty` |
91
- | Payment methods and currencies | `addPaymentMethods`, `removePaymentMethod`, `setPaymentMethodActive`, `addCurrencies`, `removeCurrency`, `deactivateCurrency`, `pruneExpiredIntents` |
92
- | Intents | `signalIntent`, `fulfillIntent`, `cancelIntent`, `releaseFundsToPayer`, `getFulfillIntentInputs` |
93
- | Prepared transactions | `client.prepareCreateDeposit(...)`, `client.signalIntent.prepare(...)`, `client.fulfillIntent.prepare(...)`, `client.setVaultFee.prepare(...)`, and equivalent prepare flows across the rest of the prepareable write surface |
94
- | Payee and quote APIs | `registerPayeeDetails`, `resolvePayeeHash`, `getQuote`, `getTakerTier` |
95
- | Delegation and hooks | `setDelegate`, `removeDelegate`, `setRateManager`, `clearRateManager`, `setDepositRateManager`, `clearDepositRateManager`, `setDepositPreIntentHook`, `setDepositWhitelistHook` |
96
- | Vault / DRM | `createRateManager`, `setVaultMinRate`, `setVaultMinRatesBatch`, `setVaultFee`, `setVaultConfig`, `getDepositRateManager`, `getManagerFee`, `getEffectiveRate` |
97
- | Oracle config | `setOracleRateConfig`, `setOracleRateConfigBatch`, `removeOracleRateConfig`, `updateCurrencyConfigBatch`, `deactivateCurrenciesBatch`, `supportsInlineOracleRateConfig`, `validateOracleFeedsOnChain` |
98
- | RPC reads | `getDeposits`, `getDeposit`, `getDepositsById`, `getIntents`, `getIntent`, `getPvDepositById`, `getPvDepositsFromIds`, `getPvAccountDeposits`, `getPvAccountIntents`, `getPvIntent` |
99
- | Indexer | `client.indexer.getDeposits`, `getDepositsWithRelations`, `getDepositById`, `getIntentFulfillmentAmounts`, `getDepositFundActivities`, `getDepositDailySnapshots`, `getRateManagers`, `getRateManagerDetail`, `getManagerDailySnapshots` |
100
- | React hooks | `@zkp2p/sdk/react` exports hooks for deposits, intents, delegation, vaults, payment methods, and taker tier |
101
- | Attribution | ERC-8021 helpers like `sendTransactionWithAttribution`, `encodeWithAttribution`, and `txOverrides.referrer` support |
92
+ | Area | Stable surface |
93
+ | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
94
+ | Deposits | `createDeposit`, `addFunds`, `removeFunds`, `withdrawDeposit`, `ensureAllowance`, `setAcceptingIntents`, `setIntentRange`, `setCurrencyMinRate`, `setRetainOnEmpty` |
95
+ | Payment methods and currencies | `addPaymentMethods`, `removePaymentMethod`, `setPaymentMethodActive`, `addCurrencies`, `removeCurrency`, `deactivateCurrency`, `pruneExpiredIntents` |
96
+ | Intents | `signalIntent`, `fulfillIntent`, `cancelIntent`, `releaseFundsToPayer`, `getFulfillIntentInputs` |
97
+ | Prepared transactions | `client.prepareCreateDeposit(...)`, `client.signalIntent.prepare(...)`, `client.fulfillIntent.prepare(...)`, `client.setVaultFee.prepare(...)`, and equivalent prepare flows across the rest of the prepareable write surface |
98
+ | Payee and quote APIs | `registerPayeeDetails`, `resolvePayeeHash`, `getQuote`, `getTakerTier` |
99
+ | Delegation and hooks | `setDelegate`, `removeDelegate`, `setRateManager`, `clearRateManager`, `setDepositRateManager`, `clearDepositRateManager`, `setDepositPreIntentHook`, `setDepositWhitelistHook` |
100
+ | Vault / DRM | `createRateManager`, `setVaultMinRate`, `setVaultMinRatesBatch`, `setVaultFee`, `setVaultConfig`, `getDepositRateManager`, `getManagerFee`, `getEffectiveRate` |
101
+ | Oracle config | `setOracleRateConfig`, `setOracleRateConfigBatch`, `removeOracleRateConfig`, `updateCurrencyConfigBatch`, `deactivateCurrenciesBatch`, `supportsInlineOracleRateConfig`, `validateOracleFeedsOnChain` |
102
+ | RPC reads | `getDeposits`, `getDeposit`, `getDepositsById`, `getIntents`, `getIntent`, `getPvDepositById`, `getPvDepositsFromIds`, `getPvAccountDeposits`, `getPvAccountIntents`, `getPvIntent` |
103
+ | Indexer | `client.indexer.getDeposits`, `getDepositsWithRelations`, `getDepositById`, `getDepositsByIds`, `getDepositsByIdsWithRelations`, `getDepositsByPayeeHash`, `getIntentsForDeposits`, `getOwnerIntents`, `getIntentsByRateManager`, `getIntentByHash`, `getExpiredIntents`, `getFulfilledIntentEvents`, `getIntentFulfillmentAmounts`, `getFulfillmentAndPayment`, `getDepositFundActivities`, `getMakerFundActivities`, `getDepositDailySnapshots`, `getProfitSnapshotsByDeposits`, `getRateManagers`, `getRateManagerDetail`, `getRateManagerDelegations`, `getDelegationForDeposit`, `getManagerDailySnapshots`, `getManualRateUpdates`, `getOracleConfigUpdates`, `query` |
104
+ | React hooks | `@zkp2p/sdk/react` exports hooks for deposits, intents, delegation, vaults, payment methods, and taker tier |
105
+ | Attribution | ERC-8021 helpers like `sendTransactionWithAttribution`, `encodeWithAttribution`, and `txOverrides.referrer` support |
102
106
 
103
107
  ## Create a Deposit
104
108
 
@@ -385,35 +389,77 @@ You can also use the convenience wrappers `getDeposits()`, `getDeposit()`, `getI
385
389
 
386
390
  ## Indexer Queries
387
391
 
388
- Use the indexer for filtered queries, pagination, fund activity history, snapshots, and vault analytics.
392
+ Use the indexer for filtered queries, pagination, fund activity history, snapshots, and vault analytics. All methods live on the flat `client.indexer.*` namespace.
389
393
 
390
394
  ```ts
395
+ // Deposit queries
391
396
  const deposits = await client.indexer.getDeposits(
392
397
  { status: 'ACTIVE', depositor: '0xMaker' },
393
398
  { limit: 25, orderBy: 'updatedAt', orderDirection: 'desc' },
394
399
  );
395
-
396
- const depositWithRelations = await client.indexer.getDepositById('8453_0xEscrowAddress_42', {
400
+ const depositsWithRelations = await client.indexer.getDepositsWithRelations(
401
+ { status: 'ACTIVE' },
402
+ { limit: 10 },
403
+ { includeIntents: true },
404
+ );
405
+ const deposit = await client.indexer.getDepositById('8453_0xEscrowAddress_42', {
406
+ includeIntents: true,
407
+ });
408
+ const depositsByIds = await client.indexer.getDepositsByIds(['8453_0xEscrow_42']);
409
+ const depositsByIdsWithRelations = await client.indexer.getDepositsByIdsWithRelations(
410
+ ['8453_0xEscrow_42'],
411
+ { includeIntents: true },
412
+ );
413
+ const depositsByPayee = await client.indexer.getDepositsByPayeeHash('0xPayeeHash', {
414
+ paymentMethodHash: '0x...',
415
+ limit: 10,
397
416
  includeIntents: true,
398
417
  });
399
418
 
419
+ // Intent queries
420
+ const intentsForDeposits = await client.indexer.getIntentsForDeposits(
421
+ ['8453_0xEscrow_42'],
422
+ ['SIGNALED'],
423
+ );
424
+ const ownerIntents = await client.indexer.getOwnerIntents('0xTaker', ['SIGNALED', 'FULFILLED']);
425
+ const intentsByVault = await client.indexer.getIntentsByRateManager('0xVaultId');
426
+ const intent = await client.indexer.getIntentByHash('0xIntentHash');
427
+ const expiredIntents = await client.indexer.getExpiredIntents({
428
+ now: BigInt(Math.floor(Date.now() / 1000)),
429
+ depositIds: ['8453_0xEscrow_42'],
430
+ });
431
+ const fulfilledEvents = await client.indexer.getFulfilledIntentEvents(['0xIntentHash']);
400
432
  const fulfillment = await client.indexer.getIntentFulfillmentAmounts('0xIntentHash');
433
+ const fulfillmentAndPayment = await client.indexer.getFulfillmentAndPayment('0xIntentHash');
434
+
435
+ // Fund activity and snapshots
401
436
  const fundActivities = await client.indexer.getDepositFundActivities('8453_0xEscrowAddress_42');
437
+ const makerActivities = await client.indexer.getMakerFundActivities('0xMaker', 50);
402
438
  const snapshots = await client.indexer.getDepositDailySnapshots('8453_0xEscrowAddress_42', 30);
439
+ const profitSnapshots = await client.indexer.getProfitSnapshotsByDeposits(['8453_0xEscrow_42']);
403
440
 
441
+ // Rate manager (vault) queries
404
442
  const managers = await client.indexer.getRateManagers({
405
443
  limit: 10,
406
444
  orderBy: 'currentDelegatedBalance',
407
445
  orderDirection: 'desc',
408
446
  });
409
-
410
447
  const managerDetail = await client.indexer.getRateManagerDetail('0xVaultId', {
411
448
  rateManagerAddress: '0xVaultAddress',
449
+ statsLimit: 30,
450
+ });
451
+ const delegations = await client.indexer.getRateManagerDelegations('0xVaultId');
452
+ const delegation = await client.indexer.getDelegationForDeposit('8453_0xEscrow_42');
453
+ const managerSnapshots = await client.indexer.getManagerDailySnapshots('0xVaultId');
454
+ const manualRates = await client.indexer.getManualRateUpdates('0xVaultId');
455
+ const oracleUpdates = await client.indexer.getOracleConfigUpdates('0xVaultId');
456
+
457
+ // Raw GraphQL
458
+ const custom = await client.indexer.query<MyType>({
459
+ query: '{ deposits(limit: 5) { id } }',
412
460
  });
413
461
  ```
414
462
 
415
- `managerDetail?.aggregate` gives you current delegated balance and filled volume stats alongside recent snapshots and delegation history.
416
-
417
463
  ## React Hooks
418
464
 
419
465
  Install React and import hooks from `@zkp2p/sdk/react`. React is an optional peer dependency of the SDK.
@@ -494,7 +540,7 @@ const hash = await client.signalIntent({
494
540
  });
495
541
  ```
496
542
 
497
- Lower-level helpers are also exported: `BASE_BUILDER_CODE`, `getAttributionDataSuffix()`, `appendAttributionToCalldata()`, `encodeWithAttribution()`, and `sendTransactionWithAttribution()`.
543
+ Lower-level helpers are also exported: `BASE_BUILDER_CODE`, `ZKP2P_IOS_REFERRER`, `ZKP2P_ANDROID_REFERRER`, `getAttributionDataSuffix()`, `appendAttributionToCalldata()`, `encodeWithAttribution()`, and `sendTransactionWithAttribution()`.
498
544
 
499
545
  ## TypeDoc API Reference
500
546
 
package/dist/index.cjs CHANGED
@@ -3461,6 +3461,7 @@ var DEPOSIT_FIELDS = `
3461
3461
  timestamp
3462
3462
  txHash
3463
3463
  updatedAt
3464
+ whitelistHookAddress
3464
3465
  `;
3465
3466
  var LEGACY_DEPOSIT_FIELDS = `
3466
3467
  id
@@ -4451,6 +4452,35 @@ var DEPOSIT_DAILY_SNAPSHOTS_QUERY = (
4451
4452
  }
4452
4453
  `
4453
4454
  );
4455
+ var PROFIT_SNAPSHOTS_BY_DEPOSITS_QUERY = (
4456
+ /* GraphQL */
4457
+ `
4458
+ query GetProfitSnapshotsByDeposits($depositIds: [String!]) {
4459
+ profitSnapshots: MakerProfitSnapshot(
4460
+ where: { depositId: { _in: $depositIds } }
4461
+ order_by: { createdAt: desc }
4462
+ ) {
4463
+ id
4464
+ chainId
4465
+ maker
4466
+ intentId
4467
+ depositId
4468
+ fiatCurrency
4469
+ quoteConversionRate
4470
+ oracleRate
4471
+ spreadBps
4472
+ amount
4473
+ notionalFiatUsdCents
4474
+ feeUsd
4475
+ realizedProfitUsdCents
4476
+ priceSnapshotId
4477
+ status
4478
+ createdAt
4479
+ updatedAt
4480
+ }
4481
+ }
4482
+ `
4483
+ );
4454
4484
  var FULFILLMENT_AND_PAYMENT_QUERY = (
4455
4485
  /* GraphQL */
4456
4486
  `
@@ -4562,7 +4592,7 @@ function convertIndexerDepositToEscrowView(deposit, _chainId, _escrowAddress) {
4562
4592
  }
4563
4593
  function convertDepositsForLiquidity(deposits, chainId, escrowAddress) {
4564
4594
  return deposits.filter(
4565
- (d) => d.depositor && d.depositor.toLowerCase() !== ZERO && d.acceptingIntents && toBigInt(d.remainingDeposits) > 0n && d.status === "ACTIVE"
4595
+ (d) => d.depositor && d.depositor.toLowerCase() !== ZERO && normalizeAddress2(d.whitelistHookAddress).toLowerCase() === ZERO && d.acceptingIntents && toBigInt(d.remainingDeposits) > 0n && d.status === "ACTIVE"
4566
4596
  ).map((d) => convertIndexerDepositToEscrowView(d));
4567
4597
  }
4568
4598
  function convertIndexerIntentsToEscrowViews(intents, depositViewsById) {
@@ -4678,14 +4708,16 @@ var IndexerDepositService = class {
4678
4708
  const where = {};
4679
4709
  if (params.depositIds?.length) where.depositId = { _in: params.depositIds };
4680
4710
  if (params.owner) where.owner = { _ilike: params.owner };
4711
+ if (params.rateManagerId) where.rateManagerId = { _ilike: params.rateManagerId };
4681
4712
  if (params.statuses?.length) where.status = { _in: params.statuses };
4682
4713
  if (!Object.keys(where).length) return [];
4714
+ const orderByField = params.orderByField ?? "signalTimestamp";
4683
4715
  const result = await this.queryWithLegacyFallback({
4684
4716
  query: INTENTS_QUERY,
4685
4717
  legacyQuery: LEGACY_INTENTS_QUERY,
4686
4718
  variables: {
4687
4719
  where,
4688
- order_by: [{ signalTimestamp: "desc" }],
4720
+ order_by: [{ [orderByField]: "desc" }],
4689
4721
  limit: params.limit,
4690
4722
  offset: params.offset
4691
4723
  }
@@ -4748,6 +4780,16 @@ var IndexerDepositService = class {
4748
4780
  if (!owner) return [];
4749
4781
  return this.fetchIntents({ owner, statuses });
4750
4782
  }
4783
+ async fetchIntentsByRateManager(rateManagerId, statuses) {
4784
+ const normalizedRateManagerId = rateManagerId?.trim();
4785
+ if (!normalizedRateManagerId) return [];
4786
+ return this.fetchIntents({
4787
+ rateManagerId: normalizedRateManagerId,
4788
+ statuses,
4789
+ limit: 500,
4790
+ orderByField: "fulfillTimestamp"
4791
+ });
4792
+ }
4751
4793
  async fetchIntentByHash(intentHash) {
4752
4794
  if (!intentHash) return null;
4753
4795
  const result = await this.queryWithLegacyFallback({
@@ -4969,6 +5011,26 @@ var IndexerDepositService = class {
4969
5011
  return [];
4970
5012
  }
4971
5013
  }
5014
+ async fetchProfitSnapshotsByDeposits(depositIds) {
5015
+ const normalizedDepositIds = Array.from(
5016
+ new Set(
5017
+ depositIds.map((depositId) => depositId?.trim()).filter((depositId) => Boolean(depositId))
5018
+ )
5019
+ );
5020
+ if (!normalizedDepositIds.length) return [];
5021
+ try {
5022
+ const result = await this.client.query({
5023
+ query: PROFIT_SNAPSHOTS_BY_DEPOSITS_QUERY,
5024
+ variables: { depositIds: normalizedDepositIds }
5025
+ });
5026
+ return result.profitSnapshots ?? result.MakerProfitSnapshot ?? [];
5027
+ } catch (error) {
5028
+ if (!isSchemaCompatibilityError(error)) {
5029
+ throw error;
5030
+ }
5031
+ return [];
5032
+ }
5033
+ }
4972
5034
  };
4973
5035
 
4974
5036
  // src/indexer/rateManagerService.ts
@@ -7766,6 +7828,12 @@ var Zkp2pClient = class {
7766
7828
  getOwnerIntents: (owner, statuses) => {
7767
7829
  return service.fetchIntentsByOwner(owner, statuses);
7768
7830
  },
7831
+ /**
7832
+ * Fetches fulfilled intents for a vault by rate manager ID.
7833
+ */
7834
+ getIntentsByRateManager: (rateManagerId, statuses) => {
7835
+ return service.fetchIntentsByRateManager(rateManagerId, statuses);
7836
+ },
7769
7837
  /**
7770
7838
  * Fetches a single intent by hash.
7771
7839
  */
@@ -7816,6 +7884,12 @@ var Zkp2pClient = class {
7816
7884
  getDepositsByIdsWithRelations: (ids, options) => {
7817
7885
  return service.fetchDepositsByIdsWithRelations(ids, options);
7818
7886
  },
7887
+ /**
7888
+ * Fetches maker profit snapshots for the provided deposits.
7889
+ */
7890
+ getProfitSnapshotsByDeposits: (depositIds) => {
7891
+ return service.fetchProfitSnapshotsByDeposits(depositIds);
7892
+ },
7819
7893
  /**
7820
7894
  * Fetches rate managers (vaults) with aggregate stats.
7821
7895
  */