@zkp2p/sdk 0.9.0 → 0.10.0-rc.1

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
@@ -1,8 +1,8 @@
1
- export { TAKER_TIER_CAPS, TAKER_TIER_FEE_DISCOUNT_BPS, TAKER_TIER_ORDER, TAKER_TIER_SCHEDULE, ZERO_RATE_MANAGER_ID, classifyDelegationState, getDelegationRoute, getNextTakerTier, getTakerTierFeeDiscountBps, isZeroRateManagerId, normalizeRateManagerId, normalizeRegistry } from './chunk-EIOXBVXP.mjs';
1
+ export { ZERO_RATE_MANAGER_ID, classifyDelegationState, getDelegationRoute, isZeroRateManagerId, normalizeRateManagerId, normalizeRegistry } from './chunk-LPJE2MN7.mjs';
2
2
  import { ValidationError, APIError, NetworkError } from './chunk-GHQK65J2.mjs';
3
3
  export { APIError, ContractError, ErrorCode, NetworkError, ValidationError, ZKP2PError } from './chunk-GHQK65J2.mjs';
4
- import { METHOD_NAME_TO_HASH, matchesQuotePaymentMethod, matchesPaymentMethodNameAndHash, getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, SUPPORTED_PAYMENT_METHOD_HASHES, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash } from './chunk-FSIRPX4W.mjs';
5
- export { PAYMENT_PLATFORMS, asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getContracts, getGatingServiceAddress, getPaymentMethodsCatalog, getRateManagerContracts, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-FSIRPX4W.mjs';
4
+ import { METHOD_NAME_TO_HASH, matchesQuotePaymentMethod, matchesPaymentMethodNameAndHash, getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, SUPPORTED_PAYMENT_METHOD_HASHES, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash } from './chunk-NKEAAPPR.mjs';
5
+ export { DEFERRED_PAYOUT_RECORDED_EVENT_ABI, ORCHESTRATOR_V3_ABI, PAYMENT_PLATFORMS, RISK_MANAGER_ABI, RISK_POSITION_SETTLED_EVENT_ABI, STAKE_VAULT_ABI, asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getContracts, getGatingServiceAddress, getOrchestratorV3Contract, getPaymentMethodsCatalog, getRateManagerContracts, getRiskManagerContract, getStakeVaultContract, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-NKEAAPPR.mjs';
6
6
  import { Currency, currencyKeccak256 } from './chunk-ZFBH4HD7.mjs';
7
7
  export { Currency, currencyInfo, getCurrencyCodeFromHash, getCurrencyInfoFromCountryCode, getCurrencyInfoFromHash, isSupportedCurrencyHash, mapConversionRatesToOnchainMinRate } from './chunk-ZFBH4HD7.mjs';
8
8
  import './chunk-J5LGTIGS.mjs';
@@ -153,6 +153,8 @@ var ContractRouter = class {
153
153
  this.orchestratorAbi = config.orchestratorAbi;
154
154
  this.orchestratorV2Address = config.orchestratorV2Address;
155
155
  this.orchestratorV2Abi = config.orchestratorV2Abi;
156
+ this.orchestratorV3Address = config.orchestratorV3Address;
157
+ this.orchestratorV3Abi = config.orchestratorV3Abi;
156
158
  this.orchestratorAddresses = config.orchestratorAddresses;
157
159
  this._registerContexts();
158
160
  }
@@ -183,24 +185,26 @@ var ContractRouter = class {
183
185
  for (let index = 0; index < configuredPairCount; index += 1) {
184
186
  addEscrowOrchestratorPair(this.escrowAddresses[index], this.orchestratorAddresses[index]);
185
187
  }
186
- const resolveOrchestratorAbi = (address) => this.getOrchestratorContextByAddress(address)?.abi ?? (isSameAddress(address, this.orchestratorV2Address) ? this.orchestratorV2Abi ?? this.orchestratorAbi : this.orchestratorAbi ?? this.orchestratorV2Abi);
188
+ const resolveOrchestratorAbi = (address) => this.getOrchestratorContextByAddress(address)?.abi ?? (isSameAddress(address, this.orchestratorV3Address) ? this.orchestratorV3Abi : isSameAddress(address, this.orchestratorV2Address) ? this.orchestratorV2Abi ?? this.orchestratorAbi : this.orchestratorAbi ?? this.orchestratorV2Abi);
187
189
  const uniqueOrchestratorAddresses = /* @__PURE__ */ new Set();
188
190
  for (const address of [
189
191
  primaryOrchestratorAddress,
190
192
  this.orchestratorAddress,
191
193
  this.orchestratorV2Address,
194
+ this.orchestratorV3Address,
192
195
  ...this.orchestratorAddresses
193
196
  ]) {
194
197
  if (!address) continue;
195
198
  const key = address.toLowerCase();
196
199
  if (uniqueOrchestratorAddresses.has(key)) continue;
197
200
  uniqueOrchestratorAddresses.add(key);
198
- const abi = isSameAddress(address, this.orchestratorV2Address) ? this.orchestratorV2Abi ?? this.orchestratorAbi : this.orchestratorAbi ?? this.orchestratorV2Abi;
201
+ const isV3 = isSameAddress(address, this.orchestratorV3Address);
202
+ const abi = isV3 ? this.orchestratorV3Abi : isSameAddress(address, this.orchestratorV2Address) ? this.orchestratorV2Abi ?? this.orchestratorAbi : this.orchestratorAbi ?? this.orchestratorV2Abi;
199
203
  if (!abi) continue;
200
204
  registerOrchestrator({
201
205
  address,
202
206
  abi,
203
- version: "v2"
207
+ version: isV3 ? "v3" : "v2"
204
208
  });
205
209
  }
206
210
  const uniqueEscrowAddresses = /* @__PURE__ */ new Set();
@@ -1220,7 +1224,11 @@ var IntentOperations = class {
1220
1224
  });
1221
1225
  const currentEscrow = this.config.getEscrowV2Address();
1222
1226
  const currentOrchestrator = this.config.getOrchestratorV2Address();
1223
- if (currentEscrow && escrowContext.address.toLowerCase() !== currentEscrow.toLowerCase() || currentOrchestrator && orchestratorContext.address.toLowerCase() !== currentOrchestrator.toLowerCase()) {
1227
+ const isOrchestratorV3 = orchestratorContext.version === "v3";
1228
+ if (currentEscrow && escrowContext.address.toLowerCase() !== currentEscrow.toLowerCase()) {
1229
+ throw new Error("signalIntent is only supported on the current EscrowV2 deployment");
1230
+ }
1231
+ if (!isOrchestratorV3 && currentOrchestrator && orchestratorContext.address.toLowerCase() !== currentOrchestrator.toLowerCase()) {
1224
1232
  throw new Error(
1225
1233
  "signalIntent is only supported on the current EscrowV2 / OrchestratorV2 deployment"
1226
1234
  );
@@ -1240,7 +1248,7 @@ var IntentOperations = class {
1240
1248
  let { gatingServiceSignature, signatureExpiration } = params;
1241
1249
  let preIntentHookData = params.preIntentHookData;
1242
1250
  const baseApiUrl = this.config.getBaseApiUrl();
1243
- if ((!gatingServiceSignature || !signatureExpiration) && baseApiUrl) {
1251
+ if (!isOrchestratorV3 && (!gatingServiceSignature || !signatureExpiration) && baseApiUrl) {
1244
1252
  const apiOpts = {
1245
1253
  baseApiUrl,
1246
1254
  apiKey: this.config.getApiKey(),
@@ -1288,7 +1296,10 @@ var IntentOperations = class {
1288
1296
  });
1289
1297
  }
1290
1298
  }
1291
- if (!gatingServiceSignature || !signatureExpiration) {
1299
+ if (isOrchestratorV3) {
1300
+ gatingServiceSignature = "0x";
1301
+ signatureExpiration = 0n;
1302
+ } else if (!gatingServiceSignature || !signatureExpiration) {
1292
1303
  throw new Error("Missing gatingServiceSignature/signatureExpiration");
1293
1304
  }
1294
1305
  const args = [
@@ -1968,7 +1979,7 @@ var ProtocolViewerReader = class {
1968
1979
  if (inputCount === null) {
1969
1980
  throw new Error("Configured ProtocolViewer ABI does not expose getDeposit");
1970
1981
  }
1971
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-ER62YZ5L.mjs');
1982
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-WNN3TJD3.mjs');
1972
1983
  if (inputCount >= 3) {
1973
1984
  return tryContexts(
1974
1985
  protocolViewerContexts,
@@ -2047,7 +2058,7 @@ var ProtocolViewerReader = class {
2047
2058
  return Promise.all(ids.map((id) => this.config.host.getPvDepositById(id)));
2048
2059
  }
2049
2060
  const bn = ids.map((id) => typeof id === "bigint" ? id : parseRawDepositId(id));
2050
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-ER62YZ5L.mjs');
2061
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-WNN3TJD3.mjs');
2051
2062
  if (inputCount >= 2) {
2052
2063
  const requests = ids.map((id, index) => ({
2053
2064
  index,
@@ -2152,7 +2163,7 @@ var ProtocolViewerReader = class {
2152
2163
  if (!protocolViewerAddress || !protocolViewerAbi || inputCount === null) {
2153
2164
  return this.config.host.getPvAccountDepositsFromIndexer(owner);
2154
2165
  }
2155
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-ER62YZ5L.mjs');
2166
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-WNN3TJD3.mjs');
2156
2167
  const { address, abi } = this.config.host.requireProtocolViewer();
2157
2168
  if (inputCount >= 2) {
2158
2169
  const readAndFilter = async (raw2) => {
@@ -2223,7 +2234,7 @@ var ProtocolViewerReader = class {
2223
2234
  if (protocolViewerEntries.length === 0) {
2224
2235
  throw new Error("ProtocolViewer not available for this network");
2225
2236
  }
2226
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-ER62YZ5L.mjs');
2237
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-WNN3TJD3.mjs');
2227
2238
  const intentsByHash = /* @__PURE__ */ new Map();
2228
2239
  let attemptedRead = false;
2229
2240
  let hadSuccessfulRead = false;
@@ -2331,7 +2342,7 @@ var ProtocolViewerReader = class {
2331
2342
  if (protocolViewerEntries.length === 0) {
2332
2343
  throw new Error("ProtocolViewer not available for this network");
2333
2344
  }
2334
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-ER62YZ5L.mjs');
2345
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-WNN3TJD3.mjs');
2335
2346
  let lastError;
2336
2347
  for (const pvEntry of protocolViewerEntries) {
2337
2348
  const inputCount = this.pvEntryFunctionInputCount(pvEntry, "getIntent");
@@ -4525,13 +4536,32 @@ async function apiGetOwnerDeposits(req, apiKey, baseApiUrl, authToken, timeoutMs
4525
4536
  statusCode: 200
4526
4537
  };
4527
4538
  }
4528
- async function apiGetTakerTier(req, baseApiUrl, timeoutMs) {
4539
+ async function apiGetTakerStake(req, baseApiUrl, timeoutMs) {
4540
+ if (!isValidHexAddress(req.owner)) {
4541
+ throw new ValidationError("owner must be a valid Ethereum address", "owner");
4542
+ }
4543
+ const normalizedOwner = req.owner.toLowerCase();
4544
+ const query = new URLSearchParams({
4545
+ owner: normalizedOwner,
4546
+ chainId: String(req.chainId)
4547
+ });
4548
+ const endpoint = `/v2/taker/stake?${query.toString()}`;
4549
+ return apiFetch({
4550
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
4551
+ method: "GET",
4552
+ timeoutMs
4553
+ });
4554
+ }
4555
+ async function apiGetTakerCapacity(req, baseApiUrl, timeoutMs) {
4556
+ if (!isValidHexAddress(req.owner)) {
4557
+ throw new ValidationError("owner must be a valid Ethereum address", "owner");
4558
+ }
4529
4559
  const normalizedOwner = req.owner.toLowerCase();
4530
4560
  const query = new URLSearchParams({
4531
4561
  owner: normalizedOwner,
4532
4562
  chainId: String(req.chainId)
4533
4563
  });
4534
- const endpoint = `/v2/taker/tier?${query.toString()}`;
4564
+ const endpoint = `/v2/taker/capacity?${query.toString()}`;
4535
4565
  return apiFetch({
4536
4566
  url: `${withApiBase(baseApiUrl)}${endpoint}`,
4537
4567
  method: "GET",
@@ -5252,6 +5282,125 @@ var getRateManagerReadFunction = (abi, functionName) => Array.isArray(abi) && ab
5252
5282
  (item) => item.type === "function" && item.name === functionName
5253
5283
  );
5254
5284
 
5285
+ // src/client/StakeOperations.ts
5286
+ function tupleValue(value, key, index) {
5287
+ if (Array.isArray(value)) return value[index];
5288
+ if (value && typeof value === "object") {
5289
+ return value[key];
5290
+ }
5291
+ return void 0;
5292
+ }
5293
+ function toBigInt2(value, label) {
5294
+ if (typeof value === "bigint") return value;
5295
+ if (typeof value === "number" || typeof value === "string") {
5296
+ return BigInt(value);
5297
+ }
5298
+ throw new Error(`Invalid StakeVault ${label}`);
5299
+ }
5300
+ function toBoolean(value, label) {
5301
+ if (typeof value === "boolean") return value;
5302
+ throw new Error(`Invalid StakeVault ${label}`);
5303
+ }
5304
+ var StakeOperations = class {
5305
+ constructor(config) {
5306
+ this.config = config;
5307
+ }
5308
+ getContract() {
5309
+ const address = this.config.getStakeVaultAddress();
5310
+ const abi = this.config.getStakeVaultAbi();
5311
+ const stakeToken = this.config.getStakeTokenAddress();
5312
+ if (!address || !abi || !stakeToken) {
5313
+ throw new Error("StakeVault not available for this chain/environment");
5314
+ }
5315
+ return { address, abi, stakeToken };
5316
+ }
5317
+ read(functionName, args = []) {
5318
+ const { address, abi } = this.getContract();
5319
+ return this.config.getPublicClient().readContract({
5320
+ address,
5321
+ abi,
5322
+ functionName,
5323
+ args
5324
+ });
5325
+ }
5326
+ getStakeBalance(staker) {
5327
+ return this.read("stakeBalance", [staker]);
5328
+ }
5329
+ getEligibleStake(staker) {
5330
+ return this.read("eligibleStake", [staker]);
5331
+ }
5332
+ getReservedStake(staker) {
5333
+ return this.read("reservedStake", [staker]);
5334
+ }
5335
+ getFreeStake(staker) {
5336
+ return this.read("freeStake", [staker]);
5337
+ }
5338
+ getStakeOwner(taker) {
5339
+ return this.read("stakeOwnerOf", [taker]);
5340
+ }
5341
+ getAllowedStakeOwner(taker) {
5342
+ return this.read("allowedStakeOwner", [taker]);
5343
+ }
5344
+ getStakeDelegationEnabled(taker) {
5345
+ return this.read("stakeDelegationEnabled", [taker]);
5346
+ }
5347
+ async getStakeWithdrawalRequest(staker) {
5348
+ const value = await this.read("getStakeWithdrawalRequest", [staker]);
5349
+ return {
5350
+ amount: toBigInt2(tupleValue(value, "amount", 0), "withdrawal amount"),
5351
+ requestedAt: toBigInt2(tupleValue(value, "requestedAt", 1), "withdrawal requestedAt"),
5352
+ availableAt: toBigInt2(tupleValue(value, "availableAt", 2), "withdrawal availableAt")
5353
+ };
5354
+ }
5355
+ async getStakeExitRequest(staker) {
5356
+ const value = await this.read("getExitRequest", [staker]);
5357
+ return {
5358
+ exiting: toBoolean(tupleValue(value, "exiting", 0), "exit status"),
5359
+ requestedAt: toBigInt2(tupleValue(value, "requestedAt", 1), "exit requestedAt"),
5360
+ availableAt: toBigInt2(tupleValue(value, "availableAt", 2), "exit availableAt")
5361
+ };
5362
+ }
5363
+ async getStakeVaultState(params) {
5364
+ const taker = params.taker ?? params.staker;
5365
+ const { stakeToken } = this.getContract();
5366
+ const [
5367
+ stakeOwner,
5368
+ allowedStakeOwner,
5369
+ delegationEnabled,
5370
+ staked,
5371
+ eligible,
5372
+ reserved,
5373
+ free,
5374
+ withdrawal,
5375
+ exit
5376
+ ] = await Promise.all([
5377
+ this.getStakeOwner(taker),
5378
+ this.getAllowedStakeOwner(taker),
5379
+ this.getStakeDelegationEnabled(taker),
5380
+ this.getStakeBalance(params.staker),
5381
+ this.getEligibleStake(params.staker),
5382
+ this.getReservedStake(params.staker),
5383
+ this.getFreeStake(params.staker),
5384
+ this.getStakeWithdrawalRequest(params.staker),
5385
+ this.getStakeExitRequest(params.staker)
5386
+ ]);
5387
+ return {
5388
+ staker: params.staker,
5389
+ taker,
5390
+ stakeToken,
5391
+ stakeOwner,
5392
+ allowedStakeOwner,
5393
+ delegationEnabled,
5394
+ staked,
5395
+ eligible,
5396
+ reserved,
5397
+ free,
5398
+ withdrawal,
5399
+ exit
5400
+ };
5401
+ }
5402
+ };
5403
+
5255
5404
  // src/indexer/rateManagerService.ts
5256
5405
  var DEFAULT_LIMIT2 = 50;
5257
5406
  var RATE_MANAGER_HISTORY_PAGE_SIZE = 250;
@@ -6311,6 +6460,56 @@ var Zkp2pClient = class {
6311
6460
  * @throws Error if walletClient is missing an account
6312
6461
  */
6313
6462
  constructor(opts) {
6463
+ /** Deposit USDC stake for the connected taker. */
6464
+ this.depositStake = this.buildStakeVaultMethod(
6465
+ "depositStake",
6466
+ (params) => [params.amount]
6467
+ );
6468
+ /** Deposit USDC stake for a different taker that has enabled delegation. */
6469
+ this.depositStakeFor = this.buildStakeVaultMethod(
6470
+ "depositStakeFor",
6471
+ (params) => [params.taker, params.amount]
6472
+ );
6473
+ /** Begin a partial stake-withdrawal delay. */
6474
+ this.requestStakeWithdrawal = this.buildStakeVaultMethod("requestStakeWithdrawal", (params) => [params.amount]);
6475
+ /** Cancel the connected staker's pending partial withdrawal. */
6476
+ this.cancelStakeWithdrawal = this.buildStakeVaultMethod("cancelStakeWithdrawal", () => []);
6477
+ /** Withdraw a matured partial stake-withdrawal request. */
6478
+ this.withdrawRequestedStake = this.buildStakeVaultMethod("withdrawRequestedStake", (params) => [params.recipient]);
6479
+ /** Begin a full exit, blocking new taking activity for the stake owner. */
6480
+ this.requestExit = this.buildStakeVaultMethod(
6481
+ "requestExit",
6482
+ () => []
6483
+ );
6484
+ /** Cancel a pending full exit. */
6485
+ this.cancelExit = this.buildStakeVaultMethod(
6486
+ "cancelExit",
6487
+ () => []
6488
+ );
6489
+ /** Withdraw all stake after a matured, fully settled exit. */
6490
+ this.withdrawStake = this.buildStakeVaultMethod(
6491
+ "withdrawStake",
6492
+ (params) => [params.recipient]
6493
+ );
6494
+ /** Allow or block third-party stake owners for the connected taker. */
6495
+ this.setStakeDelegationEnabled = this.buildStakeVaultMethod("setStakeDelegationEnabled", (params) => [params.enabled]);
6496
+ /** Select the stake owner whose portfolio backs the connected taker. */
6497
+ this.setAllowedStakeOwner = this.buildStakeVaultMethod("setAllowedStakeOwner", (params) => [params.stakeOwner]);
6498
+ /** Remove the connected taker's selected third-party stake owner. */
6499
+ this.clearStakeOwner = this.buildStakeVaultMethod(
6500
+ "clearStakeOwner",
6501
+ () => []
6502
+ );
6503
+ /** Release one or more RiskManager positions whose chargeback window matured. */
6504
+ this.releaseMaturedPositions = this.buildRiskManagerMethod("releaseMaturedPositions", (params) => [params.intentHashes]);
6505
+ /** Reconcile one failed OrchestratorV3 settlement callback. */
6506
+ this.reconcileSettlement = this.buildRiskManagerMethod("reconcileSettlement", (params) => [params.intentHash]);
6507
+ /** Reconcile multiple failed OrchestratorV3 settlement callbacks. */
6508
+ this.reconcileSettlements = this.buildRiskManagerMethod("reconcileSettlements", (params) => [params.intentHashes]);
6509
+ /** Reconcile one failed OrchestratorV3 cancellation callback. */
6510
+ this.reconcileCancellation = this.buildRiskManagerMethod("reconcileCancellation", (params) => [params.intentHash]);
6511
+ /** Reconcile multiple failed OrchestratorV3 cancellation callbacks. */
6512
+ this.reconcileCancellations = this.buildRiskManagerMethod("reconcileCancellations", (params) => [params.intentHashes]);
6314
6513
  // ╔═══════════════════════════════════════════════════════════════════════════╗
6315
6514
  // ║ CORE: DEPOSIT MANAGEMENT ║
6316
6515
  // ╚═══════════════════════════════════════════════════════════════════════════╝
@@ -7169,6 +7368,8 @@ var Zkp2pClient = class {
7169
7368
  this.escrowV2Abi = abis.escrowV2 ?? abis.escrow;
7170
7369
  this.orchestratorV2Address = toAddress(addresses.orchestratorV2 ?? addresses.orchestrator);
7171
7370
  this.orchestratorV2Abi = abis.orchestratorV2 ?? abis.orchestrator;
7371
+ this.orchestratorV3Address = toAddress(addresses.orchestratorV3);
7372
+ this.orchestratorV3Abi = abis.orchestratorV3;
7172
7373
  const configuredEscrowAddresses = (addresses.escrowAddresses ?? []).map((value) => toAddress(value)).filter((value) => Boolean(value));
7173
7374
  const configuredOrchestratorAddresses = (addresses.orchestratorAddresses ?? []).map((value) => toAddress(value)).filter((value) => Boolean(value));
7174
7375
  this.escrowAddresses = uniqAddresses([
@@ -7182,6 +7383,7 @@ var Zkp2pClient = class {
7182
7383
  }
7183
7384
  this.orchestratorAddresses = uniqAddresses([
7184
7385
  this.orchestratorV2Address ?? toAddress(addresses.orchestrator),
7386
+ this.orchestratorV3Address,
7185
7387
  ...configuredOrchestratorAddresses
7186
7388
  ]);
7187
7389
  this.orchestratorAddress = this.orchestratorV2Address ?? toAddress(addresses.orchestrator) ?? this.orchestratorAddresses[0];
@@ -7209,6 +7411,10 @@ var Zkp2pClient = class {
7209
7411
  this.rateManagerRegistryAbi = abis.rateManagerRegistry ?? this.rateManagerV1Abi;
7210
7412
  this.rateManagerControllerAddress = toAddress(addresses.rateManagerController);
7211
7413
  this.rateManagerControllerAbi = abis.rateManagerController;
7414
+ this.stakeVaultAddress = toAddress(addresses.stakeVault);
7415
+ this.stakeVaultAbi = abis.stakeVault;
7416
+ this.riskManagerAddress = toAddress(addresses.riskManager);
7417
+ this.riskManagerAbi = abis.riskManager;
7212
7418
  if (!this.rateManagerRegistryAddress || !this.rateManagerRegistryAbi) {
7213
7419
  try {
7214
7420
  const rateManagerContracts = getRateManagerContracts(this.chainId, this.runtimeEnv);
@@ -7234,6 +7440,8 @@ var Zkp2pClient = class {
7234
7440
  orchestratorAbi: this.orchestratorAbi,
7235
7441
  orchestratorV2Address: this.orchestratorV2Address,
7236
7442
  orchestratorV2Abi: this.orchestratorV2Abi,
7443
+ orchestratorV3Address: this.orchestratorV3Address,
7444
+ orchestratorV3Abi: this.orchestratorV3Abi,
7237
7445
  orchestratorAddresses: this.orchestratorAddresses
7238
7446
  });
7239
7447
  if (addresses.usdc) this._usdcAddress = addresses.usdc;
@@ -7289,6 +7497,12 @@ var Zkp2pClient = class {
7289
7497
  prepareContractTransaction: (tx) => this.prepareContractTransaction(tx)
7290
7498
  }
7291
7499
  });
7500
+ this._stakeOps = new StakeOperations({
7501
+ getPublicClient: () => this.publicClient,
7502
+ getStakeVaultAddress: () => this.stakeVaultAddress,
7503
+ getStakeVaultAbi: () => this.stakeVaultAbi,
7504
+ getStakeTokenAddress: () => this._usdcAddress
7505
+ });
7292
7506
  this._intentOps = new IntentOperations({
7293
7507
  getWalletClient: () => this.walletClient,
7294
7508
  getPublicClient: () => this.publicClient,
@@ -7746,6 +7960,28 @@ var Zkp2pClient = class {
7746
7960
  }
7747
7961
  );
7748
7962
  }
7963
+ buildStakeVaultMethod(functionName, buildArgs) {
7964
+ return this.buildContractMethod(
7965
+ () => ({
7966
+ address: this.stakeVaultAddress,
7967
+ abi: this.stakeVaultAbi,
7968
+ label: "StakeVault"
7969
+ }),
7970
+ functionName,
7971
+ buildArgs
7972
+ );
7973
+ }
7974
+ buildRiskManagerMethod(functionName, buildArgs) {
7975
+ return this.buildContractMethod(
7976
+ () => ({
7977
+ address: this.riskManagerAddress,
7978
+ abi: this.riskManagerAbi,
7979
+ label: "RiskManager"
7980
+ }),
7981
+ functionName,
7982
+ buildArgs
7983
+ );
7984
+ }
7749
7985
  buildEscrowMethod(functionName, buildArgs, buildValue) {
7750
7986
  return Object.assign(
7751
7987
  async (params) => {
@@ -8203,6 +8439,84 @@ var Zkp2pClient = class {
8203
8439
  });
8204
8440
  return { hadAllowance: false, hash };
8205
8441
  }
8442
+ // ╔═══════════════════════════════════════════════════════════════════════════╗
8443
+ // ║ CORE: TAKER STAKING ║
8444
+ // ╚═══════════════════════════════════════════════════════════════════════════╝
8445
+ /**
8446
+ * Return the resolved StakeVault coordinates for advanced wallet, relayer,
8447
+ * or reactive read integrations.
8448
+ */
8449
+ getStakeVaultContract() {
8450
+ return this._stakeOps.getContract();
8451
+ }
8452
+ /** Return the resolved OrchestratorV3 coordinates for advanced integrations. */
8453
+ getOrchestratorV3Contract() {
8454
+ if (!this.orchestratorV3Address || !this.orchestratorV3Abi) {
8455
+ throw new Error("OrchestratorV3 not available for this chain/environment");
8456
+ }
8457
+ return { address: this.orchestratorV3Address, abi: this.orchestratorV3Abi };
8458
+ }
8459
+ /** Return the resolved RiskManager coordinates for keeper integrations. */
8460
+ getRiskManagerContract() {
8461
+ if (!this.riskManagerAddress || !this.riskManagerAbi) {
8462
+ throw new Error("RiskManager not available for this chain/environment");
8463
+ }
8464
+ return { address: this.riskManagerAddress, abi: this.riskManagerAbi };
8465
+ }
8466
+ /**
8467
+ * Ensure the connected wallet has approved enough USDC for StakeVault.
8468
+ * If an approval is submitted, wait for it to confirm before depositing.
8469
+ */
8470
+ async ensureStakeAllowance(params) {
8471
+ const { address, stakeToken } = this._stakeOps.getContract();
8472
+ return this.ensureAllowance({
8473
+ token: stakeToken,
8474
+ spender: address,
8475
+ amount: params.amount,
8476
+ maxApprove: params.maxApprove,
8477
+ txOverrides: params.txOverrides
8478
+ });
8479
+ }
8480
+ /** Read total stake owned by an address directly from StakeVault. */
8481
+ getStakeBalance(staker) {
8482
+ return this._stakeOps.getStakeBalance(staker);
8483
+ }
8484
+ /** Read stake that currently backs taking capacity. */
8485
+ getEligibleStake(staker) {
8486
+ return this._stakeOps.getEligibleStake(staker);
8487
+ }
8488
+ /** Read stake reserved against active intents. */
8489
+ getReservedStake(staker) {
8490
+ return this._stakeOps.getReservedStake(staker);
8491
+ }
8492
+ /** Read stake currently available for withdrawal or new reservations. */
8493
+ getFreeStake(staker) {
8494
+ return this._stakeOps.getFreeStake(staker);
8495
+ }
8496
+ /** Resolve the effective stake owner backing a taker. */
8497
+ getStakeOwner(taker) {
8498
+ return this._stakeOps.getStakeOwner(taker);
8499
+ }
8500
+ /** Read the stake owner explicitly selected by a taker. */
8501
+ getAllowedStakeOwner(taker) {
8502
+ return this._stakeOps.getAllowedStakeOwner(taker);
8503
+ }
8504
+ /** Read whether a taker allows third-party stake delegation. */
8505
+ getStakeDelegationEnabled(taker) {
8506
+ return this._stakeOps.getStakeDelegationEnabled(taker);
8507
+ }
8508
+ /** Read the connected staker's pending partial withdrawal. */
8509
+ getStakeWithdrawalRequest(staker) {
8510
+ return this._stakeOps.getStakeWithdrawalRequest(staker);
8511
+ }
8512
+ /** Read the connected staker's pending full exit. */
8513
+ getStakeExitRequest(staker) {
8514
+ return this._stakeOps.getStakeExitRequest(staker);
8515
+ }
8516
+ /** Read the complete authoritative StakeVault state needed by a staking UI. */
8517
+ getStakeVaultState(params) {
8518
+ return this._stakeOps.getStakeVaultState(params);
8519
+ }
8206
8520
  /**
8207
8521
  * Registers payee details with the curator API and returns hashed on-chain IDs.
8208
8522
  *
@@ -8638,25 +8952,48 @@ var Zkp2pClient = class {
8638
8952
  return appendReferrerFeeDisplayFieldsToBestByPlatform(enrichedQuote, referrerFeeConfig);
8639
8953
  }
8640
8954
  // ───────────────────────────────────────────────────────────────────────────
8641
- // SUPPORTING: TAKER TIER
8642
- // (Used by frontends to display taker limits)
8955
+ // SUPPORTING: TAKER STAKE & CAPACITY
8956
+ // (Used by frontends to display the stake portfolio and per-platform taking
8957
+ // capacity; never used to filter quotes)
8643
8958
  // ───────────────────────────────────────────────────────────────────────────
8644
8959
  /**
8645
- * **Supporting Method** - Fetches taker tier information for an address.
8960
+ * **Supporting Method** - Fetches the stake portfolio backing a taker:
8961
+ * staked/pending-withdrawal/eligible/reserved/free balances, reservation
8962
+ * aggregates, delegation, and exit state.
8646
8963
  *
8647
- * @param req - Taker tier request parameters
8648
- * @param req.owner - Taker address
8964
+ * @param req - Stake request parameters
8965
+ * @param req.owner - Taker address (the resolved stake owner may differ)
8649
8966
  * @param req.chainId - Chain ID
8650
8967
  * @param opts - Optional overrides for API URL and timeout
8651
- * @returns Taker tier response
8968
+ * @returns Taker stake response
8652
8969
  */
8653
- async getTakerTier(req, opts) {
8970
+ async getTakerStake(req, opts) {
8654
8971
  const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
8655
8972
  /\/$/,
8656
8973
  ""
8657
8974
  );
8658
8975
  const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
8659
- return apiGetTakerTier(req, baseApiUrl, timeoutMs);
8976
+ return apiGetTakerStake(req, baseApiUrl, timeoutMs);
8977
+ }
8978
+ /**
8979
+ * **Supporting Method** - Fetches per-platform bonded taking capacity, free
8980
+ * takes, curve terms, warnings, and operational gates for a taker's shared
8981
+ * stake portfolio. Platform capacities are alternative views of one shared
8982
+ * balance and must never be summed.
8983
+ *
8984
+ * @param req - Capacity request parameters
8985
+ * @param req.owner - Taker address (the resolved stake owner may differ)
8986
+ * @param req.chainId - Chain ID
8987
+ * @param opts - Optional overrides for API URL and timeout
8988
+ * @returns Taker capacity response
8989
+ */
8990
+ async getTakerCapacity(req, opts) {
8991
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
8992
+ /\/$/,
8993
+ ""
8994
+ );
8995
+ const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
8996
+ return apiGetTakerCapacity(req, baseApiUrl, timeoutMs);
8660
8997
  }
8661
8998
  /**
8662
8999
  * Fetch a referral dashboard. Pass `address` for a public wallet-keyed read;
@@ -8987,12 +9324,15 @@ var Zkp2pClient = class {
8987
9324
  escrowAddresses: this.escrowAddresses,
8988
9325
  orchestrator: this.orchestratorAddress,
8989
9326
  orchestratorV2: this.orchestratorV2Address,
9327
+ orchestratorV3: this.orchestratorV3Address,
8990
9328
  orchestratorAddresses: this.orchestratorAddresses,
8991
9329
  protocolViewer: this.protocolViewerAddress,
8992
9330
  protocolViewerEntries: this._protocolViewerEntries.map((e) => e.address),
8993
9331
  unifiedPaymentVerifier: this.unifiedPaymentVerifier,
8994
9332
  rateManagerV1: this.rateManagerV1Address,
8995
9333
  orchestratorRegistry: this.orchestratorRegistryAddress,
9334
+ stakeVault: this.stakeVaultAddress,
9335
+ riskManager: this.riskManagerAddress,
8996
9336
  usdc: this._usdcAddress
8997
9337
  };
8998
9338
  }
@@ -9067,6 +9407,97 @@ var createPeerExtensionSdk = (options = {}) => ({
9067
9407
  });
9068
9408
  var peerExtensionSdk = createPeerExtensionSdk();
9069
9409
 
9070
- export { BASE_BUILDER_CODE, CHAINLINK_ORACLE_ADAPTER, CHAINLINK_ORACLE_FEEDS, ContractRouter, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, IndexerClient, IndexerDepositService, IndexerRateManagerService, 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, apiGetQuotesBestByPlatform, apiGetReferralDashboard, apiGetReferralEarnings, apiGetTakerTier, apiLookupReferralCode, apiPostDepositDetails, apiRedeemReferralCode, apiRequestIdentityAttestation, apiUpdateReferralCode, apiUploadGoogleOAuthSellerCredential, apiUploadSellerCredentialBundle, apiValidatePayeeDetails, apiVerifyBuyerTeePayment, appendAttributionToCalldata, assertValidReferrerFeeConfig, 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, referrerFeeConfigToPreciseUnits, sendTransactionWithAttribution, setLogLevel, validateOracleFeedsOnChain };
9410
+ // src/riskMath.ts
9411
+ var RISK_BPS_DENOMINATOR = 10000n;
9412
+ var RISK_SECONDS_PER_HOUR = 3600n;
9413
+ var RISK_GRIEFING_DENOMINATOR = RISK_BPS_DENOMINATOR * RISK_SECONDS_PER_HOUR;
9414
+ function integer(value, label) {
9415
+ if (typeof value === "number" && (!Number.isSafeInteger(value) || value < 0)) {
9416
+ throw new RangeError(`${label} must be a non-negative safe integer`);
9417
+ }
9418
+ const parsed = BigInt(value.toString());
9419
+ if (parsed < 0n) throw new RangeError(`${label} must be non-negative`);
9420
+ return parsed;
9421
+ }
9422
+ function ceilDiv(numerator, denominator) {
9423
+ if (denominator <= 0n) throw new RangeError("denominator must be positive");
9424
+ if (numerator === 0n) return 0n;
9425
+ return (numerator - 1n) / denominator + 1n;
9426
+ }
9427
+ function calculateMaxGriefingBond(amount, terms) {
9428
+ const bondedAmount = integer(amount, "amount");
9429
+ const maxIntentPeriod = integer(terms.maxIntentPeriod, "maxIntentPeriod");
9430
+ const griefingCliff = integer(terms.griefingCliff, "griefingCliff");
9431
+ const slope = integer(terms.griefingPenaltyBpsPerHour, "griefingPenaltyBpsPerHour");
9432
+ if (slope === 0n || maxIntentPeriod <= griefingCliff) return 0n;
9433
+ return ceilDiv(
9434
+ bondedAmount * slope * (maxIntentPeriod - griefingCliff),
9435
+ RISK_GRIEFING_DENOMINATOR
9436
+ );
9437
+ }
9438
+ function calculateChargebackReserve(amount, reserveBps) {
9439
+ const bondedAmount = integer(amount, "amount");
9440
+ const reserveRatio = integer(reserveBps, "reserveBps");
9441
+ if (reserveRatio > RISK_BPS_DENOMINATOR) {
9442
+ throw new RangeError("reserveBps cannot exceed 10,000");
9443
+ }
9444
+ return ceilDiv(bondedAmount * reserveRatio, RISK_BPS_DENOMINATOR);
9445
+ }
9446
+ function calculateRequiredReservation(amount, terms, reserveBps) {
9447
+ const griefingBond = calculateMaxGriefingBond(amount, terms);
9448
+ const chargebackReserve = calculateChargebackReserve(amount, reserveBps);
9449
+ return griefingBond > chargebackReserve ? griefingBond : chargebackReserve;
9450
+ }
9451
+ function calculateGriefingPenalty(amount, createdAt, cancelledAt, terms) {
9452
+ const bondedAmount = integer(amount, "amount");
9453
+ const created = integer(createdAt, "createdAt");
9454
+ const cancelled = integer(cancelledAt, "cancelledAt");
9455
+ const maxIntentPeriod = integer(terms.maxIntentPeriod, "maxIntentPeriod");
9456
+ const griefingCliff = integer(terms.griefingCliff, "griefingCliff");
9457
+ const slope = integer(terms.griefingPenaltyBpsPerHour, "griefingPenaltyBpsPerHour");
9458
+ if (cancelled <= created) return { penalty: 0n, effectiveElapsed: 0n };
9459
+ const elapsed = cancelled - created;
9460
+ const effectiveElapsed = elapsed < maxIntentPeriod ? elapsed : maxIntentPeriod;
9461
+ if (slope === 0n || effectiveElapsed <= griefingCliff) {
9462
+ return { penalty: 0n, effectiveElapsed };
9463
+ }
9464
+ const chargeableTime = effectiveElapsed - griefingCliff;
9465
+ return {
9466
+ penalty: ceilDiv(bondedAmount * slope * chargeableTime, RISK_GRIEFING_DENOMINATOR),
9467
+ effectiveElapsed
9468
+ };
9469
+ }
9470
+ function calculateBondedTakingCapacity(freeStake, terms, reserveBps) {
9471
+ const available = integer(freeStake, "freeStake");
9472
+ const maxIntentPeriod = integer(terms.maxIntentPeriod, "maxIntentPeriod");
9473
+ const griefingCliff = integer(terms.griefingCliff, "griefingCliff");
9474
+ const slope = integer(terms.griefingPenaltyBpsPerHour, "griefingPenaltyBpsPerHour");
9475
+ const reserveRatio = integer(reserveBps, "reserveBps");
9476
+ if (reserveRatio > RISK_BPS_DENOMINATOR) {
9477
+ throw new RangeError("reserveBps cannot exceed 10,000");
9478
+ }
9479
+ const griefingRateNumerator = maxIntentPeriod > griefingCliff ? slope * (maxIntentPeriod - griefingCliff) : 0n;
9480
+ const griefingCapacity = griefingRateNumerator === 0n ? null : available * RISK_GRIEFING_DENOMINATOR / griefingRateNumerator;
9481
+ const chargebackCapacity = reserveRatio === 0n ? null : available * RISK_BPS_DENOMINATOR / reserveRatio;
9482
+ let bondedTakingCapacity;
9483
+ if (griefingCapacity === null) bondedTakingCapacity = chargebackCapacity;
9484
+ else if (chargebackCapacity === null) bondedTakingCapacity = griefingCapacity;
9485
+ else {
9486
+ bondedTakingCapacity = griefingCapacity < chargebackCapacity ? griefingCapacity : chargebackCapacity;
9487
+ }
9488
+ return { griefingCapacity, chargebackCapacity, bondedTakingCapacity };
9489
+ }
9490
+ function calculateFreeTakeCapacity(freeTakeCount, freeTakesUsed, freeTakeAmount) {
9491
+ const count = integer(freeTakeCount, "freeTakeCount");
9492
+ const used = integer(freeTakesUsed, "freeTakesUsed");
9493
+ const amount = integer(freeTakeAmount, "freeTakeAmount");
9494
+ const remainingFreeTakes = used >= count ? 0n : count - used;
9495
+ return {
9496
+ remainingFreeTakes,
9497
+ freeTakingCapacity: remainingFreeTakes * amount
9498
+ };
9499
+ }
9500
+
9501
+ export { BASE_BUILDER_CODE, CHAINLINK_ORACLE_ADAPTER, CHAINLINK_ORACLE_FEEDS, ContractRouter, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, IndexerClient, IndexerDepositService, IndexerRateManagerService, 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, RISK_GRIEFING_DENOMINATOR, RISK_SECONDS_PER_HOUR, SPREAD_ORACLE_FEEDS, SUPPORTED_CHAIN_IDS, TOKEN_METADATA, ZKP2P_ANDROID_REFERRER, ZKP2P_IOS_REFERRER, Zkp2pClient, apiCreateReferralCode, apiCreateSellerCredentialBundle, apiGetDepositBundle, apiGetOrderbook, apiGetOrderbookTable, apiGetOwnerDeposits, apiGetPayeeDetails, apiGetQuotesBestByPlatform, apiGetReferralDashboard, apiGetReferralEarnings, apiGetTakerCapacity, apiGetTakerStake, apiLookupReferralCode, apiPostDepositDetails, apiRedeemReferralCode, apiRequestIdentityAttestation, apiUpdateReferralCode, apiUploadGoogleOAuthSellerCredential, apiUploadSellerCredentialBundle, apiValidatePayeeDetails, apiVerifyBuyerTeePayment, appendAttributionToCalldata, assertValidReferrerFeeConfig, calculateBondedTakingCapacity, calculateChargebackReserve, calculateFreeTakeCapacity, calculateGriefingPenalty, calculateMaxGriefingBond, calculateRequiredReservation, 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, referrerFeeConfigToPreciseUnits, sendTransactionWithAttribution, setLogLevel, validateOracleFeedsOnChain };
9071
9502
  //# sourceMappingURL=index.mjs.map
9072
9503
  //# sourceMappingURL=index.mjs.map