@klappay/types 5.0.0 → 5.1.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.js CHANGED
@@ -79,6 +79,7 @@ __export(index_exports, {
79
79
  MetricsQuerySchema: () => MetricsQuerySchema,
80
80
  MetricsResourceSchema: () => MetricsResourceSchema,
81
81
  NETWORK_EXPLORERS: () => NETWORK_EXPLORERS,
82
+ NETWORK_FAMILIES: () => NETWORK_FAMILIES,
82
83
  NETWORK_LABELS: () => NETWORK_LABELS,
83
84
  NetworkSchema: () => NetworkSchema,
84
85
  OPERATIONAL_NETWORKS: () => OPERATIONAL_NETWORKS,
@@ -87,6 +88,7 @@ __export(index_exports, {
87
88
  PAGINATION_LIMIT_MIN: () => PAGINATION_LIMIT_MIN,
88
89
  PaginatedChargesSchema: () => PaginatedChargesSchema,
89
90
  PaginatedPendingDistributionsSchema: () => PaginatedPendingDistributionsSchema,
91
+ PaginatedRecipientsSchema: () => PaginatedRecipientsSchema,
90
92
  PaginatedWebhookDeliveriesSchema: () => PaginatedWebhookDeliveriesSchema,
91
93
  PaginationQuerySchema: () => PaginationQuerySchema,
92
94
  PendingDistributionEventSchema: () => PendingDistributionEventSchema,
@@ -98,6 +100,7 @@ __export(index_exports, {
98
100
  SandboxTriggerSchema: () => SandboxTriggerSchema,
99
101
  SetRecipientPayoutSchema: () => SetRecipientPayoutSchema,
100
102
  SettlementStatusSchema: () => SettlementStatusSchema,
103
+ SplitAddressSchema: () => SplitAddressSchema,
101
104
  SplitDistributionStatusSchema: () => SplitDistributionStatusSchema,
102
105
  SplitRecipientInputSchema: () => SplitRecipientInputSchema,
103
106
  SplitRecipientSchema: () => SplitRecipientSchema,
@@ -124,37 +127,69 @@ __export(index_exports, {
124
127
  WebhookListItemSchema: () => WebhookListItemSchema,
125
128
  WebhookPayloadSchema: () => WebhookPayloadSchema,
126
129
  WebhookSchema: () => WebhookSchema,
130
+ addressesEqual: () => addressesEqual,
127
131
  findConflictingScopes: () => findConflictingScopes,
128
132
  getTokenDeployment: () => getTokenDeployment,
133
+ isEvmAddress: () => isEvmAddress,
129
134
  isPaymentDeploymentEnabled: () => isPaymentDeploymentEnabled,
135
+ isSplitAddress: () => isSplitAddress,
136
+ isTronAddress: () => isTronAddress,
130
137
  listSwapAlternatives: () => listSwapAlternatives,
131
- paginatedSchema: () => paginatedSchema
138
+ paginatedSchema: () => paginatedSchema,
139
+ tronAddress: () => tronAddress
132
140
  });
133
141
  module.exports = __toCommonJS(index_exports);
134
142
 
135
- // src/errors.ts
143
+ // src/addresses.ts
136
144
  var import_zod = require("zod");
137
- var ErrorPayloadSchema = import_zod.z.object({
138
- error: import_zod.z.object({
139
- code: import_zod.z.string().describe(
145
+
146
+ // src/addresses.constants.ts
147
+ var EVM_ADDRESS_REGEX = /^0x[0-9a-f]{40}$/i;
148
+ var TRON_ADDRESS_REGEX = /^T[1-9A-HJ-NP-Za-km-z]{33}$/;
149
+ function isEvmAddress(value) {
150
+ return EVM_ADDRESS_REGEX.test(value);
151
+ }
152
+ function isTronAddress(value) {
153
+ return TRON_ADDRESS_REGEX.test(value);
154
+ }
155
+ function isSplitAddress(value) {
156
+ return isEvmAddress(value) || isTronAddress(value);
157
+ }
158
+ function tronAddress(value) {
159
+ if (!isTronAddress(value)) throw new Error(`not a valid TRON address: ${value}`);
160
+ return value;
161
+ }
162
+ function addressesEqual(a, b) {
163
+ if (isEvmAddress(a) && isEvmAddress(b)) return a.toLowerCase() === b.toLowerCase();
164
+ return a === b;
165
+ }
166
+
167
+ // src/addresses.ts
168
+ var SplitAddressSchema = import_zod.z.string().refine(isSplitAddress, "must be a valid EVM (0x...) or TRON (T...) address");
169
+
170
+ // src/errors.ts
171
+ var import_zod2 = require("zod");
172
+ var ErrorPayloadSchema = import_zod2.z.object({
173
+ error: import_zod2.z.object({
174
+ code: import_zod2.z.string().describe(
140
175
  "A stable, machine-readable error identifier (e.g. `validation_error`, `charge_not_found`)."
141
176
  ),
142
- message: import_zod.z.string().describe(
177
+ message: import_zod2.z.string().describe(
143
178
  "Human-readable explanation, safe to log or show a developer \u2014 not meant for end users."
144
179
  ),
145
- param: import_zod.z.string().optional().describe("Which request field the error refers to, when applicable.")
180
+ param: import_zod2.z.string().optional().describe("Which request field the error refers to, when applicable.")
146
181
  })
147
182
  });
148
183
 
149
184
  // src/environment.ts
150
- var import_zod2 = require("zod");
151
- var EnvironmentSchema = import_zod2.z.enum(["live", "test"]).describe(
185
+ var import_zod3 = require("zod");
186
+ var EnvironmentSchema = import_zod3.z.enum(["live", "test"]).describe(
152
187
  "`live` or `test`, matching the `klap_live_.../klap_test_...` prefix of the API key that created or is scoped to this resource. `live` uses the selected network's mainnet with real funds; `test` uses its separately configured testnet. Token contracts and availability are resolved per network/environment; a missing test deployment never falls back to live."
153
188
  );
154
189
 
155
190
  // src/api-key-scopes.ts
156
- var import_zod3 = require("zod");
157
- var ApiKeyScopeSchema = import_zod3.z.enum([
191
+ var import_zod4 = require("zod");
192
+ var ApiKeyScopeSchema = import_zod4.z.enum([
158
193
  "charges:read",
159
194
  "charges:write",
160
195
  "webhooks:read",
@@ -186,7 +221,7 @@ function findConflictingScopes(scopes) {
186
221
  }
187
222
 
188
223
  // src/networks.ts
189
- var import_zod4 = require("zod");
224
+ var import_zod5 = require("zod");
190
225
 
191
226
  // src/networks.constants.ts
192
227
  var NETWORK_LABELS = {
@@ -196,7 +231,9 @@ var NETWORK_LABELS = {
196
231
  ethereum: "Ethereum",
197
232
  arbitrum: "Arbitrum",
198
233
  avalanche: "Avalanche",
199
- bnb: "BNB Chain"
234
+ bnb: "BNB Chain",
235
+ tron: "TRON",
236
+ arc: "Arc"
200
237
  };
201
238
  var NETWORK_EXPLORERS = {
202
239
  base: "https://basescan.org",
@@ -205,7 +242,9 @@ var NETWORK_EXPLORERS = {
205
242
  ethereum: "https://etherscan.io",
206
243
  arbitrum: "https://arbiscan.io",
207
244
  avalanche: "https://snowtrace.io",
208
- bnb: "https://bscscan.com"
245
+ bnb: "https://bscscan.com",
246
+ tron: "https://tronscan.org",
247
+ arc: "https://explorer.arc.io"
209
248
  };
210
249
  var EVM_NETWORKS = [
211
250
  "base",
@@ -214,7 +253,8 @@ var EVM_NETWORKS = [
214
253
  "ethereum",
215
254
  "arbitrum",
216
255
  "avalanche",
217
- "bnb"
256
+ "bnb",
257
+ "arc"
218
258
  ];
219
259
  var OPERATIONAL_NETWORKS = [
220
260
  "base",
@@ -223,7 +263,9 @@ var OPERATIONAL_NETWORKS = [
223
263
  "polygon",
224
264
  "ethereum",
225
265
  "avalanche",
226
- "bnb"
266
+ "bnb",
267
+ "arc",
268
+ "tron"
227
269
  ];
228
270
  var CHAIN_IDS = {
229
271
  base: { live: 8453, test: 84532 },
@@ -232,35 +274,47 @@ var CHAIN_IDS = {
232
274
  polygon: { live: 137 },
233
275
  arbitrum: { live: 42161 },
234
276
  avalanche: { live: 43114 },
235
- bnb: { live: 56 }
277
+ bnb: { live: 56 },
278
+ arc: { live: 5042, test: 5042002 }
279
+ };
280
+ var NETWORK_FAMILIES = {
281
+ base: "evm-official",
282
+ optimism: "evm-official",
283
+ polygon: "evm-official",
284
+ ethereum: "evm-official",
285
+ arbitrum: "evm-official",
286
+ avalanche: "evm-official",
287
+ bnb: "evm-official",
288
+ tron: "tron",
289
+ arc: "arc"
236
290
  };
237
291
 
238
292
  // src/networks.ts
239
- var NetworkSchema = import_zod4.z.enum(["base", "optimism", "polygon", "ethereum", "arbitrum", "avalanche", "bnb"]).describe("The blockchain a charge/payment is on.");
293
+ var NetworkSchema = import_zod5.z.enum(["base", "optimism", "polygon", "ethereum", "arbitrum", "avalanche", "bnb", "tron", "arc"]).describe("The blockchain a charge/payment is on.");
240
294
 
241
295
  // src/pagination.ts
242
- var import_zod5 = require("zod");
296
+ var import_zod6 = require("zod");
243
297
  var PAGINATION_LIMIT_MIN = 1;
244
298
  var PAGINATION_LIMIT_MAX = 100;
245
299
  var PAGINATION_LIMIT_DEFAULT = 20;
246
- var PaginationQuerySchema = import_zod5.z.object({
247
- limit: import_zod5.z.coerce.number().min(PAGINATION_LIMIT_MIN).max(PAGINATION_LIMIT_MAX).default(PAGINATION_LIMIT_DEFAULT).describe(
300
+ var PaginationQuerySchema = import_zod6.z.object({
301
+ limit: import_zod6.z.coerce.number().min(PAGINATION_LIMIT_MIN).max(PAGINATION_LIMIT_MAX).default(PAGINATION_LIMIT_DEFAULT).describe(
248
302
  `Max items to return per page (${PAGINATION_LIMIT_MIN}\u2013${PAGINATION_LIMIT_MAX}, default ${PAGINATION_LIMIT_DEFAULT}).`
249
303
  ),
250
- cursor: import_zod5.z.string().max(500).optional().describe(
304
+ cursor: import_zod6.z.string().max(500).optional().describe(
251
305
  "Opaque \u2014 pass the previous response's `nextCursor` verbatim to fetch the next page. Never construct or parse this value yourself; its shape is not part of the public contract and may change."
252
306
  )
253
307
  });
254
308
  function paginatedSchema(itemSchema) {
255
- return import_zod5.z.object({
256
- data: import_zod5.z.array(itemSchema),
257
- nextCursor: import_zod5.z.string().nullable().describe("Pass as `cursor` to fetch the next page. `null` when there are no more results."),
258
- hasMore: import_zod5.z.boolean()
309
+ return import_zod6.z.object({
310
+ data: import_zod6.z.array(itemSchema),
311
+ nextCursor: import_zod6.z.string().nullable().describe("Pass as `cursor` to fetch the next page. `null` when there are no more results."),
312
+ hasMore: import_zod6.z.boolean()
259
313
  });
260
314
  }
261
315
 
262
316
  // src/tokens.ts
263
- var import_zod6 = require("zod");
317
+ var import_zod7 = require("zod");
264
318
 
265
319
  // src/tokens.constants.ts
266
320
  var TOKEN_DECIMALS = 6;
@@ -281,7 +335,11 @@ var TOKEN_DEPLOYMENTS = {
281
335
  },
282
336
  arbitrum: { live: { address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", decimals: 6 } },
283
337
  avalanche: { live: { address: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", decimals: 6 } },
284
- bnb: { live: { address: "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d", decimals: 18 } }
338
+ bnb: { live: { address: "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d", decimals: 18 } },
339
+ arc: {
340
+ live: { address: "0x3600000000000000000000000000000000000000", decimals: 6 },
341
+ test: { address: "0x3600000000000000000000000000000000000000", decimals: 6 }
342
+ }
285
343
  },
286
344
  USDT: {
287
345
  base: { live: { address: "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2", decimals: 6 } },
@@ -290,7 +348,11 @@ var TOKEN_DEPLOYMENTS = {
290
348
  ethereum: { live: { address: "0xdAC17F958D2ee523a2206206994597C13D831ec7", decimals: 6 } },
291
349
  arbitrum: { live: { address: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", decimals: 6 } },
292
350
  avalanche: { live: { address: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7", decimals: 6 } },
293
- bnb: { live: { address: "0x55d398326f99059fF775485246999027B3197955", decimals: 18 } }
351
+ bnb: { live: { address: "0x55d398326f99059fF775485246999027B3197955", decimals: 18 } },
352
+ tron: {
353
+ live: { address: tronAddress("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"), decimals: 6 },
354
+ test: { address: tronAddress("TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf"), decimals: 6 }
355
+ }
294
356
  }
295
357
  };
296
358
  function getTokenDeployment(token, network, environment) {
@@ -302,7 +364,7 @@ function isPaymentDeploymentEnabled(token, network, environment) {
302
364
  }
303
365
  function deriveAddresses(deployments) {
304
366
  const addresses = {};
305
- for (const network of EVM_NETWORKS) {
367
+ for (const network of Object.keys(deployments)) {
306
368
  const byEnvironment = deployments[network];
307
369
  if (!byEnvironment) continue;
308
370
  const networkAddresses = {};
@@ -320,12 +382,12 @@ var TOKEN_ADDRESSES = {
320
382
  };
321
383
 
322
384
  // src/tokens.ts
323
- var TokenSchema = import_zod6.z.enum(["USDC", "USDT"]).describe(
385
+ var TokenSchema = import_zod7.z.enum(["USDC", "USDT"]).describe(
324
386
  "Which stablecoin the payer will send. Availability depends on `network` and `environment`; check `GET /v1/networks` before creating a charge. Unconfigured or disabled pairs are rejected with `422 token_not_supported`. Base, Optimism, and Ethereum have USDC test deployments; no test USDT is configured. The catalog includes both BNB Chain tokens for historical interpretation, but payments with either are currently disabled. Both configured BNB contracts are Binance-Peg tokens with 18 decimals; the other configured deployments use 6. Binance-Peg tokens carry Binance custody/backing risk and must not be represented as direct Circle/Tether issuance. Resolve address and decimals together with `getTokenDeployment`; a catalog entry alone does not imply payment availability."
325
387
  );
326
388
 
327
389
  // src/alt-tokens.ts
328
- var import_zod7 = require("zod");
390
+ var import_zod8 = require("zod");
329
391
 
330
392
  // src/alt-tokens.constants.ts
331
393
  var ALT_TOKEN_DECIMALS = {
@@ -373,14 +435,18 @@ var ALT_TOKEN_ADDRESSES = {
373
435
  BTC: "0x2297aebd383787a160dd0d9f71508148769342e3",
374
436
  LINK: "0x5947BB275c521040051D82396192181b413227A3"
375
437
  },
376
- bnb: { BNB: "native" }
438
+ bnb: { BNB: "native" },
439
+ tron: {},
440
+ arc: {
441
+ BTC: "0x171A4217b86A807A64eB94757Db6849fb4bDbAA0"
442
+ }
377
443
  };
378
444
 
379
445
  // src/alt-tokens.ts
380
- var AltTokenSchema = import_zod7.z.enum(["ETH", "BNB", "POL", "AVAX", "BTC", "LINK", "ARB", "OP", "CBETH"]).describe(
446
+ var AltTokenSchema = import_zod8.z.enum(["ETH", "BNB", "POL", "AVAX", "BTC", "LINK", "ARB", "OP", "CBETH"]).describe(
381
447
  "A non-stablecoin cryptocurrency Klappay trusts as swap input for a charge, via the 0x Swap API \u2014 swapped to one of the charge's `acceptedPayments` tokens before it ever reaches the merchant, so the merchant always receives USDC/USDT regardless of what the payer sent. Trusted on a given network only when it has deep, reputably-issued/custodied liquidity there: each network's own native currency, `BTC` (wrapped) on the networks with a trusted deployment, `LINK` (Chainlink's own official per-chain deployment, except Avalanche's bridged `LINK.e`), and a small set of chain-specific blue chips (`ARB` on Arbitrum, `OP` on Optimism, `CBETH` on Base) \u2014 see `ALT_TOKEN_ADDRESSES` for the authoritative per-network list, never assume every value here is available on every network. `POL` replaced `MATIC` as Polygon's native currency name (Polygon's own token migration, 2024) \u2014 this schema tracks the network's current native asset, not the deprecated ticker."
382
448
  );
383
- var SwapAlternativeSchema = import_zod7.z.object({
449
+ var SwapAlternativeSchema = import_zod8.z.object({
384
450
  token: AltTokenSchema,
385
451
  network: NetworkSchema.describe(
386
452
  "Which network to send `token` on \u2014 pass both as `inputToken`/`inputNetwork` to `POST /v1/charges/{id}/quote`. The same token can appear more than once here, once per network that trusts it and that this charge accepts payment on."
@@ -397,77 +463,77 @@ function listSwapAlternatives(networks) {
397
463
  }
398
464
 
399
465
  // src/charges.ts
400
- var import_zod11 = require("zod");
466
+ var import_zod12 = require("zod");
401
467
 
402
468
  // src/checkout-metadata.ts
403
- var import_zod8 = require("zod");
469
+ var import_zod9 = require("zod");
404
470
  var CHECKOUT_PRODUCTS_MAX = 20;
405
- var CheckoutProductSchema = import_zod8.z.object({
406
- name: import_zod8.z.string().min(1).max(200).describe("What the payer is buying, shown as-is on the hosted checkout page."),
407
- quantity: import_zod8.z.number().int().positive().max(9999).optional().describe("How many of this item. Omit for a single, unquantified item."),
408
- imageUrl: import_zod8.z.string().url().max(2048).refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
471
+ var CheckoutProductSchema = import_zod9.z.object({
472
+ name: import_zod9.z.string().min(1).max(200).describe("What the payer is buying, shown as-is on the hosted checkout page."),
473
+ quantity: import_zod9.z.number().int().positive().max(9999).optional().describe("How many of this item. Omit for a single, unquantified item."),
474
+ imageUrl: import_zod9.z.string().url().max(2048).refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
409
475
  "Product image, fetched only by the payer's own browser \u2014 Klappay never fetches it server-side. Must be `http(s)`."
410
476
  )
411
477
  });
412
- var KlappayCheckoutMetadataSchema = import_zod8.z.object({
413
- products: import_zod8.z.array(CheckoutProductSchema).max(CHECKOUT_PRODUCTS_MAX).optional().describe(
478
+ var KlappayCheckoutMetadataSchema = import_zod9.z.object({
479
+ products: import_zod9.z.array(CheckoutProductSchema).max(CHECKOUT_PRODUCTS_MAX).optional().describe(
414
480
  `What the payer is buying, shown on the hosted checkout page \u2014 up to ${CHECKOUT_PRODUCTS_MAX} items. Purely informational: never validated against \`amount\`, never used by any payment or distribution logic.`
415
481
  )
416
482
  }).describe(
417
483
  "Reserved for Klappay \u2014 the one namespace inside `metadata` whose format is defined and enforced by Klappay, not by you. A `metadata.klappay` that does not match this shape is rejected outright (`400 validation_error`), unlike every other key in `metadata`, which accepts absolutely anything and never fails validation."
418
484
  );
419
- var MetadataWithKlappaySchema = import_zod8.z.object({ klappay: KlappayCheckoutMetadataSchema.optional() }).catchall(import_zod8.z.unknown()).describe(
485
+ var MetadataWithKlappaySchema = import_zod9.z.object({ klappay: KlappayCheckoutMetadataSchema.optional() }).catchall(import_zod9.z.unknown()).describe(
420
486
  "Arbitrary key/value data, returned as-is on every read. Put whatever you want in here \u2014 none of it is validated, except the `klappay` key, which is reserved for Klappay: if present, it must match `KlappayCheckoutMetadataSchema` exactly, or the whole request is rejected with `400 validation_error`."
421
487
  );
422
488
 
423
489
  // src/escrow.ts
424
- var import_zod9 = require("zod");
425
- var EscrowConfigSchema = import_zod9.z.object({
426
- releaserAddress: import_zod9.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").optional().describe(
490
+ var import_zod10 = require("zod");
491
+ var EscrowConfigSchema = import_zod10.z.object({
492
+ releaserAddress: import_zod10.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").optional().describe(
427
493
  "The only address ever authorized to release this charge's escrowed funds \u2014 set once at creation, immutable after. Klappay never holds a key with any release authority of its own; every release requires a signature from this address, verified on-chain, never taken on faith. Omit to default to the API key's own `payoutAddress` \u2014 the common case where the merchant releasing their own charge is the same wallet they already get paid to. Pass an explicit address only when the releaser is a different party (e.g. an operational key distinct from the payout wallet). Not validated against anything else \u2014 any well-formed address is accepted, since Klappay never custodies these funds."
428
494
  )
429
495
  });
430
- var ReleaseEscrowRequestSchema = import_zod9.z.object({
431
- signature: import_zod9.z.string().regex(/^0x[0-9a-fA-F]+$/, "must be hex-encoded signature bytes").describe(
496
+ var ReleaseEscrowRequestSchema = import_zod10.z.object({
497
+ signature: import_zod10.z.string().regex(/^0x[0-9a-fA-F]+$/, "must be hex-encoded signature bytes").describe(
432
498
  "The Safe transaction signature authorizing this release, produced by signing a transfer of the escrow's entire current token balance to the charge's already-frozen split address (the same split that would have received the payment on a normal, non-escrow charge) with the private key behind this charge's `escrowReleaserAddress` \u2014 never anything Klappay can produce itself. The destination is fixed by the charge's `splitConfig` (frozen at creation); the amount is read live on-chain at release time, not fixed in advance, so it always matches whatever actually arrived \u2014 reconstruct the exact transaction server-side computes (ERC-20 `transfer(splitAddress, balance)` from the escrow Safe, nonce 0) before signing. Independently verified on-chain before anything moves \u2014 the Safe contract itself rejects a signature that isn't from `escrowReleaserAddress`, never trusted at face value by Klappay."
433
499
  )
434
500
  });
435
- var RefundEscrowRequestSchema = import_zod9.z.object({
436
- signature: import_zod9.z.string().regex(/^0x[0-9a-fA-F]+$/, "must be hex-encoded signature bytes").describe(
501
+ var RefundEscrowRequestSchema = import_zod10.z.object({
502
+ signature: import_zod10.z.string().regex(/^0x[0-9a-fA-F]+$/, "must be hex-encoded signature bytes").describe(
437
503
  "The Safe transaction signature authorizing this refund, produced by signing a transfer of the escrow's entire current token balance back to the address that funded this charge (`Charge.payerAddress`, captured from the credited transfer) with the private key behind this charge's `escrowReleaserAddress` \u2014 never anything Klappay can produce itself. The amount is read live on-chain at refund time, not fixed in advance, so it always matches whatever actually arrived \u2014 reconstruct the exact transaction Klappay computes server-side (ERC-20 `transfer(payerAddress, balance)` from the escrow Safe, nonce 0) before signing. Independently verified on-chain before anything moves \u2014 the Safe contract itself rejects a signature that isn't from `escrowReleaserAddress`, never trusted at face value by Klappay."
438
504
  )
439
505
  });
440
506
 
441
507
  // src/exact-amount.ts
442
- var import_zod10 = require("zod");
443
- var ExactAmountSchema = import_zod10.z.string().regex(/^(0|[1-9]\d*)(?:\.\d{1,18})?$(?!\s)/).describe(
508
+ var import_zod11 = require("zod");
509
+ var ExactAmountSchema = import_zod11.z.string().regex(/^(0|[1-9]\d*)(?:\.\d{1,18})?$(?!\s)/).describe(
444
510
  "Nonnegative amount in whole currency/token units, as a decimal string with at most 18 fractional digits and no scientific notation."
445
511
  );
446
512
 
447
513
  // src/charges.ts
448
- var ChargeStatusSchema = import_zod11.z.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
514
+ var ChargeStatusSchema = import_zod12.z.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
449
515
  "Payment progress, from the payer side. `pending`: created, nothing received yet. `partially_paid`: some funds received, less than `amount`. `confirmed`: full amount received (or more \u2014 see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. Every status is reached automatically, on its own timeline \u2014 there is no merchant-initiated cancellation. This never reflects whether funds actually reached the merchant \u2014 see `settlementStatus` for that."
450
516
  );
451
- var SettlementStatusSchema = import_zod11.z.enum(["pending", "completed", "failed"]).describe(
517
+ var SettlementStatusSchema = import_zod12.z.enum(["pending", "completed", "failed"]).describe(
452
518
  "Progress of the payout to the merchant's wallet, a separate step from `status` \u2014 `status: confirmed` only means the payment was detected on-chain, not that the merchant has been paid yet. `pending`: payment detected, payout not yet attempted. `completed`: the merchant's wallet has the funds. `failed`: the payout attempt failed and retries were exhausted (rare; contact support). `null` on the parent `Charge` means no payout has been attempted yet \u2014 nothing has been received, or the charge is still in progress."
453
519
  );
454
- var ChargeFeePayerSchema = import_zod11.z.enum(["merchant", "payer"]).describe(
520
+ var ChargeFeePayerSchema = import_zod12.z.enum(["merchant", "payer"]).describe(
455
521
  "Who ends up covering Klappay's `feePercent`. `merchant` (default): `amount` is exactly what you asked for, and Klappay's fee is deducted from your own payout \u2014 you net `amount * (1 - feePercent / 100)`. `payer` : `amount` is grossed up at creation time so that, after the same fee deduction, you still net the amount you originally requested \u2014 the payer sees and sends the larger, fee-inclusive total. Frozen at creation like every other fee input; does not change how `feeAmount`/`merchantAmount` are computed on read, only what `amount` was set to in the first place."
456
522
  );
457
523
  var CHARGE_EXPIRES_IN_MIN_SECONDS = 60;
458
524
  var CHARGE_EXPIRES_IN_MAX_SECONDS = 3600;
459
- var CHARGE_ACCEPTED_PAYMENTS_MAX = 14;
460
- var AcceptedPaymentSchema = import_zod11.z.object({
525
+ var CHARGE_ACCEPTED_PAYMENTS_MAX = 18;
526
+ var AcceptedPaymentSchema = import_zod12.z.object({
461
527
  token: TokenSchema,
462
528
  network: NetworkSchema
463
529
  });
464
- var AcceptedPaymentsSchema = import_zod11.z.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
530
+ var AcceptedPaymentsSchema = import_zod12.z.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
465
531
  const seen = /* @__PURE__ */ new Set();
466
532
  pairs.forEach((pair, index) => {
467
533
  const key = `${pair.token}:${pair.network}`;
468
534
  if (seen.has(key)) {
469
535
  ctx.addIssue({
470
- code: import_zod11.z.ZodIssueCode.custom,
536
+ code: import_zod12.z.ZodIssueCode.custom,
471
537
  message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,
472
538
  path: [index]
473
539
  });
@@ -475,42 +541,51 @@ var AcceptedPaymentsSchema = import_zod11.z.array(AcceptedPaymentSchema).min(1,
475
541
  seen.add(key);
476
542
  if (!OPERATIONAL_NETWORKS.some((network) => network === pair.network)) {
477
543
  ctx.addIssue({
478
- code: import_zod11.z.ZodIssueCode.custom,
544
+ code: import_zod12.z.ZodIssueCode.custom,
479
545
  message: `Network "${pair.network}" isn't live yet \u2014 only ${OPERATIONAL_NETWORKS.join(", ")} today.`,
480
546
  path: [index, "network"]
481
547
  });
482
548
  }
483
549
  });
550
+ const families = new Set(pairs.map((pair) => NETWORK_FAMILIES[pair.network]));
551
+ if (families.size > 1) {
552
+ ctx.addIssue({
553
+ code: import_zod12.z.ZodIssueCode.custom,
554
+ message: `acceptedPayments mixes networks from different split families (${[...families].sort().join(", ")}) \u2014 every network in this list must share the same underlying split factory, so a charge can only ever accept networks from one family at a time.`
555
+ });
556
+ }
484
557
  }).describe(
485
- `Every \`(token, network)\` pair the payer is allowed to pay with \u2014 at least one, up to ${CHARGE_ACCEPTED_PAYMENTS_MAX}. This list is also the only restriction knob: the payer can use any combination of the pairs listed here, and every transfer on one of them is credited and sums toward the charge total (see \`paidWith\`) \u2014 e.g. a charge accepting USDC and USDT can be confirmed by $9 in USDC plus $1 in USDT, or by USDC arriving on two different accepted networks. To require payment in one specific token on one specific network, list only that single pair \u2014 a transfer on any pair not in this list is still recorded (for audit) but never credited. Each network must be live (see \`GET /v1/networks\` for the current matrix) \u2014 an unconfigured \`(token, network)\` combination for your environment is rejected with \`422 token_not_supported\`.`
558
+ `Every \`(token, network)\` pair the payer is allowed to pay with \u2014 at least one, up to ${CHARGE_ACCEPTED_PAYMENTS_MAX}. This list is also the only restriction knob: the payer can use any combination of the pairs listed here, and every transfer on one of them is credited and sums toward the charge total (see \`paidWith\`) \u2014 e.g. a charge accepting USDC and USDT can be confirmed by $9 in USDC plus $1 in USDT, or by USDC arriving on two different accepted networks. To require payment in one specific token on one specific network, list only that single pair \u2014 a transfer on any pair not in this list is still recorded (for audit) but never credited. Each network must be live (see \`GET /v1/networks\` for the current matrix) \u2014 an unconfigured \`(token, network)\` combination for your environment is rejected with \`422 token_not_supported\`. Every network listed must also share the same split family (which networks are grouped together is an implementation detail, not part of this API's contract) \u2014 a charge predicts one split address up front and reuses it across every accepted network, which is only safe within one family; mixing families is rejected with \`400 validation_error\`.`
486
559
  );
487
560
  var CHARGE_SPLIT_RECIPIENTS_MAX = 5;
488
- var SplitRecipientSchema = import_zod11.z.object({
489
- address: import_zod11.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").describe("EVM address to send a slice of this charge to."),
490
- percent: import_zod11.z.number().positive().max(100).describe(
561
+ var SplitRecipientSchema = import_zod12.z.object({
562
+ address: SplitAddressSchema.describe(
563
+ "Address to send a slice of this charge to \u2014 an EVM 0x... address or a TRON T... address, matching whichever network family the charge accepts (acceptedPayments can only ever list networks from one split family at a time, so this always matches that same family)."
564
+ ),
565
+ percent: import_zod12.z.number().positive().max(100).describe(
491
566
  "Percent of *your own* net share (i.e. of `100 - feePercent`, not of the charge's gross `amount`) to route to this address instead of your own payout wallet. Klappay's fee is computed on the gross amount first and is never diluted by how you choose to split what's left \u2014 see `docs/payments.md`'s \"Settling the payout\" section for the exact math."
492
567
  ),
493
- label: import_zod11.z.string().min(1).max(64).optional().describe(
568
+ label: import_zod12.z.string().min(1).max(64).optional().describe(
494
569
  'Free-form label for your own bookkeeping (e.g. `"supplier"`, `"sales rep"`) \u2014 echoed back unchanged, never interpreted by Klappay.'
495
570
  )
496
571
  });
497
- var SplitRecipientInputSchema = import_zod11.z.object({
498
- recipientId: import_zod11.z.string().describe(
572
+ var SplitRecipientInputSchema = import_zod12.z.object({
573
+ recipientId: import_zod12.z.string().describe(
499
574
  "id of a `Recipient` you already registered via `POST /v1/recipients` (not a raw address) \u2014 see `recipients:write`/`charges:split_write` scopes. A leaked `charges:write`-only key can never redirect payout to a brand new address this way, only reference one already trusted."
500
575
  ),
501
- percent: import_zod11.z.number().positive().max(100).describe(
576
+ percent: import_zod12.z.number().positive().max(100).describe(
502
577
  "Percent of *your own* net share (i.e. of `100 - feePercent`, not of the charge's gross `amount`) to route to this recipient instead of your own payout wallet. Klappay's fee is computed on the gross amount first and is never diluted by how you choose to split what's left \u2014 see `docs/payments.md`'s \"Settling the payout\" section for the exact math."
503
578
  ),
504
- label: import_zod11.z.string().min(1).max(64).optional().describe(
579
+ label: import_zod12.z.string().min(1).max(64).optional().describe(
505
580
  'Free-form label for your own bookkeeping (e.g. `"supplier"`, `"sales rep"`) \u2014 echoed back unchanged, never interpreted by Klappay. Independent of the label the recipient was registered with.'
506
581
  )
507
582
  });
508
- var SplitRecipientsInputSchema = import_zod11.z.array(SplitRecipientInputSchema).max(CHARGE_SPLIT_RECIPIENTS_MAX).superRefine((recipients, ctx) => {
583
+ var SplitRecipientsInputSchema = import_zod12.z.array(SplitRecipientInputSchema).max(CHARGE_SPLIT_RECIPIENTS_MAX).superRefine((recipients, ctx) => {
509
584
  const seen = /* @__PURE__ */ new Set();
510
585
  recipients.forEach((recipient, index) => {
511
586
  if (seen.has(recipient.recipientId)) {
512
587
  ctx.addIssue({
513
- code: import_zod11.z.ZodIssueCode.custom,
588
+ code: import_zod12.z.ZodIssueCode.custom,
514
589
  message: `Duplicate split recipientId: ${recipient.recipientId}.`,
515
590
  path: [index, "recipientId"]
516
591
  });
@@ -521,114 +596,127 @@ var SplitRecipientsInputSchema = import_zod11.z.array(SplitRecipientInputSchema)
521
596
  `Optional extra recipients for this charge's split \u2014 e.g. a supplier or the sales rep who closed the deal \u2014 up to ${CHARGE_SPLIT_RECIPIENTS_MAX}, each referenced by \`recipientId\` (see \`POST /v1/recipients\`), never a raw address. Requires the \`charges:split_write\` scope in addition to \`charges:write\`. Frozen at creation exactly like everything else that shapes the split address; cannot be changed afterward. The sum of every \`percent\` here must fit within \`100 - feePercent\` (your own net share) \u2014 a request that doesn't is rejected with \`422 split_recipients_exceed_available_percent\`.`
522
597
  );
523
598
  var CHARGE_AMOUNT_MAX = 999999999999;
524
- var CreateChargeSchema = import_zod11.z.object({
525
- amount: import_zod11.z.number().positive().max(CHARGE_AMOUNT_MAX).describe(
599
+ var CreateChargeSchema = import_zod12.z.object({
600
+ amount: import_zod12.z.number().positive().max(CHARGE_AMOUNT_MAX).describe(
526
601
  "Amount to charge, in `currency` units (e.g. `49.9` = $49.90) \u2014 up to 6 decimal places; anything more precise is silently truncated. Required \u2014 every charge has a target amount, the first credited transfer that reaches it confirms the charge. With `feePayer: 'payer'` (see below), this is your own desired net amount, not the total the payer ends up sending \u2014 the response's `amount` is grossed up to cover `feePercent`, while `merchantAmount` on the response echoes back this exact value."
527
602
  ),
528
603
  feePayer: ChargeFeePayerSchema.optional().default("merchant"),
529
- currency: import_zod11.z.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
604
+ currency: import_zod12.z.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
530
605
  acceptedPayments: AcceptedPaymentsSchema,
531
- expiresIn: import_zod11.z.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
606
+ expiresIn: import_zod12.z.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
532
607
  "Seconds, not minutes or milliseconds \u2014 how long the charge stays open before it expires. Required, min 60, max 3600 (60 minutes) \u2014 sized off the slowest chain Klappay supports today (Ethereum mainnet, where a safely-confirmed transfer takes up to ~15 minutes), leaving real margin for payer-side delay (gas spikes, wallet friction) on top of that. Cannot be extended or shortened after creation."
533
608
  ),
534
- idempotencyKey: import_zod11.z.string().min(1).max(255).optional().describe(
609
+ idempotencyKey: import_zod12.z.string().min(1).max(255).optional().describe(
535
610
  "Scoped to your tenant. Replaying the same key with the exact same request body returns the original charge unchanged instead of creating a duplicate \u2014 safe to retry a request after a timeout without double-charging. Reusing the same key with a different body (including a different `escrow` config) is rejected with `409 idempotency_key_reused`, never silently returned as the original charge."
536
611
  ),
537
- externalRef: import_zod11.z.string().min(1).max(255).optional().describe(
612
+ externalRef: import_zod12.z.string().min(1).max(255).optional().describe(
538
613
  "An opaque correlation id from your own system (e.g. an order id) \u2014 echoed back on the charge and in every webhook payload. Not interpreted or validated by Klappay."
539
614
  ),
540
- source: import_zod11.z.string().min(1).max(64).optional().describe(
615
+ source: import_zod12.z.string().min(1).max(64).optional().describe(
541
616
  'Free-form label for what created this charge (e.g. `"checkout"`, `"invoice"`) \u2014 useful if you create charges from more than one flow and want to tell them apart later. Not a fixed enum; use whatever values make sense to you.'
542
617
  ),
543
618
  metadata: MetadataWithKlappaySchema.optional(),
544
- redirectUrl: import_zod11.z.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
619
+ redirectUrl: import_zod12.z.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
545
620
  "Where to send the payer once this charge resolves, if you use Klappay's hosted checkout page (see `checkoutUrl` on the read shape) \u2014 ignored otherwise. Must be `http(s)` \u2014 a browser will navigate here, so `javascript:`/`data:` and other non-navigational schemes are rejected. Otherwise not validated beyond being well-formed; what happens at that destination is yours to build."
546
621
  ),
547
622
  splitRecipients: SplitRecipientsInputSchema.optional(),
548
623
  escrow: EscrowConfigSchema.optional().describe(
549
- "Configure this charge as an escrow instead of a normal payment. Funds land in a dedicated, non-custodial Safe (not the usual split address) and only `releaserAddress` (or, if omitted, your API key's own `payoutAddress`) can ever release them \u2014 via `POST /v1/charges/{id}/release`, signed on their end, never something Klappay can trigger or redirect. Omit this field entirely for a normal charge."
624
+ "Configure this charge as an escrow instead of a normal payment. Funds land in a dedicated, non-custodial Safe (not the usual split address) and only `releaserAddress` (or, if omitted, your API key's own `payoutAddress`) can ever release them \u2014 via `POST /v1/charges/{id}/release`, signed on their end, never something Klappay can trigger or redirect. Omit this field entirely for a normal charge. **Requires every accepted network to be EVM** (Safe \u2014 the underlying custody contract \u2014 isn't deployed on Tron, and can never be; it's not an EVM chain) \u2014 rejected with `400 validation_error` otherwise."
550
625
  )
626
+ }).superRefine((data, ctx) => {
627
+ if (!data.escrow) return;
628
+ const evmNetworks = EVM_NETWORKS;
629
+ const hasUnsupportedNetwork = data.acceptedPayments.some(
630
+ (pair) => !evmNetworks.includes(pair.network)
631
+ );
632
+ if (hasUnsupportedNetwork) {
633
+ ctx.addIssue({
634
+ code: import_zod12.z.ZodIssueCode.custom,
635
+ message: "Escrow is not supported for this charge's network \u2014 Safe (the underlying custody contract) isn't an EVM chain there. Remove `escrow`, or accept payment on an EVM network instead.",
636
+ path: ["escrow"]
637
+ });
638
+ }
551
639
  });
552
- var ChargeSchema = import_zod11.z.object({
553
- id: import_zod11.z.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
554
- amount: import_zod11.z.number().describe(
640
+ var ChargeSchema = import_zod12.z.object({
641
+ id: import_zod12.z.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
642
+ amount: import_zod12.z.number().describe(
555
643
  "The total the payer must send, in `currency` units (up to 6 decimal places). This legacy JSON number can lose precision; use `amountExact` for calculations and payment preparation. With `feePayer: 'merchant'` (the default) this is what you requested at creation. With `feePayer: 'payer'` this is grossed up to cover `feePercent` \u2014 see `merchantAmount` for what you requested/will actually net."
556
644
  ),
557
645
  amountExact: ExactAmountSchema.regex(/^(0|[1-9]\d*)(?:\.\d{1,6})?$/).optional().describe(
558
646
  'Exact total the payer must send, in `currency` units, as a nonnegative decimal string with at most 6 fractional digits and no scientific notation (e.g. `"100.000001"`). Use this instead of `amount` for arithmetic. Optional for compatibility with older API responses.'
559
647
  ),
560
648
  feePayer: ChargeFeePayerSchema,
561
- feePercent: import_zod11.z.number().describe(
649
+ feePercent: import_zod12.z.number().describe(
562
650
  "Klappay's fee for this charge, as a percent of `amount` (e.g. `2` = 2%) \u2014 includes any escrow surcharge if this charge is an escrow. Frozen at creation; see `feeAmount`/`merchantAmount` for the actual amounts this works out to."
563
651
  ),
564
- feeAmount: import_zod11.z.number().describe("`amount * feePercent / 100`, in `currency` units \u2014 Klappay's cut of this charge."),
565
- merchantAmount: import_zod11.z.number().describe(
652
+ feeAmount: import_zod12.z.number().describe("`amount * feePercent / 100`, in `currency` units \u2014 Klappay's cut of this charge."),
653
+ merchantAmount: import_zod12.z.number().describe(
566
654
  "`amount - feeAmount`, in `currency` units \u2014 what you actually net once the payout settles, regardless of `feePayer` (this is always what the split delivers to you; `feePayer` only affects what `amount` was set to at creation)."
567
655
  ),
568
- amountReceived: import_zod11.z.number().nullable().describe(
656
+ amountReceived: import_zod12.z.number().nullable().describe(
569
657
  "Cumulative amount received on-chain so far, in `currency` units. This legacy JSON number can lose precision; use `amountReceivedExact` for arithmetic with up to 18 fractional digits. `null` until the first transfer arrives. Can exceed `amount` \u2014 see `isOverpaid`."
570
658
  ),
571
659
  amountReceivedExact: ExactAmountSchema.nullable().optional().describe(
572
660
  'Exact cumulative amount received on-chain, in `currency` units, as a nonnegative decimal string with at most 18 fractional digits and no scientific notation (e.g. `"0.0000000001"`). `null` until the first transfer arrives. Can exceed `amountExact`. Optional for compatibility with older API responses.'
573
661
  ),
574
- paymentUnavailable: import_zod11.z.boolean().optional().describe(
662
+ paymentUnavailable: import_zod12.z.boolean().optional().describe(
575
663
  "When `true`, payment processing for this charge is temporarily unavailable. Do not offer payment instructions, request another transfer, or fulfill from its monetary/status fields until availability is restored. The charge retains its existing business status. Optional for compatibility with older API responses."
576
664
  ),
577
- isOverpaid: import_zod11.z.boolean().describe(
665
+ isOverpaid: import_zod12.z.boolean().describe(
578
666
  "`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically \u2014 see the docs for why."
579
667
  ),
580
- currency: import_zod11.z.string().describe("Always `USD` today \u2014 the only supported currency."),
581
- acceptedPayments: import_zod11.z.array(AcceptedPaymentSchema).describe(
668
+ currency: import_zod12.z.string().describe("Always `USD` today \u2014 the only supported currency."),
669
+ acceptedPayments: import_zod12.z.array(AcceptedPaymentSchema).describe(
582
670
  "Every `(token, network)` pair this charge was configured to accept, unchanged after creation."
583
671
  ),
584
- paidWith: import_zod11.z.array(AcceptedPaymentSchema).describe(
672
+ paidWith: import_zod12.z.array(AcceptedPaymentSchema).describe(
585
673
  "Every distinct `(token, network)` pair that has actually contributed a credited transfer so far \u2014 empty until the first one arrives. Can hold more than one entry: a charge accepting several pairs can be paid across a combination of them, and every entry here sums toward `amountReceived`."
586
674
  ),
587
- swapAlternatives: import_zod11.z.array(SwapAlternativeSchema).describe(
675
+ swapAlternatives: import_zod12.z.array(SwapAlternativeSchema).describe(
588
676
  "Every `(token, network)` pair the payer can pay with instead, via `POST /v1/charges/{id}/quote` \u2014 derived from the networks in `acceptedPayments` (e.g. a charge accepting USDC on both Base and Optimism lists `ETH` on Base and `ETH` on Optimism separately, since they're different networks the payer has to choose between, not one merged option). Pass an entry's `token`/`network` straight through as `inputToken`/`inputNetwork`. Recomputed on every read against Klappay's current trusted list, not frozen at creation \u2014 empty if this charge's networks have no trusted alt-token, if swap-to-pay isn't configured on this deployment, or if `environment` is `test` (0x, who powers the swap, has no testnet support at all \u2014 `POST /v1/charges/{id}/quote` always rejects a test-environment charge with `422 swap_test_environment_unsupported`)."
589
677
  ),
590
- address: import_zod11.z.string().describe(
678
+ address: import_zod12.z.string().describe(
591
679
  "The on-chain address the payer must send funds to \u2014 identical across every accepted network (0xSplits addresses are chain-agnostic). Unique per charge, predicted at creation time \u2014 funds sent here go directly to the merchant, Klappay never custodies them."
592
680
  ),
593
681
  status: ChargeStatusSchema,
594
682
  settlementStatus: SettlementStatusSchema.nullable(),
595
683
  environment: EnvironmentSchema,
596
- apiKeyId: import_zod11.z.string().nullable().describe(
684
+ apiKeyId: import_zod12.z.string().nullable().describe(
597
685
  "Which of your API keys created this charge. `null` for a charge created before this field existed."
598
686
  ),
599
- txHash: import_zod11.z.string().nullable().describe(
687
+ txHash: import_zod12.z.string().nullable().describe(
600
688
  "Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected."
601
689
  ),
602
- externalRef: import_zod11.z.string().nullable(),
603
- source: import_zod11.z.string().nullable(),
690
+ externalRef: import_zod12.z.string().nullable(),
691
+ source: import_zod12.z.string().nullable(),
604
692
  metadata: MetadataWithKlappaySchema.nullable(),
605
- redirectUrl: import_zod11.z.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
606
- checkoutUrl: import_zod11.z.string().nullable().describe(
693
+ redirectUrl: import_zod12.z.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
694
+ checkoutUrl: import_zod12.z.string().nullable().describe(
607
695
  "Link to Klappay's hosted checkout page for this charge. `null` if this deployment has no hosted checkout configured \u2014 build your own payment UI from `address`/`acceptedPayments` instead."
608
696
  ),
609
- splitRecipients: import_zod11.z.array(SplitRecipientSchema).describe("Echoes whatever extra split recipients were set at creation \u2014 empty array if none."),
610
- createdAt: import_zod11.z.string().datetime(),
611
- expiresAt: import_zod11.z.string().datetime().describe(
697
+ splitRecipients: import_zod12.z.array(SplitRecipientSchema).describe("Echoes whatever extra split recipients were set at creation \u2014 empty array if none."),
698
+ createdAt: import_zod12.z.string().datetime(),
699
+ expiresAt: import_zod12.z.string().datetime().describe(
612
700
  "When this charge stops accepting payment, if still `pending`/`partially_paid` by then."
613
701
  ),
614
- confirmedAt: import_zod11.z.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
615
- settledAt: import_zod11.z.string().datetime().nullable().describe(
702
+ confirmedAt: import_zod12.z.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
703
+ settledAt: import_zod12.z.string().datetime().nullable().describe(
616
704
  "When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
617
705
  ),
618
- lastActivityAt: import_zod11.z.string().datetime().describe(
706
+ lastActivityAt: import_zod12.z.string().datetime().describe(
619
707
  "When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet."
620
708
  ),
621
- escrow: import_zod11.z.object({
622
- releaserAddress: import_zod11.z.string().describe("The only address that can ever release this escrow \u2014 never Klappay."),
623
- releasedAt: import_zod11.z.string().datetime().nullable().describe("When the release actually executed on-chain. `null` until then."),
624
- refundedAt: import_zod11.z.string().datetime().nullable().describe(
709
+ escrow: import_zod12.z.object({
710
+ releaserAddress: import_zod12.z.string().describe("The only address that can ever release this escrow \u2014 never Klappay."),
711
+ releasedAt: import_zod12.z.string().datetime().nullable().describe("When the release actually executed on-chain. `null` until then."),
712
+ refundedAt: import_zod12.z.string().datetime().nullable().describe(
625
713
  "When the refund actually executed on-chain. `null` until then. Mutually exclusive with `releasedAt` \u2014 an escrow can only ever be released or refunded once, never both."
626
714
  )
627
715
  }).nullable().describe(
628
716
  "Present only when this charge was created as an escrow (see `escrow` on the create request) \u2014 `null` for a normal charge."
629
717
  )
630
718
  });
631
- var ListChargesSchema = import_zod11.z.object({
719
+ var ListChargesSchema = import_zod12.z.object({
632
720
  status: ChargeStatusSchema.optional(),
633
721
  token: TokenSchema.optional().describe(
634
722
  "Filters on `paidWith.token` \u2014 the pair actually paid, not accepted."
@@ -637,13 +725,13 @@ var ListChargesSchema = import_zod11.z.object({
637
725
  "Filters on `paidWith.network` \u2014 the pair actually paid, not accepted."
638
726
  ),
639
727
  environment: EnvironmentSchema.optional(),
640
- since: import_zod11.z.string().datetime().optional().describe(
728
+ since: import_zod12.z.string().datetime().optional().describe(
641
729
  "Only return charges created at or after this timestamp (filters on `createdAt`, not on when the status last changed). If polling as a fallback for missed webhooks, use a window at least as wide as the longest `expiresIn` your charges use, or you can miss a long-lived charge that changed status outside a narrower window."
642
730
  ),
643
- isOverpaid: import_zod11.z.enum(["true", "false"]).transform((v) => v === "true").optional()
731
+ isOverpaid: import_zod12.z.enum(["true", "false"]).transform((v) => v === "true").optional()
644
732
  }).extend(PaginationQuerySchema.shape);
645
733
  var PaginatedChargesSchema = paginatedSchema(ChargeSchema);
646
- var GetChargeQrCodeQuerySchema = import_zod11.z.object({
734
+ var GetChargeQrCodeQuerySchema = import_zod12.z.object({
647
735
  token: TokenSchema.optional().describe(
648
736
  "Which accepted `(token, network)` pair to encode in the QR \u2014 required if `acceptedPayments` has more than one pair, since there is no single unambiguous default to fall back to. Ignored (and unnecessary) when the charge accepts exactly one pair."
649
737
  ),
@@ -651,19 +739,19 @@ var GetChargeQrCodeQuerySchema = import_zod11.z.object({
651
739
  });
652
740
 
653
741
  // src/charge-check.ts
654
- var import_zod13 = require("zod");
742
+ var import_zod14 = require("zod");
655
743
 
656
744
  // src/confirmation-progress.ts
657
- var import_zod12 = require("zod");
658
- var ConfirmationProgressSchema = import_zod12.z.object({
745
+ var import_zod13 = require("zod");
746
+ var ConfirmationProgressSchema = import_zod13.z.object({
659
747
  network: NetworkSchema.describe("Which network the transfer was seen on."),
660
- blocksSeen: import_zod12.z.number().int().min(0).describe(
748
+ blocksSeen: import_zod13.z.number().int().min(0).describe(
661
749
  "How many blocks have passed since the transfer's own block, as of this update \u2014 a raw block count, not seconds. Grows toward `blocksRequired` as the network's blocks keep arriving."
662
750
  ),
663
- blocksRequired: import_zod12.z.number().int().min(1).describe(
751
+ blocksRequired: import_zod13.z.number().int().min(1).describe(
664
752
  "This network's minimum confirmation depth (a fixed, per-network constant) \u2014 the transfer is only credited once `blocksSeen` reaches this value."
665
753
  ),
666
- percent: import_zod12.z.number().int().min(0).max(99).describe(
754
+ percent: import_zod13.z.number().int().min(0).max(99).describe(
667
755
  '`blocksSeen`/`blocksRequired` as a rounded-down 0-99 percentage, for a progress bar. Never reaches 100 by construction \u2014 once a transfer is deep enough it is credited immediately and this stops being reported at all (the charge event itself is the "done" signal).'
668
756
  )
669
757
  }).describe(
@@ -671,8 +759,8 @@ var ConfirmationProgressSchema = import_zod12.z.object({
671
759
  );
672
760
 
673
761
  // src/charge-check.ts
674
- var CheckChargeRequestSchema = import_zod13.z.object({
675
- txHash: import_zod13.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be a 32-byte transaction hash").optional().describe(
762
+ var CheckChargeRequestSchema = import_zod14.z.object({
763
+ txHash: import_zod14.z.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be a 32-byte transaction hash").optional().describe(
676
764
  "The on-chain transaction hash to verify directly, if you already have it \u2014 e.g. right after a swap-to-pay or wallet-connect transaction is sent. Costs a single RPC call instead of scanning a block range, so the check resolves faster and cheaper. Omit to fall back to scanning recent transfers to this charge's address, the same lookup the background reconciliation pass runs. Never trusted at face value \u2014 whatever this transaction actually contains on-chain is what gets credited, regardless of any amount/token implied elsewhere."
677
765
  ),
678
766
  network: NetworkSchema.optional().describe(
@@ -682,7 +770,7 @@ var CheckChargeRequestSchema = import_zod13.z.object({
682
770
  message: "`txHash` and `network` must be provided together, or both omitted"
683
771
  });
684
772
  var CheckChargeResponseSchema = ChargeSchema.extend({
685
- transactionSender: import_zod13.z.string().nullable().describe(
773
+ transactionSender: import_zod14.z.string().nullable().describe(
686
774
  "The `txHash` transaction's own sender (`from`) \u2014 who actually signed and submitted it on-chain, which stays the payer's own wallet even when the transaction swaps through a router/aggregator on the way to paying, unlike the credited transfer's `from` (which can be the router/pool contract, not the payer). `null` unless `txHash`/`network` was passed in the request and a successful receipt was found for it \u2014 a hint-less background scan, an unaccepted network, or a not-found/reverted transaction all leave this `null`."
687
775
  ),
688
776
  confirmationProgress: ConfirmationProgressSchema.nullable().describe(
@@ -691,61 +779,61 @@ var CheckChargeResponseSchema = ChargeSchema.extend({
691
779
  });
692
780
 
693
781
  // src/distributions.ts
694
- var import_zod14 = require("zod");
695
- var SplitDistributionStatusSchema = import_zod14.z.enum(["pending", "processing", "completed", "failed"]).describe(
782
+ var import_zod15 = require("zod");
783
+ var SplitDistributionStatusSchema = import_zod15.z.enum(["pending", "processing", "completed", "failed"]).describe(
696
784
  "Status of one payout attempt to the merchant, for a single `(token, network)` pair \u2014 a charge that settles across more than one pair has one of these per pair. `pending`: queued, not yet claimed by a distributor. `processing`: a distributor (Klappay's own worker, or anyone racing to call `distribute()` first, see `PendingDistributionSchema`) has claimed it and is submitting the on-chain transaction. `completed`: the merchant's wallet has the funds. `failed`: every automatic retry was exhausted."
697
785
  );
698
- var PendingDistributionRecipientSchema = import_zod14.z.object({
699
- address: import_zod14.z.string().describe("On-chain recipient address."),
700
- percentAllocation: import_zod14.z.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
786
+ var PendingDistributionRecipientSchema = import_zod15.z.object({
787
+ address: import_zod15.z.string().describe("On-chain recipient address."),
788
+ percentAllocation: import_zod15.z.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
701
789
  });
702
- var PendingDistributionSchema = import_zod14.z.object({
703
- splitAddress: import_zod14.z.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
790
+ var PendingDistributionSchema = import_zod15.z.object({
791
+ splitAddress: import_zod15.z.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
704
792
  network: NetworkSchema,
705
793
  token: TokenSchema,
706
- recipients: import_zod14.z.array(PendingDistributionRecipientSchema).describe(
794
+ recipients: import_zod15.z.array(PendingDistributionRecipientSchema).describe(
707
795
  "The exact recipient list to pass to `distribute()` \u2014 the split contract only stores a hash of this config, so the caller must supply the identical array to prove it matches. Always present, never reconstructed from partial data."
708
796
  ),
709
- distributorFeePercent: import_zod14.z.number().describe(
797
+ distributorFeePercent: import_zod15.z.number().describe(
710
798
  "Percentage of the split balance paid to whoever calls `distribute()` first (e.g. `0.1` = 0.1%). Frozen at charge creation, same for every distribution today."
711
799
  ),
712
- estimatedRewardAmount: import_zod14.z.number().describe(
800
+ estimatedRewardAmount: import_zod15.z.number().describe(
713
801
  "Estimate only, in the charge's `currency` units, based on the amount Klappay detected on-chain \u2014 not a live read of the split's current balance. Read the balance yourself before submitting a transaction; a stale estimate is harmless (see the docs), never a reason to skip that check."
714
802
  ),
715
- availableSince: import_zod14.z.string().datetime().describe("When this distribution entered its grace period."),
716
- graceEndsAt: import_zod14.z.string().datetime().describe(
803
+ availableSince: import_zod15.z.string().datetime().describe("When this distribution entered its grace period."),
804
+ graceEndsAt: import_zod15.z.string().datetime().describe(
717
805
  "When Klappay's own worker may claim this distribution. Racing to call `distribute()` after this timestamp is possible but increasingly likely to lose to the worker."
718
806
  )
719
807
  });
720
808
  var PaginatedPendingDistributionsSchema = paginatedSchema(PendingDistributionSchema);
721
- var ListenPendingDistributionsQuerySchema = import_zod14.z.object({
722
- limit: import_zod14.z.coerce.number().int().min(0).max(PAGINATION_LIMIT_MAX).default(0).describe(
809
+ var ListenPendingDistributionsQuerySchema = import_zod15.z.object({
810
+ limit: import_zod15.z.coerce.number().int().min(0).max(PAGINATION_LIMIT_MAX).default(0).describe(
723
811
  "How many currently-claimable distributions to emit as an initial snapshot right after connecting \u2014 each as a synthetic `distribution.available` event \u2014 before continuing with real-time deltas. `0` (the default, same as omitting it) sends no snapshot at all, matching this endpoint's original behavior: connect first, then call `GET /v1/distributions/pending` yourself to bootstrap. Not a page \u2014 there is no cursor for this snapshot, so if more than `limit` are claimable at connect time, the excess is simply not sent; call `GET /v1/distributions/pending` directly for a complete, paginated listing."
724
812
  )
725
813
  });
726
- var PendingDistributionEventSchema = import_zod14.z.discriminatedUnion("type", [
727
- import_zod14.z.object({
728
- type: import_zod14.z.literal("distribution.available"),
814
+ var PendingDistributionEventSchema = import_zod15.z.discriminatedUnion("type", [
815
+ import_zod15.z.object({
816
+ type: import_zod15.z.literal("distribution.available"),
729
817
  distribution: PendingDistributionSchema
730
818
  }),
731
- import_zod14.z.object({
732
- type: import_zod14.z.literal("distribution.claimed"),
733
- splitAddress: import_zod14.z.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
819
+ import_zod15.z.object({
820
+ type: import_zod15.z.literal("distribution.claimed"),
821
+ splitAddress: import_zod15.z.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
734
822
  })
735
823
  ]);
736
824
 
737
825
  // src/metrics.ts
738
- var import_zod15 = require("zod");
739
- var MetricsResourceSchema = import_zod15.z.enum(["charges", "transactions", "distributions"]).describe(
826
+ var import_zod16 = require("zod");
827
+ var MetricsResourceSchema = import_zod16.z.enum(["charges", "transactions", "distributions"]).describe(
740
828
  "Which underlying dataset to query. `charges`: one row per charge. `transactions`: one row per detected on-chain transfer \u2014 a charge paid in installments has more than one. `distributions`: one row per payout attempt to the merchant, one per `(token, network)` pair a charge settled across."
741
829
  );
742
- var MetricsAggregationSchema = import_zod15.z.enum(["count", "sum", "avg", "min", "max"]).describe(
830
+ var MetricsAggregationSchema = import_zod16.z.enum(["count", "sum", "avg", "min", "max"]).describe(
743
831
  "`count` counts matching rows and never takes `field`. `sum`/`avg`/`min`/`max` require `field` to be set to one of the resource\u2019s numeric fields."
744
832
  );
745
- var MetricsFilterOperatorSchema = import_zod15.z.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
833
+ var MetricsFilterOperatorSchema = import_zod16.z.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
746
834
  "`in` expects an array value (max 50 entries); every other operator expects a single scalar."
747
835
  );
748
- var MetricsDateGranularitySchema = import_zod15.z.enum(["day", "week", "month", "year"]).describe(
836
+ var MetricsDateGranularitySchema = import_zod16.z.enum(["day", "week", "month", "year"]).describe(
749
837
  "Bucket width for a `date_bucket` `groupBy` entry \u2014 Postgres `date_trunc` semantics (UTC)."
750
838
  );
751
839
  var metricsQueryEnvironmentSchema = EnvironmentSchema.describe(
@@ -758,31 +846,32 @@ var METRICS_QUERY_MAX_GROUP_BY = 3;
758
846
  var METRICS_QUERY_MAX_FILTERS = 20;
759
847
  var METRICS_QUERY_MAX_METRICS = 10;
760
848
  var METRIC_ALIAS_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
761
- var metricAliasSchema = import_zod15.z.string().min(1).max(64).regex(
849
+ var metricAliasSchema = import_zod16.z.string().min(1).max(64).regex(
762
850
  METRIC_ALIAS_PATTERN,
763
851
  "Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 this becomes a SQL column alias."
764
852
  ).optional();
765
- var MetricsFilterValueSchema = import_zod15.z.union([
766
- import_zod15.z.string().max(255),
767
- import_zod15.z.number(),
768
- import_zod15.z.boolean(),
769
- import_zod15.z.array(import_zod15.z.union([import_zod15.z.string().max(255), import_zod15.z.number()])).min(1).max(50)
853
+ var MetricsFilterValueSchema = import_zod16.z.union([
854
+ import_zod16.z.string().max(255),
855
+ import_zod16.z.number(),
856
+ import_zod16.z.boolean(),
857
+ import_zod16.z.null(),
858
+ import_zod16.z.array(import_zod16.z.union([import_zod16.z.string().max(255), import_zod16.z.number()])).min(1).max(50)
770
859
  ]);
771
- var orderBySchema = import_zod15.z.object({
772
- key: import_zod15.z.string().min(1).max(64).regex(
860
+ var orderBySchema = import_zod16.z.object({
861
+ key: import_zod16.z.string().min(1).max(64).regex(
773
862
  METRIC_ALIAS_PATTERN,
774
863
  "Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 every valid output column name already looks like this."
775
864
  ).describe(
776
865
  "An output column name from this same query \u2014 either a `groupBy` field name, or a metric\u2019s `alias` (or its default name: `${aggregation}` for `count`, `${aggregation}_${field}` otherwise, e.g. `sum_amount`). Must match `^[a-zA-Z_][a-zA-Z0-9_]*$` \u2014 every real output column name already does, so this only ever rejects a value that could never have been one."
777
866
  ),
778
- direction: import_zod15.z.enum(["asc", "desc"])
867
+ direction: import_zod16.z.enum(["asc", "desc"])
779
868
  }).describe(
780
869
  "Sort the result rows by any output column \u2014 including the bucket field itself for a `date_bucket` query (e.g. `createdAt`). Omit to get ascending-by-bucket order for a date-bucketed query, or implementation-defined (not guaranteed stable) order otherwise."
781
870
  );
782
- var limitSchema = import_zod15.z.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
871
+ var limitSchema = import_zod16.z.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
783
872
  `Max rows to return, ${1}\u2013${METRICS_QUERY_MAX_ROW_LIMIT}, default ${METRICS_QUERY_DEFAULT_ROW_LIMIT}. If more rows matched, \`meta.truncated\` is \`true\` on the response \u2014 narrow the query instead of just raising this.`
784
873
  );
785
- var ChargesQueryFieldSchema = import_zod15.z.enum([
874
+ var ChargesQueryFieldSchema = import_zod16.z.enum([
786
875
  "status",
787
876
  "source",
788
877
  "apiKeyId",
@@ -793,124 +882,124 @@ var ChargesQueryFieldSchema = import_zod15.z.enum([
793
882
  ]).describe(
794
883
  "A `Charge` field to filter or group by \u2014 see `ChargeStatusSchema` for `status`'s own possible values (charges.md). `source`/`externalRef` are free-form strings your own integration set at creation, not a fixed enum. `escrowReleaserAddress` is `null` for a normal charge \u2014 filter `escrowReleaserAddress` with operator `neq`/value `null` to isolate escrow-configured charges (see `escrow` in charges.md)."
795
884
  );
796
- var ChargesMetricFieldSchema = import_zod15.z.enum(["amount", "amountReceived", "feePercent", "escrowFeePercent"]).describe(
885
+ var ChargesMetricFieldSchema = import_zod16.z.enum(["amount", "amountReceived", "feePercent", "escrowFeePercent"]).describe(
797
886
  "A `Charge` numeric field to aggregate. `amount`/`amountReceived` are decimal currency amounts (requested vs. actually received \u2014 see `charges.md`). `feePercent` is the platform fee frozen on the charge at creation, e.g. `1.5` means 1.5%. `escrowFeePercent` is the additional escrow-specific fee component, only present on escrow-configured charges \u2014 see `docs/payments.md`."
798
887
  );
799
- var ChargesDateFieldSchema = import_zod15.z.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt", "escrowReleasedAt"]).describe(
888
+ var ChargesDateFieldSchema = import_zod16.z.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt", "escrowReleasedAt"]).describe(
800
889
  "A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` \u2014 a `dateRange`/`date_bucket` on it implicitly excludes every charge that never confirmed. `expiresAt` is always present (set at creation), useful for e.g. finding charges expiring soon or measuring how close to expiry charges typically resolve. `escrowReleasedAt` is `null` until an escrow-configured charge is actually released \u2014 same implicit-exclusion behavior as `confirmedAt`, scoped to escrow charges only."
801
890
  );
802
- var ChargesFilterSchema = import_zod15.z.object({
891
+ var ChargesFilterSchema = import_zod16.z.object({
803
892
  field: ChargesQueryFieldSchema,
804
893
  operator: MetricsFilterOperatorSchema,
805
894
  value: MetricsFilterValueSchema
806
895
  });
807
- var ChargesGroupBySchema = import_zod15.z.union([
808
- import_zod15.z.object({ type: import_zod15.z.literal("field"), field: ChargesQueryFieldSchema }),
809
- import_zod15.z.object({
810
- type: import_zod15.z.literal("date_bucket"),
896
+ var ChargesGroupBySchema = import_zod16.z.union([
897
+ import_zod16.z.object({ type: import_zod16.z.literal("field"), field: ChargesQueryFieldSchema }),
898
+ import_zod16.z.object({
899
+ type: import_zod16.z.literal("date_bucket"),
811
900
  field: ChargesDateFieldSchema,
812
901
  granularity: MetricsDateGranularitySchema
813
902
  })
814
903
  ]);
815
- var ChargesMetricSchema = import_zod15.z.object({
904
+ var ChargesMetricSchema = import_zod16.z.object({
816
905
  aggregation: MetricsAggregationSchema,
817
906
  field: ChargesMetricFieldSchema.optional(),
818
907
  alias: metricAliasSchema
819
908
  });
820
- var ChargesMetricsQuerySchema = import_zod15.z.object({
821
- resource: import_zod15.z.literal("charges"),
909
+ var ChargesMetricsQuerySchema = import_zod16.z.object({
910
+ resource: import_zod16.z.literal("charges"),
822
911
  environment: metricsQueryEnvironmentSchema,
823
- dateRange: import_zod15.z.object({
912
+ dateRange: import_zod16.z.object({
824
913
  field: ChargesDateFieldSchema,
825
- from: import_zod15.z.string().max(64).datetime(),
826
- to: import_zod15.z.string().max(64).datetime()
914
+ from: import_zod16.z.string().max(64).datetime(),
915
+ to: import_zod16.z.string().max(64).datetime()
827
916
  }),
828
- groupBy: import_zod15.z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
829
- metrics: import_zod15.z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
830
- filters: import_zod15.z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
917
+ groupBy: import_zod16.z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
918
+ metrics: import_zod16.z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
919
+ filters: import_zod16.z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
831
920
  orderBy: orderBySchema.optional(),
832
921
  limit: limitSchema
833
922
  });
834
- var TransactionsQueryFieldSchema = import_zod15.z.enum(["network", "token", "source", "causedTransition"]).describe(
923
+ var TransactionsQueryFieldSchema = import_zod16.z.enum(["network", "token", "source", "causedTransition"]).describe(
835
924
  "A `Transaction` field to filter or group by \u2014 see `NetworkSchema`/`TokenSchema`/`TransactionSourceSchema` for their possible values. `causedTransition` is `true` only for the transfer(s) that actually flipped the charge's `status` \u2014 a charge paid in installments can have more than one; filtering/grouping on it excludes no-op duplicate transfers (see `TimelineEvent.causedTransition` in charges.md for the full explanation)."
836
925
  );
837
- var TransactionsMetricFieldSchema = import_zod15.z.enum(["amount"]).describe("The transfer amount, in the charge's `currency` units.");
838
- var TransactionsDateFieldSchema = import_zod15.z.enum(["detectedAt"]).describe("When Klappay detected this transfer on-chain (not when it was mined).");
839
- var TransactionsFilterSchema = import_zod15.z.object({
926
+ var TransactionsMetricFieldSchema = import_zod16.z.enum(["amount"]).describe("The transfer amount, in the charge's `currency` units.");
927
+ var TransactionsDateFieldSchema = import_zod16.z.enum(["detectedAt"]).describe("When Klappay detected this transfer on-chain (not when it was mined).");
928
+ var TransactionsFilterSchema = import_zod16.z.object({
840
929
  field: TransactionsQueryFieldSchema,
841
930
  operator: MetricsFilterOperatorSchema,
842
931
  value: MetricsFilterValueSchema
843
932
  });
844
- var TransactionsGroupBySchema = import_zod15.z.union([
845
- import_zod15.z.object({ type: import_zod15.z.literal("field"), field: TransactionsQueryFieldSchema }),
846
- import_zod15.z.object({
847
- type: import_zod15.z.literal("date_bucket"),
933
+ var TransactionsGroupBySchema = import_zod16.z.union([
934
+ import_zod16.z.object({ type: import_zod16.z.literal("field"), field: TransactionsQueryFieldSchema }),
935
+ import_zod16.z.object({
936
+ type: import_zod16.z.literal("date_bucket"),
848
937
  field: TransactionsDateFieldSchema,
849
938
  granularity: MetricsDateGranularitySchema
850
939
  })
851
940
  ]);
852
- var TransactionsMetricSchema = import_zod15.z.object({
941
+ var TransactionsMetricSchema = import_zod16.z.object({
853
942
  aggregation: MetricsAggregationSchema,
854
943
  field: TransactionsMetricFieldSchema.optional(),
855
944
  alias: metricAliasSchema
856
945
  });
857
- var TransactionsMetricsQuerySchema = import_zod15.z.object({
858
- resource: import_zod15.z.literal("transactions"),
946
+ var TransactionsMetricsQuerySchema = import_zod16.z.object({
947
+ resource: import_zod16.z.literal("transactions"),
859
948
  environment: metricsQueryEnvironmentSchema,
860
- dateRange: import_zod15.z.object({
949
+ dateRange: import_zod16.z.object({
861
950
  field: TransactionsDateFieldSchema,
862
- from: import_zod15.z.string().max(64).datetime(),
863
- to: import_zod15.z.string().max(64).datetime()
951
+ from: import_zod16.z.string().max(64).datetime(),
952
+ to: import_zod16.z.string().max(64).datetime()
864
953
  }),
865
- groupBy: import_zod15.z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
866
- metrics: import_zod15.z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
867
- filters: import_zod15.z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
954
+ groupBy: import_zod16.z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
955
+ metrics: import_zod16.z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
956
+ filters: import_zod16.z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
868
957
  orderBy: orderBySchema.optional(),
869
958
  limit: limitSchema
870
959
  });
871
- var DistributionsQueryFieldSchema = import_zod15.z.enum(["status", "network", "token", "distributorAddress"]).describe(
960
+ var DistributionsQueryFieldSchema = import_zod16.z.enum(["status", "network", "token", "distributorAddress"]).describe(
872
961
  "A `SplitDistribution` field to filter or group by \u2014 see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values. `distributorAddress` is the public on-chain address that actually called `distribute()` for a `completed` distribution \u2014 Klappay's own operator address if settled by Klappay's own worker, a community keeper's address if settled externally (or `null` on the rare case that lookup failed), `null` for every non-`completed` status."
873
962
  );
874
- var DistributionsMetricFieldSchema = import_zod15.z.enum(["attempts"]).describe(
963
+ var DistributionsMetricFieldSchema = import_zod16.z.enum(["attempts"]).describe(
875
964
  "How many times a payout was attempted for this settlement so far \u2014 incremented on every attempt, whether it succeeded or is being retried after failing. A high `attempts` alongside `status: 'failed'` means every automatic retry was exhausted."
876
965
  );
877
- var DistributionsDateFieldSchema = import_zod15.z.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
966
+ var DistributionsDateFieldSchema = import_zod16.z.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
878
967
  "`createdAt`: when this settlement was queued. `processingStartedAt`: when a worker began its most recent attempt at the payout \u2014 `null` until the first attempt, then overwritten on every subsequent retry, so it reflects the *latest* attempt's start, not the first. `completedAt`: when it actually paid out \u2014 `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed."
879
968
  );
880
- var DistributionsFilterSchema = import_zod15.z.object({
969
+ var DistributionsFilterSchema = import_zod16.z.object({
881
970
  field: DistributionsQueryFieldSchema,
882
971
  operator: MetricsFilterOperatorSchema,
883
972
  value: MetricsFilterValueSchema
884
973
  });
885
- var DistributionsGroupBySchema = import_zod15.z.union([
886
- import_zod15.z.object({ type: import_zod15.z.literal("field"), field: DistributionsQueryFieldSchema }),
887
- import_zod15.z.object({
888
- type: import_zod15.z.literal("date_bucket"),
974
+ var DistributionsGroupBySchema = import_zod16.z.union([
975
+ import_zod16.z.object({ type: import_zod16.z.literal("field"), field: DistributionsQueryFieldSchema }),
976
+ import_zod16.z.object({
977
+ type: import_zod16.z.literal("date_bucket"),
889
978
  field: DistributionsDateFieldSchema,
890
979
  granularity: MetricsDateGranularitySchema
891
980
  })
892
981
  ]);
893
- var DistributionsMetricSchema = import_zod15.z.object({
982
+ var DistributionsMetricSchema = import_zod16.z.object({
894
983
  aggregation: MetricsAggregationSchema,
895
984
  field: DistributionsMetricFieldSchema.optional(),
896
985
  alias: metricAliasSchema
897
986
  });
898
- var DistributionsMetricsQuerySchema = import_zod15.z.object({
899
- resource: import_zod15.z.literal("distributions"),
987
+ var DistributionsMetricsQuerySchema = import_zod16.z.object({
988
+ resource: import_zod16.z.literal("distributions"),
900
989
  environment: metricsQueryEnvironmentSchema,
901
- dateRange: import_zod15.z.object({
990
+ dateRange: import_zod16.z.object({
902
991
  field: DistributionsDateFieldSchema,
903
- from: import_zod15.z.string().max(64).datetime(),
904
- to: import_zod15.z.string().max(64).datetime()
992
+ from: import_zod16.z.string().max(64).datetime(),
993
+ to: import_zod16.z.string().max(64).datetime()
905
994
  }),
906
- groupBy: import_zod15.z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
907
- metrics: import_zod15.z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
908
- filters: import_zod15.z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
995
+ groupBy: import_zod16.z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
996
+ metrics: import_zod16.z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
997
+ filters: import_zod16.z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
909
998
  orderBy: orderBySchema.optional(),
910
999
  limit: limitSchema
911
1000
  });
912
1001
  var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
913
- var MetricsQuerySchema = import_zod15.z.discriminatedUnion("resource", [
1002
+ var MetricsQuerySchema = import_zod16.z.discriminatedUnion("resource", [
914
1003
  ChargesMetricsQuerySchema,
915
1004
  TransactionsMetricsQuerySchema,
916
1005
  DistributionsMetricsQuerySchema
@@ -919,7 +1008,7 @@ var MetricsQuerySchema = import_zod15.z.discriminatedUnion("resource", [
919
1008
  const to = new Date(input.dateRange.to);
920
1009
  if (from >= to) {
921
1010
  ctx.addIssue({
922
- code: import_zod15.z.ZodIssueCode.custom,
1011
+ code: import_zod16.z.ZodIssueCode.custom,
923
1012
  message: "`dateRange.from` must be before `dateRange.to`.",
924
1013
  path: ["dateRange", "from"]
925
1014
  });
@@ -927,7 +1016,7 @@ var MetricsQuerySchema = import_zod15.z.discriminatedUnion("resource", [
927
1016
  const spanDays = (to.getTime() - from.getTime()) / ONE_DAY_MS;
928
1017
  if (spanDays > MAX_METRICS_QUERY_DATE_RANGE_DAYS) {
929
1018
  ctx.addIssue({
930
- code: import_zod15.z.ZodIssueCode.custom,
1019
+ code: import_zod16.z.ZodIssueCode.custom,
931
1020
  message: `\`dateRange\` cannot span more than ${MAX_METRICS_QUERY_DATE_RANGE_DAYS} days.`,
932
1021
  path: ["dateRange", "to"]
933
1022
  });
@@ -935,7 +1024,7 @@ var MetricsQuerySchema = import_zod15.z.discriminatedUnion("resource", [
935
1024
  const dateBucketCount = input.groupBy.filter((entry) => entry.type === "date_bucket").length;
936
1025
  if (dateBucketCount > 1) {
937
1026
  ctx.addIssue({
938
- code: import_zod15.z.ZodIssueCode.custom,
1027
+ code: import_zod16.z.ZodIssueCode.custom,
939
1028
  message: "At most one `date_bucket` entry is allowed in `groupBy`.",
940
1029
  path: ["groupBy"]
941
1030
  });
@@ -943,7 +1032,7 @@ var MetricsQuerySchema = import_zod15.z.discriminatedUnion("resource", [
943
1032
  input.metrics.forEach((metric, index) => {
944
1033
  if (metric.aggregation !== "count" && metric.field === void 0) {
945
1034
  ctx.addIssue({
946
- code: import_zod15.z.ZodIssueCode.custom,
1035
+ code: import_zod16.z.ZodIssueCode.custom,
947
1036
  message: "`field` is required unless `aggregation` is `count`.",
948
1037
  path: ["metrics", index, "field"]
949
1038
  });
@@ -952,7 +1041,7 @@ var MetricsQuerySchema = import_zod15.z.discriminatedUnion("resource", [
952
1041
  const aliases = input.metrics.map((metric) => metric.alias).filter((alias) => alias !== void 0);
953
1042
  if (new Set(aliases).size !== aliases.length) {
954
1043
  ctx.addIssue({
955
- code: import_zod15.z.ZodIssueCode.custom,
1044
+ code: import_zod16.z.ZodIssueCode.custom,
956
1045
  message: "Every `metrics[].alias` must be unique.",
957
1046
  path: ["metrics"]
958
1047
  });
@@ -961,32 +1050,32 @@ var MetricsQuerySchema = import_zod15.z.discriminatedUnion("resource", [
961
1050
  input.metrics.forEach((metric, index) => {
962
1051
  if (metric.alias !== void 0 && reservedNames.has(metric.alias)) {
963
1052
  ctx.addIssue({
964
- code: import_zod15.z.ZodIssueCode.custom,
1053
+ code: import_zod16.z.ZodIssueCode.custom,
965
1054
  message: `\`alias\` "${metric.alias}" collides with a \`groupBy\` field name (or the reserved word "bucket") \u2014 choose a different alias.`,
966
1055
  path: ["metrics", index, "alias"]
967
1056
  });
968
1057
  }
969
1058
  });
970
1059
  });
971
- var MetricsQueryResultRowSchema = import_zod15.z.record(
972
- import_zod15.z.string(),
973
- import_zod15.z.union([import_zod15.z.string(), import_zod15.z.number(), import_zod15.z.boolean(), import_zod15.z.null()])
1060
+ var MetricsQueryResultRowSchema = import_zod16.z.record(
1061
+ import_zod16.z.string(),
1062
+ import_zod16.z.union([import_zod16.z.string(), import_zod16.z.number(), import_zod16.z.boolean(), import_zod16.z.null()])
974
1063
  );
975
- var MetricsQueryResultSchema = import_zod15.z.object({
976
- data: import_zod15.z.array(MetricsQueryResultRowSchema),
977
- meta: import_zod15.z.object({
1064
+ var MetricsQueryResultSchema = import_zod16.z.object({
1065
+ data: import_zod16.z.array(MetricsQueryResultRowSchema),
1066
+ meta: import_zod16.z.object({
978
1067
  resource: MetricsResourceSchema,
979
1068
  environment: EnvironmentSchema,
980
- rowCount: import_zod15.z.number().int().describe("Number of rows in `data`."),
981
- truncated: import_zod15.z.boolean().describe(
1069
+ rowCount: import_zod16.z.number().int().describe("Number of rows in `data`."),
1070
+ truncated: import_zod16.z.boolean().describe(
982
1071
  "`true` if more rows matched than `limit` allowed \u2014 `data` holds only the first `limit`."
983
1072
  )
984
1073
  })
985
1074
  });
986
1075
 
987
1076
  // src/webhook-events.ts
988
- var import_zod16 = require("zod");
989
- var ChargeWebhookEventTypeSchema = import_zod16.z.enum([
1077
+ var import_zod17 = require("zod");
1078
+ var ChargeWebhookEventTypeSchema = import_zod17.z.enum([
990
1079
  "charge.created",
991
1080
  "charge.partially_paid",
992
1081
  "charge.confirmed",
@@ -1000,14 +1089,14 @@ var ChargeWebhookEventTypeSchema = import_zod16.z.enum([
1000
1089
  ]).describe(
1001
1090
  'Note the distinction between `charge.confirmed` and `charge.settled`: `confirmed` means the payment was detected on-chain; `settled` means the merchant\'s wallet actually received the funds \u2014 a separate, later step. Subscribe to `confirmed` if you only need "will I get paid," or `settled` if you need "has the money actually arrived." `charge.overpaid` fires alongside `charge.confirmed`/`charge.partially_paid` whenever the cumulative amount received ends up above `amount` (see `Charge.isOverpaid`). `charge.escrow_released` fires once an escrow-configured charge\'s funds have been moved out of its Safe to the split address by `POST /v1/charges/{id}/release` \u2014 a normal `charge.settled` still follows once the split itself finishes distributing. `charge.escrow_refunded` fires once an escrow-configured charge\'s funds have been moved out of its Safe back to the payer by `POST /v1/charges/{id}/refund` \u2014 mutually exclusive with `charge.escrow_released`, an escrow charge only ever emits one of the two. Every event in this category carries the full `Charge` object as `data`.'
1002
1091
  );
1003
- var WebhookDeliveryEventTypeSchema = import_zod16.z.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
1092
+ var WebhookDeliveryEventTypeSchema = import_zod17.z.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
1004
1093
  "Meta-events about the health of your own webhook endpoints \u2014 useful for monitoring without polling `GET /v1/webhooks/{id}/deliveries`. `webhook.endpoint_unhealthy` fires once when a webhook's failure rate over the trailing 24h crosses 20%, and `webhook.delivery_recovered` fires once when a delivery to that webhook next succeeds. `data` for every event in this category: `{ webhookId, url, failureRatio? }` (`failureRatio` only present on `webhook.endpoint_unhealthy`)."
1005
1094
  );
1006
- var WebhookEventTypeSchema = import_zod16.z.union([
1095
+ var WebhookEventTypeSchema = import_zod17.z.union([
1007
1096
  ChargeWebhookEventTypeSchema,
1008
1097
  WebhookDeliveryEventTypeSchema
1009
1098
  ]);
1010
- var WebhookCategorySchema = import_zod16.z.enum(["payments", "webhooks"]).describe(
1099
+ var WebhookCategorySchema = import_zod17.z.enum(["payments", "webhooks"]).describe(
1011
1100
  "Subscribe to every event in a category via `eventCategories` instead of listing events one by one \u2014 new events added to a category later arrive automatically, no subscription update needed."
1012
1101
  );
1013
1102
  function buildCategoryMap() {
@@ -1037,101 +1126,103 @@ var TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([
1037
1126
  );
1038
1127
 
1039
1128
  // src/webhooks.ts
1040
- var import_zod17 = require("zod");
1129
+ var import_zod18 = require("zod");
1041
1130
  var WEBHOOK_EVENTS_WILDCARD = "*";
1042
- var CreateWebhookSchema = import_zod17.z.object({
1043
- url: import_zod17.z.string().max(2048).url().describe(
1131
+ var CreateWebhookSchema = import_zod18.z.object({
1132
+ url: import_zod18.z.string().max(2048).url().describe(
1044
1133
  "Must be HTTPS and resolve to a public address \u2014 private/internal IPs are rejected."
1045
1134
  ),
1046
- events: import_zod17.z.array(import_zod17.z.union([WebhookEventTypeSchema, import_zod17.z.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
1135
+ events: import_zod18.z.array(import_zod18.z.union([WebhookEventTypeSchema, import_zod18.z.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
1047
1136
  'Individual event types to receive, or `"*"` for every event (combine with `excludeEvents` to opt back out of specific ones). Omit in favor of `eventCategories` if you want whole categories instead.'
1048
1137
  ),
1049
- eventCategories: import_zod17.z.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
1138
+ eventCategories: import_zod18.z.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
1050
1139
  "Subscribe to every event in these categories. At least one of `events` or `eventCategories` is required."
1051
1140
  ),
1052
- excludeEvents: import_zod17.z.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
1141
+ excludeEvents: import_zod18.z.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
1053
1142
  'Event types to exclude even if selected via `events: ["*"]` or `eventCategories`.'
1054
1143
  )
1055
1144
  }).refine((v) => v.events.length > 0 || v.eventCategories.length > 0, {
1056
1145
  message: "must select at least one event via `events` or `eventCategories`",
1057
1146
  path: ["events"]
1058
1147
  });
1059
- var WebhookSchema = import_zod17.z.object({
1060
- id: import_zod17.z.string(),
1148
+ var WebhookSchema = import_zod18.z.object({
1149
+ id: import_zod18.z.string(),
1061
1150
  environment: EnvironmentSchema.nullable().describe(
1062
1151
  "Which environment's API key created this webhook \u2014 `live` or `test`. Every event is only ever delivered to a webhook whose `environment` matches the event's own (or to a webhook with `environment: null`, which receives every environment \u2014 the case for every webhook created before this field existed)."
1063
1152
  ),
1064
- url: import_zod17.z.string(),
1065
- events: import_zod17.z.array(WebhookEventTypeSchema),
1066
- eventCategories: import_zod17.z.array(WebhookCategorySchema),
1067
- excludeEvents: import_zod17.z.array(WebhookEventTypeSchema),
1068
- isWildcard: import_zod17.z.boolean(),
1069
- secret: import_zod17.z.string().describe(
1153
+ url: import_zod18.z.string(),
1154
+ events: import_zod18.z.array(WebhookEventTypeSchema),
1155
+ eventCategories: import_zod18.z.array(WebhookCategorySchema),
1156
+ excludeEvents: import_zod18.z.array(WebhookEventTypeSchema),
1157
+ isWildcard: import_zod18.z.boolean(),
1158
+ secret: import_zod18.z.string().describe(
1070
1159
  "The signing secret, used to verify the `X-Klappay-Signature` header on every delivery. Returned in full only this once \u2014 store it now, it is not recoverable afterward. Header format: `t=<unix-seconds>,v1=<hex-encoded HMAC-SHA256>`. Compute the expected signature as `HMAC-SHA256(secret, \"${t}.${raw request body}\")` (hex-encoded) and compare it to `v1` using a constant-time comparison; as a replay-protection measure, also reject if `t` is too far from the current time \u2014 Klappay does not enforce or check any particular tolerance server-side, so the exact threshold is entirely the receiver's own policy call. An official SDK's `constructEvent()`/`verifySignature()` do this for you, defaulting to a 300-second tolerance, overridable via `constructEvent`'s `toleranceSeconds` option \u2014 see github.com/klappay for available SDKs."
1071
1160
  ),
1072
- createdAt: import_zod17.z.string().datetime()
1161
+ createdAt: import_zod18.z.string().datetime()
1073
1162
  });
1074
1163
  var WebhookListItemSchema = WebhookSchema.omit({ secret: true }).extend({
1075
- hint: import_zod17.z.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
1164
+ hint: import_zod18.z.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
1076
1165
  });
1077
- var WebhookPayloadSchema = import_zod17.z.object({
1078
- id: import_zod17.z.string().describe(
1166
+ var WebhookPayloadSchema = import_zod18.z.object({
1167
+ id: import_zod18.z.string().describe(
1079
1168
  "Unique id for this specific delivery \u2014 also sent as the `X-Klappay-Delivery` header."
1080
1169
  ),
1081
1170
  event: WebhookEventTypeSchema,
1082
- createdAt: import_zod17.z.string().datetime(),
1083
- data: import_zod17.z.unknown().describe(
1171
+ createdAt: import_zod18.z.string().datetime(),
1172
+ data: import_zod18.z.unknown().describe(
1084
1173
  "Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; webhook-delivery events carry a smaller, event-specific object \u2014 see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md."
1085
1174
  )
1086
1175
  });
1087
- var WebhookDeliveryStatusSchema = import_zod17.z.enum(["pending", "delivered", "failed"]);
1088
- var WebhookDeliverySchema = import_zod17.z.object({
1089
- id: import_zod17.z.string(),
1090
- webhookId: import_zod17.z.string(),
1176
+ var WebhookDeliveryStatusSchema = import_zod18.z.enum(["pending", "delivered", "failed"]);
1177
+ var WebhookDeliverySchema = import_zod18.z.object({
1178
+ id: import_zod18.z.string(),
1179
+ webhookId: import_zod18.z.string(),
1091
1180
  event: WebhookEventTypeSchema,
1092
1181
  status: WebhookDeliveryStatusSchema.describe(
1093
1182
  "`pending`: still retrying. `delivered`: got a 2xx response. `failed`: retries exhausted (5 attempts over ~24h) \u2014 use `POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry` to try again manually."
1094
1183
  ),
1095
- attempts: import_zod17.z.number(),
1096
- responseCode: import_zod17.z.number().nullable().describe(
1184
+ attempts: import_zod18.z.number(),
1185
+ responseCode: import_zod18.z.number().nullable().describe(
1097
1186
  "HTTP status your endpoint returned on the most recent attempt. `null` if every attempt failed to connect at all."
1098
1187
  ),
1099
- nextRetryAt: import_zod17.z.string().datetime().nullable(),
1100
- deliveredAt: import_zod17.z.string().datetime().nullable(),
1101
- createdAt: import_zod17.z.string().datetime()
1188
+ nextRetryAt: import_zod18.z.string().datetime().nullable(),
1189
+ deliveredAt: import_zod18.z.string().datetime().nullable(),
1190
+ createdAt: import_zod18.z.string().datetime()
1102
1191
  });
1103
1192
  var ListWebhookDeliveriesSchema = PaginationQuerySchema;
1104
1193
  var PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema);
1105
1194
 
1106
1195
  // src/recipients.ts
1107
- var import_zod18 = require("zod");
1108
- var EVM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
1109
- var CreateRecipientSchema = import_zod18.z.object({
1110
- address: import_zod18.z.string().regex(EVM_ADDRESS_REGEX, "must be a 20-byte hex address").describe("EVM address to register as a trusted split recipient for your organization."),
1111
- label: import_zod18.z.string().min(1).max(64).optional().describe('Free-form label for your own bookkeeping (e.g. `"supplier"`) \u2014 never interpreted.')
1196
+ var import_zod19 = require("zod");
1197
+ var CreateRecipientSchema = import_zod19.z.object({
1198
+ address: SplitAddressSchema.describe(
1199
+ "Address to register as a trusted split recipient for your organization \u2014 an EVM 0x... address or a TRON T... address."
1200
+ ),
1201
+ label: import_zod19.z.string().min(1).max(64).optional().describe('Free-form label for your own bookkeeping (e.g. `"supplier"`) \u2014 never interpreted.')
1112
1202
  });
1113
- var RecipientSchema = import_zod18.z.object({
1114
- id: import_zod18.z.string().describe(
1203
+ var RecipientSchema = import_zod19.z.object({
1204
+ id: import_zod19.z.string().describe(
1115
1205
  "Klappay-generated id, e.g. `rc_...` \u2014 this, not the raw address, is what a charge's `splitRecipients[].recipientId` references."
1116
1206
  ),
1117
1207
  environment: EnvironmentSchema,
1118
- address: import_zod18.z.string(),
1119
- label: import_zod18.z.string().nullable(),
1120
- payout: import_zod18.z.boolean().describe(
1208
+ address: import_zod19.z.string(),
1209
+ label: import_zod19.z.string().nullable(),
1210
+ payout: import_zod19.z.boolean().describe(
1121
1211
  "Whether this recipient is eligible to be used as an API key's `payoutAddress` (in addition to being referenceable in a split, which every non-revoked recipient already is). Set via `PATCH /v1/recipients/{id}` \u2014 requires the `recipients:manage_payout` scope, deliberately separate from `recipients:write`."
1122
1212
  ),
1123
- createdAt: import_zod18.z.string().datetime()
1213
+ createdAt: import_zod19.z.string().datetime()
1124
1214
  });
1125
- var SetRecipientPayoutSchema = import_zod18.z.object({
1126
- payout: import_zod18.z.boolean().describe("New payout-eligibility value for this recipient.")
1215
+ var PaginatedRecipientsSchema = paginatedSchema(RecipientSchema);
1216
+ var SetRecipientPayoutSchema = import_zod19.z.object({
1217
+ payout: import_zod19.z.boolean().describe("New payout-eligibility value for this recipient.")
1127
1218
  });
1128
1219
 
1129
1220
  // src/timeline.ts
1130
- var import_zod19 = require("zod");
1131
- var TransactionSourceSchema = import_zod19.z.enum(["contract_watcher", "reconciliation_job", "sandbox"]).describe(
1132
- "How this transfer was detected: `contract_watcher` (the normal path \u2014 a real-time on-chain event subscription), `reconciliation_job` (a fallback poller caught it after the watcher missed or delayed it), or `sandbox` (simulated via `POST /v1/sandbox/charges/{id}/trigger`, no real on-chain transfer)."
1221
+ var import_zod20 = require("zod");
1222
+ var TransactionSourceSchema = import_zod20.z.enum(["contract_watcher", "reconciliation_job", "sandbox", "tron_watcher"]).describe(
1223
+ "How this transfer was detected: `contract_watcher` (the normal path for EVM networks \u2014 a real-time WebSocket log subscription), `tron_watcher` (the TRON equivalent \u2014 a real-time ZeroMQ event subscription against a self-hosted node, a different underlying mechanism since TRON has no WebSocket log subscription), `reconciliation_job` (a fallback poller caught it after the watcher missed or delayed it), or `sandbox` (simulated via `POST /v1/sandbox/charges/{id}/trigger`, no real on-chain transfer)."
1133
1224
  );
1134
- var TimelineEventTypeSchema = import_zod19.z.enum([
1225
+ var TimelineEventTypeSchema = import_zod20.z.enum([
1135
1226
  "charge.created",
1136
1227
  "charge.expired",
1137
1228
  "transaction.detected",
@@ -1143,13 +1234,13 @@ var TimelineEventTypeSchema = import_zod19.z.enum([
1143
1234
  ]).describe(
1144
1235
  "`charge.created`: the charge was created. `charge.expired`: `expiresAt` passed with no full payment. `transaction.detected`: a raw on-chain transfer was seen (see the `event`-shaped fields below for details \u2014 a charge can have more than one, e.g. a partial payment followed by the rest). `split.distributed`: a payout to the merchant completed on-chain, for one contributing `(token, network)` pair \u2014 a charge settled across more than one pair emits one of these per pair (see the `token`/`network` fields below). `webhook.dispatched`/`webhook.delivered`/`webhook.failed`: one specific delivery *attempt* for one webhook subscription \u2014 `failed` here means this single attempt failed, not that all retries were exhausted (see `WebhookDeliveryStatusSchema` for the exhausted-all-retries state). `transfer.reclaimed`: an on-chain transfer was detected but never reached its network's required confirmation depth before vanishing (reverted, or dropped from the canonical chain) \u2014 see `txHash` below for which transfer."
1145
1236
  );
1146
- var TimelineEventSchema = import_zod19.z.object({
1237
+ var TimelineEventSchema = import_zod20.z.object({
1147
1238
  type: TimelineEventTypeSchema,
1148
- at: import_zod19.z.string().datetime(),
1149
- txHash: import_zod19.z.string().optional().describe(
1239
+ at: import_zod20.z.string().datetime(),
1240
+ txHash: import_zod20.z.string().optional().describe(
1150
1241
  "Present for `transaction.detected`, `split.distributed`, and `transfer.reclaimed` events only."
1151
1242
  ),
1152
- amount: import_zod19.z.number().optional().describe(
1243
+ amount: import_zod20.z.number().optional().describe(
1153
1244
  "Present for `transaction.detected` events only \u2014 the amount that specific transfer carried."
1154
1245
  ),
1155
1246
  source: TransactionSourceSchema.optional().describe(
@@ -1161,70 +1252,70 @@ var TimelineEventSchema = import_zod19.z.object({
1161
1252
  network: NetworkSchema.optional().describe(
1162
1253
  "Present for `transaction.detected` and `split.distributed` events \u2014 which network this specific transfer, or settlement, used."
1163
1254
  ),
1164
- causedTransition: import_zod19.z.boolean().optional().describe(
1255
+ causedTransition: import_zod20.z.boolean().optional().describe(
1165
1256
  "Present for `transaction.detected` events only. `true` if this specific transfer changed the charge's status (e.g. PENDING\u2192CONFIRMED) \u2014 a charge paid in installments can have more than one such event."
1166
1257
  ),
1167
1258
  event: WebhookEventTypeSchema.optional().describe(
1168
1259
  "Present for `webhook.*` events only \u2014 which event type this delivery was for."
1169
1260
  ),
1170
- responseCode: import_zod19.z.number().nullable().optional().describe(
1261
+ responseCode: import_zod20.z.number().nullable().optional().describe(
1171
1262
  "Present for `webhook.*` events only \u2014 HTTP status your endpoint returned, or `null` if the request never connected."
1172
1263
  ),
1173
- attempts: import_zod19.z.number().optional().describe(
1264
+ attempts: import_zod20.z.number().optional().describe(
1174
1265
  "Present for `webhook.*` events only \u2014 how many delivery attempts have been made so far."
1175
1266
  )
1176
1267
  });
1177
1268
 
1178
1269
  // src/health.ts
1179
- var import_zod20 = require("zod");
1180
- var HealthSchema = import_zod20.z.object({
1181
- status: import_zod20.z.enum(["ok", "error"]).describe(
1270
+ var import_zod21 = require("zod");
1271
+ var HealthSchema = import_zod21.z.object({
1272
+ status: import_zod21.z.enum(["ok", "error"]).describe(
1182
1273
  "`error` when the database connectivity check fails \u2014 the HTTP status code mirrors this (503 instead of 200), so a plain uptime check (not just a JSON-aware one) still catches a DB outage."
1183
1274
  ),
1184
- version: import_zod20.z.string(),
1185
- timestamp: import_zod20.z.string().datetime(),
1186
- db: import_zod20.z.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
1187
- pendingWebhooks: import_zod20.z.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
1188
- oldestPendingChargeAgeSeconds: import_zod20.z.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
1189
- lastContractWatcherEventAgeSeconds: import_zod20.z.number().nullable().describe(
1275
+ version: import_zod21.z.string(),
1276
+ timestamp: import_zod21.z.string().datetime(),
1277
+ db: import_zod21.z.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
1278
+ pendingWebhooks: import_zod21.z.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
1279
+ oldestPendingChargeAgeSeconds: import_zod21.z.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
1280
+ lastContractWatcherEventAgeSeconds: import_zod21.z.number().nullable().describe(
1190
1281
  "Seconds since the last on-chain payment notification was received \u2014 a cheap signal for whether payment detection is currently working. `null` if none have ever been received."
1191
1282
  )
1192
1283
  });
1193
1284
 
1194
1285
  // src/sandbox.ts
1195
- var import_zod21 = require("zod");
1196
- var SandboxTriggerSchema = import_zod21.z.object({
1286
+ var import_zod22 = require("zod");
1287
+ var SandboxTriggerSchema = import_zod22.z.object({
1197
1288
  event: TriggerableChargeEventSchema,
1198
- amount: import_zod21.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
1289
+ amount: import_zod22.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
1199
1290
  "Used with `charge.partially_paid` (amount to simulate as received so far \u2014 must be less than the charge amount, defaults to half of it if omitted) and with `charge.overpaid` (amount received \u2014 must be greater than the charge amount, defaults to 1.5x it if omitted). Ignored for every other event."
1200
1291
  )
1201
1292
  });
1202
1293
 
1203
1294
  // src/capabilities.ts
1204
- var import_zod22 = require("zod");
1205
- var CapabilitiesSchema = import_zod22.z.object({
1206
- acceptedPayments: import_zod22.z.array(AcceptedPaymentSchema).describe(
1295
+ var import_zod23 = require("zod");
1296
+ var CapabilitiesSchema = import_zod23.z.object({
1297
+ acceptedPayments: import_zod23.z.array(AcceptedPaymentSchema).describe(
1207
1298
  "Every `(token, network)` pair enabled for your environment right now, using the same deployment metadata and availability policy as `POST /v1/charges`. Cataloged but disabled pairs are omitted. Availability can change between requests, so handle `422 token_not_supported` when creating a charge. Use this to build a picker UI instead of hardcoding the matrix client-side."
1208
1299
  )
1209
1300
  });
1210
1301
 
1211
1302
  // src/swap.ts
1212
- var import_zod23 = require("zod");
1213
- var CreateSwapQuoteSchema = import_zod23.z.object({
1303
+ var import_zod24 = require("zod");
1304
+ var CreateSwapQuoteSchema = import_zod24.z.object({
1214
1305
  inputToken: AltTokenSchema.describe(
1215
1306
  "Which alt-cryptocurrency the payer wants to send \u2014 must be one of this charge's `swapAlternatives`, or `422 token_not_supported`."
1216
1307
  ),
1217
1308
  inputNetwork: NetworkSchema.describe(
1218
1309
  "Which network the payer will send `inputToken` on. Also picks which of this charge's `acceptedPayments` pairs the swap resolves to \u2014 a charge accepting USDC on both Base and Optimism resolves to whichever `inputNetwork` you pass. If the charge accepts more than one token on that same network, Klappay applies its token preference among enabled pairs the charge accepts. BNB Chain payments are currently disabled for both cataloged Binance-Peg tokens."
1219
1310
  ),
1220
- takerAddress: import_zod23.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").describe(
1311
+ takerAddress: import_zod24.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").describe(
1221
1312
  "The payer's own wallet address \u2014 the account that will sign and submit the swap transaction. Not validated against anything else; any well-formed address is accepted, since Klappay never custodies these funds."
1222
1313
  )
1223
1314
  });
1224
- var SwapQuoteSchema = import_zod23.z.object({
1315
+ var SwapQuoteSchema = import_zod24.z.object({
1225
1316
  inputToken: AltTokenSchema,
1226
1317
  inputNetwork: NetworkSchema,
1227
- inputAmount: import_zod23.z.number().describe(
1318
+ inputAmount: import_zod24.z.number().describe(
1228
1319
  "The ceiling of `inputToken` the payer needs available to sign for, in whole units (not wei/base units) \u2014 not necessarily the exact final cost. Any `inputToken` beyond what the swap actually needs (price moved favorably, less slippage than budgeted) is swapped back and refunded to the payer automatically, in the same transaction \u2014 never a separate step or a Klappay-side refund."
1229
1320
  ),
1230
1321
  inputAmountExact: ExactAmountSchema.optional().describe(
@@ -1234,20 +1325,20 @@ var SwapQuoteSchema = import_zod23.z.object({
1234
1325
  "Which of this charge's `acceptedPayments` tokens the swap resolves to."
1235
1326
  ),
1236
1327
  outputNetwork: NetworkSchema,
1237
- outputAmount: import_zod23.z.number().describe(
1328
+ outputAmount: import_zod24.z.number().describe(
1238
1329
  "The stablecoin amount requested by this quote, in whole `outputToken` units. Covers the remaining balance, rounded up only if the selected token cannot represent it exactly. This legacy JSON number can lose precision; use `outputAmountExact` for arithmetic. The actual transfer is verified on-chain before crediting the charge."
1239
1330
  ),
1240
1331
  outputAmountExact: ExactAmountSchema.optional().describe(
1241
1332
  "Exact stablecoin amount requested by this quote, in whole `outputToken` units as a nonnegative decimal string with no scientific notation. Covers the remaining charge balance and rounds upward only to the smallest representable token unit when needed. Optional for compatibility with older API responses."
1242
1333
  ),
1243
- fees: import_zod23.z.object({
1244
- klappayFee: import_zod23.z.number().describe(
1334
+ fees: import_zod24.z.object({
1335
+ klappayFee: import_zod24.z.number().describe(
1245
1336
  "Klappay's own swap fee (1% today), in `outputToken` units \u2014 paid by the payer and already reflected in `inputAmount`, separate from the merchant's own `feePercent`. Never subtracted from `outputAmount`."
1246
1337
  ),
1247
1338
  klappayFeeExact: ExactAmountSchema.optional().describe(
1248
1339
  "Exact Klappay swap fee in whole `outputToken` units as a nonnegative decimal string with at most 18 fractional digits and no scientific notation. Already reflected in the input ceiling. Optional for compatibility with older API responses."
1249
1340
  ),
1250
- zeroExFee: import_zod23.z.number().nullable().describe(
1341
+ zeroExFee: import_zod24.z.number().nullable().describe(
1251
1342
  "0x's own protocol fee for this specific token pair, in `outputToken` units, or `null` when this pair isn't currently one 0x charges on. Paid by the payer and already reflected in `inputAmount`, never subtracted from `outputAmount` \u2014 Klappay never sees this fee, it goes straight to 0x."
1252
1343
  ),
1253
1344
  zeroExFeeExact: ExactAmountSchema.nullable().optional().describe(
@@ -1256,19 +1347,19 @@ var SwapQuoteSchema = import_zod23.z.object({
1256
1347
  }).describe(
1257
1348
  "Every fee the payer is charged for using swap-to-pay, broken out by who collects it \u2014 both already reflected in `inputAmount`, shown here separately for transparency. Neither ever reduces `outputAmount`."
1258
1349
  ),
1259
- expiresAt: import_zod23.z.string().datetime().describe(
1350
+ expiresAt: import_zod24.z.string().datetime().describe(
1260
1351
  "When this quote's price is no longer safely valid \u2014 a rough guide for the payer's UI countdown only. The actual price guarantee is enforced on-chain by the swap transaction itself (a signed Permit2 deadline, or a minimum-output check for a native-currency sell), not by this timestamp \u2014 submitting after it expires either reverts on-chain or simply gets re-quoted at the current price, never silently executes at a stale rate."
1261
1352
  ),
1262
- transaction: import_zod23.z.object({
1263
- to: import_zod23.z.string().describe("Contract address the payer's wallet must send this transaction to."),
1264
- data: import_zod23.z.string().describe("Calldata \u2014 opaque, must be sent unmodified."),
1265
- value: import_zod23.z.string().describe(
1353
+ transaction: import_zod24.z.object({
1354
+ to: import_zod24.z.string().describe("Contract address the payer's wallet must send this transaction to."),
1355
+ data: import_zod24.z.string().describe("Calldata \u2014 opaque, must be sent unmodified."),
1356
+ value: import_zod24.z.string().describe(
1266
1357
  "Native currency (ETH/BNB/POL/AVAX) to attach, in wei \u2014 `\"0\"` when `inputToken` isn't this network's native currency."
1267
1358
  )
1268
1359
  }).describe(
1269
1360
  "Pass this directly to the payer's wallet (e.g. viem/ethers `sendTransaction`) \u2014 Klappay never touches the payer's private key or submits anything on their behalf. If `permit2` is present on this response, sign that first and append the signature to this `data` before sending; if `permit2` is absent, send `transaction` as-is with no extra step."
1270
1361
  ),
1271
- permit2: import_zod23.z.object({ eip712: import_zod23.z.record(import_zod23.z.unknown()) }).nullish().describe(
1362
+ permit2: import_zod24.z.object({ eip712: import_zod24.z.record(import_zod24.z.unknown()) }).nullish().describe(
1272
1363
  "Present only when `inputToken` is an ERC-20 (BTC, LINK, or a chain-specific blue chip like ARB/OP/CBETH) \u2014 the payer's wallet must sign this EIP-712 message and append the signature to `transaction.data` before sending, since an ERC-20 sell needs a Permit2 allowance signature that a native-currency sell doesn't. `null` (never omitted, in a genuine 0x-backed quote) when `inputToken` is a network's own native currency (ETH/BNB/POL/AVAX) \u2014 `transaction` is then ready to sign and send directly, no extra step."
1273
1364
  )
1274
1365
  });
@@ -1333,6 +1424,7 @@ var SwapQuoteSchema = import_zod23.z.object({
1333
1424
  MetricsQuerySchema,
1334
1425
  MetricsResourceSchema,
1335
1426
  NETWORK_EXPLORERS,
1427
+ NETWORK_FAMILIES,
1336
1428
  NETWORK_LABELS,
1337
1429
  NetworkSchema,
1338
1430
  OPERATIONAL_NETWORKS,
@@ -1341,6 +1433,7 @@ var SwapQuoteSchema = import_zod23.z.object({
1341
1433
  PAGINATION_LIMIT_MIN,
1342
1434
  PaginatedChargesSchema,
1343
1435
  PaginatedPendingDistributionsSchema,
1436
+ PaginatedRecipientsSchema,
1344
1437
  PaginatedWebhookDeliveriesSchema,
1345
1438
  PaginationQuerySchema,
1346
1439
  PendingDistributionEventSchema,
@@ -1352,6 +1445,7 @@ var SwapQuoteSchema = import_zod23.z.object({
1352
1445
  SandboxTriggerSchema,
1353
1446
  SetRecipientPayoutSchema,
1354
1447
  SettlementStatusSchema,
1448
+ SplitAddressSchema,
1355
1449
  SplitDistributionStatusSchema,
1356
1450
  SplitRecipientInputSchema,
1357
1451
  SplitRecipientSchema,
@@ -1378,10 +1472,15 @@ var SwapQuoteSchema = import_zod23.z.object({
1378
1472
  WebhookListItemSchema,
1379
1473
  WebhookPayloadSchema,
1380
1474
  WebhookSchema,
1475
+ addressesEqual,
1381
1476
  findConflictingScopes,
1382
1477
  getTokenDeployment,
1478
+ isEvmAddress,
1383
1479
  isPaymentDeploymentEnabled,
1480
+ isSplitAddress,
1481
+ isTronAddress,
1384
1482
  listSwapAlternatives,
1385
- paginatedSchema
1483
+ paginatedSchema,
1484
+ tronAddress
1386
1485
  });
1387
1486
  //# sourceMappingURL=index.js.map