@klappay/types 3.0.0 → 3.0.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
@@ -20,8 +20,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ ALT_TOKEN_ADDRESSES: () => ALT_TOKEN_ADDRESSES,
24
+ ALT_TOKEN_DECIMALS: () => ALT_TOKEN_DECIMALS,
23
25
  API_KEY_SCOPES: () => API_KEY_SCOPES,
24
26
  AcceptedPaymentSchema: () => AcceptedPaymentSchema,
27
+ AltTokenSchema: () => AltTokenSchema,
25
28
  ApiKeyScopeSchema: () => ApiKeyScopeSchema,
26
29
  CHARGE_ACCEPTED_PAYMENTS_MAX: () => CHARGE_ACCEPTED_PAYMENTS_MAX,
27
30
  CHARGE_AMOUNT_MAX: () => CHARGE_AMOUNT_MAX,
@@ -40,6 +43,7 @@ __export(index_exports, {
40
43
  CheckoutProductSchema: () => CheckoutProductSchema,
41
44
  CreateChargeSchema: () => CreateChargeSchema,
42
45
  CreateRecipientSchema: () => CreateRecipientSchema,
46
+ CreateSwapQuoteSchema: () => CreateSwapQuoteSchema,
43
47
  CreateWebhookSchema: () => CreateWebhookSchema,
44
48
  DistributionsDateFieldSchema: () => DistributionsDateFieldSchema,
45
49
  DistributionsMetricFieldSchema: () => DistributionsMetricFieldSchema,
@@ -89,6 +93,7 @@ __export(index_exports, {
89
93
  SplitDistributionStatusSchema: () => SplitDistributionStatusSchema,
90
94
  SplitRecipientInputSchema: () => SplitRecipientInputSchema,
91
95
  SplitRecipientSchema: () => SplitRecipientSchema,
96
+ SwapQuoteSchema: () => SwapQuoteSchema,
92
97
  TOKEN_ADDRESSES: () => TOKEN_ADDRESSES,
93
98
  TOKEN_DECIMALS: () => TOKEN_DECIMALS,
94
99
  TimelineEventSchema: () => TimelineEventSchema,
@@ -110,6 +115,7 @@ __export(index_exports, {
110
115
  WebhookPayloadSchema: () => WebhookPayloadSchema,
111
116
  WebhookSchema: () => WebhookSchema,
112
117
  findConflictingScopes: () => findConflictingScopes,
118
+ listAltTokensForNetworks: () => listAltTokensForNetworks,
113
119
  paginatedSchema: () => paginatedSchema
114
120
  });
115
121
  module.exports = __toCommonJS(index_exports);
@@ -264,51 +270,82 @@ var TOKEN_ADDRESSES = {
264
270
  }
265
271
  };
266
272
 
273
+ // src/alt-tokens.ts
274
+ var import_zod7 = require("zod");
275
+ var AltTokenSchema = import_zod7.z.enum(["ETH", "BNB", "MATIC", "AVAX", "BTC"]).describe(
276
+ "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. Only a network's own native currency, plus `BTC` (wrapped) on the networks with deep, reputably-custodied liquidity, is trusted today (see `ALT_TOKEN_ADDRESSES`) \u2014 never assume every value here is available on every network."
277
+ );
278
+ var ALT_TOKEN_DECIMALS = {
279
+ ETH: 18,
280
+ BNB: 18,
281
+ MATIC: 18,
282
+ AVAX: 18,
283
+ BTC: 8
284
+ };
285
+ var ALT_TOKEN_ADDRESSES = {
286
+ base: { ETH: "native", BTC: "0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf" },
287
+ optimism: { ETH: "native", BTC: "0x68f180fcCe6836688e9084f035309E29Bf0A2095" },
288
+ ethereum: { ETH: "native", BTC: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599" },
289
+ arbitrum: { ETH: "native", BTC: "0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f" },
290
+ polygon: { MATIC: "native", BTC: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6" },
291
+ avalanche: { AVAX: "native" },
292
+ bnb: { BNB: "native" }
293
+ };
294
+ function listAltTokensForNetworks(networks) {
295
+ const found = /* @__PURE__ */ new Set();
296
+ for (const network of networks) {
297
+ for (const token of Object.keys(ALT_TOKEN_ADDRESSES[network] ?? {})) {
298
+ found.add(token);
299
+ }
300
+ }
301
+ return [...found];
302
+ }
303
+
267
304
  // src/charges.ts
268
- var import_zod8 = require("zod");
305
+ var import_zod9 = require("zod");
269
306
 
270
307
  // src/checkout-metadata.ts
271
- var import_zod7 = require("zod");
308
+ var import_zod8 = require("zod");
272
309
  var CHECKOUT_PRODUCTS_MAX = 20;
273
- var CheckoutProductSchema = import_zod7.z.object({
274
- name: import_zod7.z.string().min(1).max(200).describe("What the payer is buying, shown as-is on the hosted checkout page."),
275
- quantity: import_zod7.z.number().int().positive().max(9999).optional().describe("How many of this item. Omit for a single, unquantified item."),
276
- imageUrl: import_zod7.z.string().url().max(2048).refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
310
+ var CheckoutProductSchema = import_zod8.z.object({
311
+ name: import_zod8.z.string().min(1).max(200).describe("What the payer is buying, shown as-is on the hosted checkout page."),
312
+ quantity: import_zod8.z.number().int().positive().max(9999).optional().describe("How many of this item. Omit for a single, unquantified item."),
313
+ imageUrl: import_zod8.z.string().url().max(2048).refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
277
314
  "Product image, fetched only by the payer's own browser \u2014 Klappay never fetches it server-side. Must be `http(s)`."
278
315
  )
279
316
  });
280
- var KlappayCheckoutMetadataSchema = import_zod7.z.object({
281
- products: import_zod7.z.array(CheckoutProductSchema).max(CHECKOUT_PRODUCTS_MAX).optional().describe(
317
+ var KlappayCheckoutMetadataSchema = import_zod8.z.object({
318
+ products: import_zod8.z.array(CheckoutProductSchema).max(CHECKOUT_PRODUCTS_MAX).optional().describe(
282
319
  `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.`
283
320
  )
284
321
  }).describe(
285
322
  "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."
286
323
  );
287
- var MetadataWithKlappaySchema = import_zod7.z.object({ klappay: KlappayCheckoutMetadataSchema.optional() }).catchall(import_zod7.z.unknown()).describe(
324
+ var MetadataWithKlappaySchema = import_zod8.z.object({ klappay: KlappayCheckoutMetadataSchema.optional() }).catchall(import_zod8.z.unknown()).describe(
288
325
  "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`."
289
326
  );
290
327
 
291
328
  // src/charges.ts
292
- var ChargeStatusSchema = import_zod8.z.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
329
+ var ChargeStatusSchema = import_zod9.z.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
293
330
  "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."
294
331
  );
295
- var SettlementStatusSchema = import_zod8.z.enum(["pending", "completed", "failed"]).describe(
332
+ var SettlementStatusSchema = import_zod9.z.enum(["pending", "completed", "failed"]).describe(
296
333
  "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."
297
334
  );
298
335
  var CHARGE_EXPIRES_IN_MIN_SECONDS = 60;
299
336
  var CHARGE_EXPIRES_IN_MAX_SECONDS = 3600;
300
337
  var CHARGE_ACCEPTED_PAYMENTS_MAX = 14;
301
- var AcceptedPaymentSchema = import_zod8.z.object({
338
+ var AcceptedPaymentSchema = import_zod9.z.object({
302
339
  token: TokenSchema,
303
340
  network: NetworkSchema
304
341
  });
305
- var AcceptedPaymentsSchema = import_zod8.z.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
342
+ var AcceptedPaymentsSchema = import_zod9.z.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
306
343
  const seen = /* @__PURE__ */ new Set();
307
344
  pairs.forEach((pair, index) => {
308
345
  const key = `${pair.token}:${pair.network}`;
309
346
  if (seen.has(key)) {
310
347
  ctx.addIssue({
311
- code: import_zod8.z.ZodIssueCode.custom,
348
+ code: import_zod9.z.ZodIssueCode.custom,
312
349
  message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,
313
350
  path: [index]
314
351
  });
@@ -316,7 +353,7 @@ var AcceptedPaymentsSchema = import_zod8.z.array(AcceptedPaymentSchema).min(1, "
316
353
  seen.add(key);
317
354
  if (!OPERATIONAL_NETWORKS.includes(pair.network)) {
318
355
  ctx.addIssue({
319
- code: import_zod8.z.ZodIssueCode.custom,
356
+ code: import_zod9.z.ZodIssueCode.custom,
320
357
  message: `Network "${pair.network}" isn't live yet \u2014 only ${OPERATIONAL_NETWORKS.join(", ")} today.`,
321
358
  path: [index, "network"]
322
359
  });
@@ -326,32 +363,32 @@ var AcceptedPaymentsSchema = import_zod8.z.array(AcceptedPaymentSchema).min(1, "
326
363
  `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\`.`
327
364
  );
328
365
  var CHARGE_SPLIT_RECIPIENTS_MAX = 5;
329
- var SplitRecipientSchema = import_zod8.z.object({
330
- address: import_zod8.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."),
331
- percent: import_zod8.z.number().positive().max(100).describe(
366
+ var SplitRecipientSchema = import_zod9.z.object({
367
+ address: import_zod9.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."),
368
+ percent: import_zod9.z.number().positive().max(100).describe(
332
369
  "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."
333
370
  ),
334
- label: import_zod8.z.string().min(1).max(64).optional().describe(
371
+ label: import_zod9.z.string().min(1).max(64).optional().describe(
335
372
  'Free-form label for your own bookkeeping (e.g. `"supplier"`, `"sales rep"`) \u2014 echoed back unchanged, never interpreted by Klappay.'
336
373
  )
337
374
  });
338
- var SplitRecipientInputSchema = import_zod8.z.object({
339
- recipientId: import_zod8.z.string().describe(
375
+ var SplitRecipientInputSchema = import_zod9.z.object({
376
+ recipientId: import_zod9.z.string().describe(
340
377
  "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."
341
378
  ),
342
- percent: import_zod8.z.number().positive().max(100).describe(
379
+ percent: import_zod9.z.number().positive().max(100).describe(
343
380
  "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."
344
381
  ),
345
- label: import_zod8.z.string().min(1).max(64).optional().describe(
382
+ label: import_zod9.z.string().min(1).max(64).optional().describe(
346
383
  '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.'
347
384
  )
348
385
  });
349
- var SplitRecipientsInputSchema = import_zod8.z.array(SplitRecipientInputSchema).max(CHARGE_SPLIT_RECIPIENTS_MAX).superRefine((recipients, ctx) => {
386
+ var SplitRecipientsInputSchema = import_zod9.z.array(SplitRecipientInputSchema).max(CHARGE_SPLIT_RECIPIENTS_MAX).superRefine((recipients, ctx) => {
350
387
  const seen = /* @__PURE__ */ new Set();
351
388
  recipients.forEach((recipient, index) => {
352
389
  if (seen.has(recipient.recipientId)) {
353
390
  ctx.addIssue({
354
- code: import_zod8.z.ZodIssueCode.custom,
391
+ code: import_zod9.z.ZodIssueCode.custom,
355
392
  message: `Duplicate split recipientId: ${recipient.recipientId}.`,
356
393
  path: [index, "recipientId"]
357
394
  });
@@ -362,79 +399,82 @@ var SplitRecipientsInputSchema = import_zod8.z.array(SplitRecipientInputSchema).
362
399
  `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\`.`
363
400
  );
364
401
  var CHARGE_AMOUNT_MAX = 999999999999;
365
- var CreateChargeSchema = import_zod8.z.object({
366
- amount: import_zod8.z.number().positive().max(CHARGE_AMOUNT_MAX).describe(
402
+ var CreateChargeSchema = import_zod9.z.object({
403
+ amount: import_zod9.z.number().positive().max(CHARGE_AMOUNT_MAX).describe(
367
404
  "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."
368
405
  ),
369
- currency: import_zod8.z.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
406
+ currency: import_zod9.z.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
370
407
  acceptedPayments: AcceptedPaymentsSchema,
371
- expiresIn: import_zod8.z.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
408
+ expiresIn: import_zod9.z.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
372
409
  "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."
373
410
  ),
374
- idempotencyKey: import_zod8.z.string().min(1).max(255).optional().describe(
411
+ idempotencyKey: import_zod9.z.string().min(1).max(255).optional().describe(
375
412
  "Scoped to your tenant. Replaying the same key returns the original charge unchanged instead of creating a duplicate \u2014 safe to retry a request after a timeout without double-charging."
376
413
  ),
377
- externalRef: import_zod8.z.string().min(1).max(255).optional().describe(
414
+ externalRef: import_zod9.z.string().min(1).max(255).optional().describe(
378
415
  "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."
379
416
  ),
380
- source: import_zod8.z.string().min(1).max(64).optional().describe(
417
+ source: import_zod9.z.string().min(1).max(64).optional().describe(
381
418
  '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.'
382
419
  ),
383
420
  metadata: MetadataWithKlappaySchema.optional(),
384
- redirectUrl: import_zod8.z.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
421
+ redirectUrl: import_zod9.z.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
385
422
  "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."
386
423
  ),
387
424
  splitRecipients: SplitRecipientsInputSchema.optional()
388
425
  });
389
- var ChargeSchema = import_zod8.z.object({
390
- id: import_zod8.z.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
391
- amount: import_zod8.z.number().describe("The amount originally requested, in `currency` units (up to 6 decimal places)."),
392
- amountReceived: import_zod8.z.number().nullable().describe(
426
+ var ChargeSchema = import_zod9.z.object({
427
+ id: import_zod9.z.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
428
+ amount: import_zod9.z.number().describe("The amount originally requested, in `currency` units (up to 6 decimal places)."),
429
+ amountReceived: import_zod9.z.number().nullable().describe(
393
430
  "Cumulative amount actually received on-chain so far, in `currency` units (up to 6 decimal places). `null` until the first transfer arrives. Can exceed `amount` \u2014 see `isOverpaid`."
394
431
  ),
395
- isOverpaid: import_zod8.z.boolean().describe(
432
+ isOverpaid: import_zod9.z.boolean().describe(
396
433
  "`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically \u2014 see the docs for why."
397
434
  ),
398
- currency: import_zod8.z.string().describe("Always `USD` today \u2014 the only supported currency."),
399
- acceptedPayments: import_zod8.z.array(AcceptedPaymentSchema).describe(
435
+ currency: import_zod9.z.string().describe("Always `USD` today \u2014 the only supported currency."),
436
+ acceptedPayments: import_zod9.z.array(AcceptedPaymentSchema).describe(
400
437
  "Every `(token, network)` pair this charge was configured to accept, unchanged after creation."
401
438
  ),
402
- paidWith: import_zod8.z.array(AcceptedPaymentSchema).describe(
439
+ paidWith: import_zod9.z.array(AcceptedPaymentSchema).describe(
403
440
  "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`."
404
441
  ),
405
- address: import_zod8.z.string().describe(
442
+ swapAlternatives: import_zod9.z.array(AltTokenSchema).describe(
443
+ "Non-stablecoin cryptocurrencies 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 Base lists `ETH` here, since Base's native currency is trusted as swap input). 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, or if swap-to-pay isn't configured on this deployment."
444
+ ),
445
+ address: import_zod9.z.string().describe(
406
446
  "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."
407
447
  ),
408
448
  status: ChargeStatusSchema,
409
449
  settlementStatus: SettlementStatusSchema.nullable(),
410
450
  environment: EnvironmentSchema,
411
- apiKeyId: import_zod8.z.string().nullable().describe(
451
+ apiKeyId: import_zod9.z.string().nullable().describe(
412
452
  "Which of your API keys created this charge. `null` for a charge created before this field existed."
413
453
  ),
414
- txHash: import_zod8.z.string().nullable().describe(
454
+ txHash: import_zod9.z.string().nullable().describe(
415
455
  "Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected."
416
456
  ),
417
- externalRef: import_zod8.z.string().nullable(),
418
- source: import_zod8.z.string().nullable(),
457
+ externalRef: import_zod9.z.string().nullable(),
458
+ source: import_zod9.z.string().nullable(),
419
459
  metadata: MetadataWithKlappaySchema.nullable(),
420
- redirectUrl: import_zod8.z.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
421
- checkoutUrl: import_zod8.z.string().nullable().describe(
460
+ redirectUrl: import_zod9.z.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
461
+ checkoutUrl: import_zod9.z.string().nullable().describe(
422
462
  "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."
423
463
  ),
424
- splitRecipients: import_zod8.z.array(SplitRecipientSchema).describe("Echoes whatever extra split recipients were set at creation \u2014 empty array if none."),
425
- createdAt: import_zod8.z.string().datetime(),
426
- expiresAt: import_zod8.z.string().datetime().describe(
464
+ splitRecipients: import_zod9.z.array(SplitRecipientSchema).describe("Echoes whatever extra split recipients were set at creation \u2014 empty array if none."),
465
+ createdAt: import_zod9.z.string().datetime(),
466
+ expiresAt: import_zod9.z.string().datetime().describe(
427
467
  "When this charge stops accepting payment, if still `pending`/`partially_paid` by then."
428
468
  ),
429
- confirmedAt: import_zod8.z.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
430
- settledAt: import_zod8.z.string().datetime().nullable().describe(
469
+ confirmedAt: import_zod9.z.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
470
+ settledAt: import_zod9.z.string().datetime().nullable().describe(
431
471
  "When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
432
472
  ),
433
- lastActivityAt: import_zod8.z.string().datetime().describe(
473
+ lastActivityAt: import_zod9.z.string().datetime().describe(
434
474
  "When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet."
435
475
  )
436
476
  });
437
- var ListChargesSchema = import_zod8.z.object({
477
+ var ListChargesSchema = import_zod9.z.object({
438
478
  status: ChargeStatusSchema.optional(),
439
479
  token: TokenSchema.optional().describe(
440
480
  "Filters on `paidWith.token` \u2014 the pair actually paid, not accepted."
@@ -443,13 +483,13 @@ var ListChargesSchema = import_zod8.z.object({
443
483
  "Filters on `paidWith.network` \u2014 the pair actually paid, not accepted."
444
484
  ),
445
485
  environment: EnvironmentSchema.optional(),
446
- since: import_zod8.z.string().datetime().optional().describe(
486
+ since: import_zod9.z.string().datetime().optional().describe(
447
487
  "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."
448
488
  ),
449
- isOverpaid: import_zod8.z.enum(["true", "false"]).transform((v) => v === "true").optional()
489
+ isOverpaid: import_zod9.z.enum(["true", "false"]).transform((v) => v === "true").optional()
450
490
  }).extend(PaginationQuerySchema.shape);
451
491
  var PaginatedChargesSchema = paginatedSchema(ChargeSchema);
452
- var GetChargeQrCodeQuerySchema = import_zod8.z.object({
492
+ var GetChargeQrCodeQuerySchema = import_zod9.z.object({
453
493
  token: TokenSchema.optional().describe(
454
494
  "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."
455
495
  ),
@@ -457,61 +497,61 @@ var GetChargeQrCodeQuerySchema = import_zod8.z.object({
457
497
  });
458
498
 
459
499
  // src/distributions.ts
460
- var import_zod9 = require("zod");
461
- var SplitDistributionStatusSchema = import_zod9.z.enum(["pending", "processing", "completed", "failed"]).describe(
500
+ var import_zod10 = require("zod");
501
+ var SplitDistributionStatusSchema = import_zod10.z.enum(["pending", "processing", "completed", "failed"]).describe(
462
502
  "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."
463
503
  );
464
- var PendingDistributionRecipientSchema = import_zod9.z.object({
465
- address: import_zod9.z.string().describe("On-chain recipient address."),
466
- percentAllocation: import_zod9.z.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
504
+ var PendingDistributionRecipientSchema = import_zod10.z.object({
505
+ address: import_zod10.z.string().describe("On-chain recipient address."),
506
+ percentAllocation: import_zod10.z.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
467
507
  });
468
- var PendingDistributionSchema = import_zod9.z.object({
469
- splitAddress: import_zod9.z.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
508
+ var PendingDistributionSchema = import_zod10.z.object({
509
+ splitAddress: import_zod10.z.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
470
510
  network: NetworkSchema,
471
511
  token: TokenSchema,
472
- recipients: import_zod9.z.array(PendingDistributionRecipientSchema).describe(
512
+ recipients: import_zod10.z.array(PendingDistributionRecipientSchema).describe(
473
513
  "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."
474
514
  ),
475
- distributorFeePercent: import_zod9.z.number().describe(
515
+ distributorFeePercent: import_zod10.z.number().describe(
476
516
  "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."
477
517
  ),
478
- estimatedRewardAmount: import_zod9.z.number().describe(
518
+ estimatedRewardAmount: import_zod10.z.number().describe(
479
519
  "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."
480
520
  ),
481
- availableSince: import_zod9.z.string().datetime().describe("When this distribution entered its grace period."),
482
- graceEndsAt: import_zod9.z.string().datetime().describe(
521
+ availableSince: import_zod10.z.string().datetime().describe("When this distribution entered its grace period."),
522
+ graceEndsAt: import_zod10.z.string().datetime().describe(
483
523
  "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."
484
524
  )
485
525
  });
486
526
  var PaginatedPendingDistributionsSchema = paginatedSchema(PendingDistributionSchema);
487
- var ListenPendingDistributionsQuerySchema = import_zod9.z.object({
488
- limit: import_zod9.z.coerce.number().int().min(0).max(PAGINATION_LIMIT_MAX).default(0).describe(
527
+ var ListenPendingDistributionsQuerySchema = import_zod10.z.object({
528
+ limit: import_zod10.z.coerce.number().int().min(0).max(PAGINATION_LIMIT_MAX).default(0).describe(
489
529
  "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."
490
530
  )
491
531
  });
492
- var PendingDistributionEventSchema = import_zod9.z.discriminatedUnion("type", [
493
- import_zod9.z.object({
494
- type: import_zod9.z.literal("distribution.available"),
532
+ var PendingDistributionEventSchema = import_zod10.z.discriminatedUnion("type", [
533
+ import_zod10.z.object({
534
+ type: import_zod10.z.literal("distribution.available"),
495
535
  distribution: PendingDistributionSchema
496
536
  }),
497
- import_zod9.z.object({
498
- type: import_zod9.z.literal("distribution.claimed"),
499
- splitAddress: import_zod9.z.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
537
+ import_zod10.z.object({
538
+ type: import_zod10.z.literal("distribution.claimed"),
539
+ splitAddress: import_zod10.z.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
500
540
  })
501
541
  ]);
502
542
 
503
543
  // src/metrics.ts
504
- var import_zod10 = require("zod");
505
- var MetricsResourceSchema = import_zod10.z.enum(["charges", "transactions", "distributions"]).describe(
544
+ var import_zod11 = require("zod");
545
+ var MetricsResourceSchema = import_zod11.z.enum(["charges", "transactions", "distributions"]).describe(
506
546
  "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."
507
547
  );
508
- var MetricsAggregationSchema = import_zod10.z.enum(["count", "sum", "avg", "min", "max"]).describe(
548
+ var MetricsAggregationSchema = import_zod11.z.enum(["count", "sum", "avg", "min", "max"]).describe(
509
549
  "`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."
510
550
  );
511
- var MetricsFilterOperatorSchema = import_zod10.z.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
551
+ var MetricsFilterOperatorSchema = import_zod11.z.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
512
552
  "`in` expects an array value (max 50 entries); every other operator expects a single scalar."
513
553
  );
514
- var MetricsDateGranularitySchema = import_zod10.z.enum(["day", "week", "month", "year"]).describe(
554
+ var MetricsDateGranularitySchema = import_zod11.z.enum(["day", "week", "month", "year"]).describe(
515
555
  "Bucket width for a `date_bucket` `groupBy` entry \u2014 Postgres `date_trunc` semantics (UTC)."
516
556
  );
517
557
  var metricsQueryEnvironmentSchema = EnvironmentSchema.describe(
@@ -524,151 +564,151 @@ var METRICS_QUERY_MAX_GROUP_BY = 3;
524
564
  var METRICS_QUERY_MAX_FILTERS = 20;
525
565
  var METRICS_QUERY_MAX_METRICS = 10;
526
566
  var METRIC_ALIAS_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
527
- var metricAliasSchema = import_zod10.z.string().min(1).max(64).regex(
567
+ var metricAliasSchema = import_zod11.z.string().min(1).max(64).regex(
528
568
  METRIC_ALIAS_PATTERN,
529
569
  "Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 this becomes a SQL column alias."
530
570
  ).optional();
531
- var MetricsFilterValueSchema = import_zod10.z.union([
532
- import_zod10.z.string().max(255),
533
- import_zod10.z.number(),
534
- import_zod10.z.boolean(),
535
- import_zod10.z.array(import_zod10.z.union([import_zod10.z.string().max(255), import_zod10.z.number()])).min(1).max(50)
571
+ var MetricsFilterValueSchema = import_zod11.z.union([
572
+ import_zod11.z.string().max(255),
573
+ import_zod11.z.number(),
574
+ import_zod11.z.boolean(),
575
+ import_zod11.z.array(import_zod11.z.union([import_zod11.z.string().max(255), import_zod11.z.number()])).min(1).max(50)
536
576
  ]);
537
- var orderBySchema = import_zod10.z.object({
538
- key: import_zod10.z.string().min(1).max(64).regex(
577
+ var orderBySchema = import_zod11.z.object({
578
+ key: import_zod11.z.string().min(1).max(64).regex(
539
579
  METRIC_ALIAS_PATTERN,
540
580
  "Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 every valid output column name already looks like this."
541
581
  ).describe(
542
582
  "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."
543
583
  ),
544
- direction: import_zod10.z.enum(["asc", "desc"])
584
+ direction: import_zod11.z.enum(["asc", "desc"])
545
585
  }).describe(
546
586
  "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."
547
587
  );
548
- var limitSchema = import_zod10.z.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
588
+ var limitSchema = import_zod11.z.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
549
589
  `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.`
550
590
  );
551
- var ChargesQueryFieldSchema = import_zod10.z.enum(["status", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
591
+ var ChargesQueryFieldSchema = import_zod11.z.enum(["status", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
552
592
  "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."
553
593
  );
554
- var ChargesMetricFieldSchema = import_zod10.z.enum(["amount", "amountReceived", "feePercent"]).describe(
594
+ var ChargesMetricFieldSchema = import_zod11.z.enum(["amount", "amountReceived", "feePercent"]).describe(
555
595
  "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%."
556
596
  );
557
- var ChargesDateFieldSchema = import_zod10.z.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt"]).describe(
597
+ var ChargesDateFieldSchema = import_zod11.z.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt"]).describe(
558
598
  "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."
559
599
  );
560
- var ChargesFilterSchema = import_zod10.z.object({
600
+ var ChargesFilterSchema = import_zod11.z.object({
561
601
  field: ChargesQueryFieldSchema,
562
602
  operator: MetricsFilterOperatorSchema,
563
603
  value: MetricsFilterValueSchema
564
604
  });
565
- var ChargesGroupBySchema = import_zod10.z.union([
566
- import_zod10.z.object({ type: import_zod10.z.literal("field"), field: ChargesQueryFieldSchema }),
567
- import_zod10.z.object({
568
- type: import_zod10.z.literal("date_bucket"),
605
+ var ChargesGroupBySchema = import_zod11.z.union([
606
+ import_zod11.z.object({ type: import_zod11.z.literal("field"), field: ChargesQueryFieldSchema }),
607
+ import_zod11.z.object({
608
+ type: import_zod11.z.literal("date_bucket"),
569
609
  field: ChargesDateFieldSchema,
570
610
  granularity: MetricsDateGranularitySchema
571
611
  })
572
612
  ]);
573
- var ChargesMetricSchema = import_zod10.z.object({
613
+ var ChargesMetricSchema = import_zod11.z.object({
574
614
  aggregation: MetricsAggregationSchema,
575
615
  field: ChargesMetricFieldSchema.optional(),
576
616
  alias: metricAliasSchema
577
617
  });
578
- var ChargesMetricsQuerySchema = import_zod10.z.object({
579
- resource: import_zod10.z.literal("charges"),
618
+ var ChargesMetricsQuerySchema = import_zod11.z.object({
619
+ resource: import_zod11.z.literal("charges"),
580
620
  environment: metricsQueryEnvironmentSchema,
581
- dateRange: import_zod10.z.object({
621
+ dateRange: import_zod11.z.object({
582
622
  field: ChargesDateFieldSchema,
583
- from: import_zod10.z.string().max(64).datetime(),
584
- to: import_zod10.z.string().max(64).datetime()
623
+ from: import_zod11.z.string().max(64).datetime(),
624
+ to: import_zod11.z.string().max(64).datetime()
585
625
  }),
586
- groupBy: import_zod10.z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
587
- metrics: import_zod10.z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
588
- filters: import_zod10.z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
626
+ groupBy: import_zod11.z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
627
+ metrics: import_zod11.z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
628
+ filters: import_zod11.z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
589
629
  orderBy: orderBySchema.optional(),
590
630
  limit: limitSchema
591
631
  });
592
- var TransactionsQueryFieldSchema = import_zod10.z.enum(["network", "token", "source", "causedTransition"]).describe(
632
+ var TransactionsQueryFieldSchema = import_zod11.z.enum(["network", "token", "source", "causedTransition"]).describe(
593
633
  "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)."
594
634
  );
595
- var TransactionsMetricFieldSchema = import_zod10.z.enum(["amount"]).describe("The transfer amount, in the charge's `currency` units.");
596
- var TransactionsDateFieldSchema = import_zod10.z.enum(["detectedAt"]).describe("When Klappay detected this transfer on-chain (not when it was mined).");
597
- var TransactionsFilterSchema = import_zod10.z.object({
635
+ var TransactionsMetricFieldSchema = import_zod11.z.enum(["amount"]).describe("The transfer amount, in the charge's `currency` units.");
636
+ var TransactionsDateFieldSchema = import_zod11.z.enum(["detectedAt"]).describe("When Klappay detected this transfer on-chain (not when it was mined).");
637
+ var TransactionsFilterSchema = import_zod11.z.object({
598
638
  field: TransactionsQueryFieldSchema,
599
639
  operator: MetricsFilterOperatorSchema,
600
640
  value: MetricsFilterValueSchema
601
641
  });
602
- var TransactionsGroupBySchema = import_zod10.z.union([
603
- import_zod10.z.object({ type: import_zod10.z.literal("field"), field: TransactionsQueryFieldSchema }),
604
- import_zod10.z.object({
605
- type: import_zod10.z.literal("date_bucket"),
642
+ var TransactionsGroupBySchema = import_zod11.z.union([
643
+ import_zod11.z.object({ type: import_zod11.z.literal("field"), field: TransactionsQueryFieldSchema }),
644
+ import_zod11.z.object({
645
+ type: import_zod11.z.literal("date_bucket"),
606
646
  field: TransactionsDateFieldSchema,
607
647
  granularity: MetricsDateGranularitySchema
608
648
  })
609
649
  ]);
610
- var TransactionsMetricSchema = import_zod10.z.object({
650
+ var TransactionsMetricSchema = import_zod11.z.object({
611
651
  aggregation: MetricsAggregationSchema,
612
652
  field: TransactionsMetricFieldSchema.optional(),
613
653
  alias: metricAliasSchema
614
654
  });
615
- var TransactionsMetricsQuerySchema = import_zod10.z.object({
616
- resource: import_zod10.z.literal("transactions"),
655
+ var TransactionsMetricsQuerySchema = import_zod11.z.object({
656
+ resource: import_zod11.z.literal("transactions"),
617
657
  environment: metricsQueryEnvironmentSchema,
618
- dateRange: import_zod10.z.object({
658
+ dateRange: import_zod11.z.object({
619
659
  field: TransactionsDateFieldSchema,
620
- from: import_zod10.z.string().max(64).datetime(),
621
- to: import_zod10.z.string().max(64).datetime()
660
+ from: import_zod11.z.string().max(64).datetime(),
661
+ to: import_zod11.z.string().max(64).datetime()
622
662
  }),
623
- groupBy: import_zod10.z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
624
- metrics: import_zod10.z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
625
- filters: import_zod10.z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
663
+ groupBy: import_zod11.z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
664
+ metrics: import_zod11.z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
665
+ filters: import_zod11.z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
626
666
  orderBy: orderBySchema.optional(),
627
667
  limit: limitSchema
628
668
  });
629
- var DistributionsQueryFieldSchema = import_zod10.z.enum(["status", "network", "token", "distributorAddress"]).describe(
669
+ var DistributionsQueryFieldSchema = import_zod11.z.enum(["status", "network", "token", "distributorAddress"]).describe(
630
670
  "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."
631
671
  );
632
- var DistributionsMetricFieldSchema = import_zod10.z.enum(["attempts"]).describe(
672
+ var DistributionsMetricFieldSchema = import_zod11.z.enum(["attempts"]).describe(
633
673
  "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."
634
674
  );
635
- var DistributionsDateFieldSchema = import_zod10.z.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
675
+ var DistributionsDateFieldSchema = import_zod11.z.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
636
676
  "`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."
637
677
  );
638
- var DistributionsFilterSchema = import_zod10.z.object({
678
+ var DistributionsFilterSchema = import_zod11.z.object({
639
679
  field: DistributionsQueryFieldSchema,
640
680
  operator: MetricsFilterOperatorSchema,
641
681
  value: MetricsFilterValueSchema
642
682
  });
643
- var DistributionsGroupBySchema = import_zod10.z.union([
644
- import_zod10.z.object({ type: import_zod10.z.literal("field"), field: DistributionsQueryFieldSchema }),
645
- import_zod10.z.object({
646
- type: import_zod10.z.literal("date_bucket"),
683
+ var DistributionsGroupBySchema = import_zod11.z.union([
684
+ import_zod11.z.object({ type: import_zod11.z.literal("field"), field: DistributionsQueryFieldSchema }),
685
+ import_zod11.z.object({
686
+ type: import_zod11.z.literal("date_bucket"),
647
687
  field: DistributionsDateFieldSchema,
648
688
  granularity: MetricsDateGranularitySchema
649
689
  })
650
690
  ]);
651
- var DistributionsMetricSchema = import_zod10.z.object({
691
+ var DistributionsMetricSchema = import_zod11.z.object({
652
692
  aggregation: MetricsAggregationSchema,
653
693
  field: DistributionsMetricFieldSchema.optional(),
654
694
  alias: metricAliasSchema
655
695
  });
656
- var DistributionsMetricsQuerySchema = import_zod10.z.object({
657
- resource: import_zod10.z.literal("distributions"),
696
+ var DistributionsMetricsQuerySchema = import_zod11.z.object({
697
+ resource: import_zod11.z.literal("distributions"),
658
698
  environment: metricsQueryEnvironmentSchema,
659
- dateRange: import_zod10.z.object({
699
+ dateRange: import_zod11.z.object({
660
700
  field: DistributionsDateFieldSchema,
661
- from: import_zod10.z.string().max(64).datetime(),
662
- to: import_zod10.z.string().max(64).datetime()
701
+ from: import_zod11.z.string().max(64).datetime(),
702
+ to: import_zod11.z.string().max(64).datetime()
663
703
  }),
664
- groupBy: import_zod10.z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
665
- metrics: import_zod10.z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
666
- filters: import_zod10.z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
704
+ groupBy: import_zod11.z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
705
+ metrics: import_zod11.z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
706
+ filters: import_zod11.z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
667
707
  orderBy: orderBySchema.optional(),
668
708
  limit: limitSchema
669
709
  });
670
710
  var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
671
- var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
711
+ var MetricsQuerySchema = import_zod11.z.discriminatedUnion("resource", [
672
712
  ChargesMetricsQuerySchema,
673
713
  TransactionsMetricsQuerySchema,
674
714
  DistributionsMetricsQuerySchema
@@ -677,7 +717,7 @@ var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
677
717
  const to = new Date(input.dateRange.to);
678
718
  if (from >= to) {
679
719
  ctx.addIssue({
680
- code: import_zod10.z.ZodIssueCode.custom,
720
+ code: import_zod11.z.ZodIssueCode.custom,
681
721
  message: "`dateRange.from` must be before `dateRange.to`.",
682
722
  path: ["dateRange", "from"]
683
723
  });
@@ -685,7 +725,7 @@ var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
685
725
  const spanDays = (to.getTime() - from.getTime()) / ONE_DAY_MS;
686
726
  if (spanDays > MAX_METRICS_QUERY_DATE_RANGE_DAYS) {
687
727
  ctx.addIssue({
688
- code: import_zod10.z.ZodIssueCode.custom,
728
+ code: import_zod11.z.ZodIssueCode.custom,
689
729
  message: `\`dateRange\` cannot span more than ${MAX_METRICS_QUERY_DATE_RANGE_DAYS} days.`,
690
730
  path: ["dateRange", "to"]
691
731
  });
@@ -693,7 +733,7 @@ var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
693
733
  const dateBucketCount = input.groupBy.filter((entry) => entry.type === "date_bucket").length;
694
734
  if (dateBucketCount > 1) {
695
735
  ctx.addIssue({
696
- code: import_zod10.z.ZodIssueCode.custom,
736
+ code: import_zod11.z.ZodIssueCode.custom,
697
737
  message: "At most one `date_bucket` entry is allowed in `groupBy`.",
698
738
  path: ["groupBy"]
699
739
  });
@@ -701,7 +741,7 @@ var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
701
741
  input.metrics.forEach((metric, index) => {
702
742
  if (metric.aggregation !== "count" && metric.field === void 0) {
703
743
  ctx.addIssue({
704
- code: import_zod10.z.ZodIssueCode.custom,
744
+ code: import_zod11.z.ZodIssueCode.custom,
705
745
  message: "`field` is required unless `aggregation` is `count`.",
706
746
  path: ["metrics", index, "field"]
707
747
  });
@@ -710,7 +750,7 @@ var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
710
750
  const aliases = input.metrics.map((metric) => metric.alias).filter((alias) => alias !== void 0);
711
751
  if (new Set(aliases).size !== aliases.length) {
712
752
  ctx.addIssue({
713
- code: import_zod10.z.ZodIssueCode.custom,
753
+ code: import_zod11.z.ZodIssueCode.custom,
714
754
  message: "Every `metrics[].alias` must be unique.",
715
755
  path: ["metrics"]
716
756
  });
@@ -719,32 +759,32 @@ var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
719
759
  input.metrics.forEach((metric, index) => {
720
760
  if (metric.alias !== void 0 && reservedNames.has(metric.alias)) {
721
761
  ctx.addIssue({
722
- code: import_zod10.z.ZodIssueCode.custom,
762
+ code: import_zod11.z.ZodIssueCode.custom,
723
763
  message: `\`alias\` "${metric.alias}" collides with a \`groupBy\` field name (or the reserved word "bucket") \u2014 choose a different alias.`,
724
764
  path: ["metrics", index, "alias"]
725
765
  });
726
766
  }
727
767
  });
728
768
  });
729
- var MetricsQueryResultRowSchema = import_zod10.z.record(
730
- import_zod10.z.string(),
731
- import_zod10.z.union([import_zod10.z.string(), import_zod10.z.number(), import_zod10.z.boolean(), import_zod10.z.null()])
769
+ var MetricsQueryResultRowSchema = import_zod11.z.record(
770
+ import_zod11.z.string(),
771
+ import_zod11.z.union([import_zod11.z.string(), import_zod11.z.number(), import_zod11.z.boolean(), import_zod11.z.null()])
732
772
  );
733
- var MetricsQueryResultSchema = import_zod10.z.object({
734
- data: import_zod10.z.array(MetricsQueryResultRowSchema),
735
- meta: import_zod10.z.object({
773
+ var MetricsQueryResultSchema = import_zod11.z.object({
774
+ data: import_zod11.z.array(MetricsQueryResultRowSchema),
775
+ meta: import_zod11.z.object({
736
776
  resource: MetricsResourceSchema,
737
777
  environment: EnvironmentSchema,
738
- rowCount: import_zod10.z.number().int().describe("Number of rows in `data`."),
739
- truncated: import_zod10.z.boolean().describe(
778
+ rowCount: import_zod11.z.number().int().describe("Number of rows in `data`."),
779
+ truncated: import_zod11.z.boolean().describe(
740
780
  "`true` if more rows matched than `limit` allowed \u2014 `data` holds only the first `limit`."
741
781
  )
742
782
  })
743
783
  });
744
784
 
745
785
  // src/webhook-events.ts
746
- var import_zod11 = require("zod");
747
- var ChargeWebhookEventTypeSchema = import_zod11.z.enum([
786
+ var import_zod12 = require("zod");
787
+ var ChargeWebhookEventTypeSchema = import_zod12.z.enum([
748
788
  "charge.created",
749
789
  "charge.partially_paid",
750
790
  "charge.confirmed",
@@ -756,14 +796,14 @@ var ChargeWebhookEventTypeSchema = import_zod11.z.enum([
756
796
  ]).describe(
757
797
  '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`). Every event in this category carries the full `Charge` object as `data`.'
758
798
  );
759
- var WebhookDeliveryEventTypeSchema = import_zod11.z.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
799
+ var WebhookDeliveryEventTypeSchema = import_zod12.z.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
760
800
  "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`)."
761
801
  );
762
- var WebhookEventTypeSchema = import_zod11.z.union([
802
+ var WebhookEventTypeSchema = import_zod12.z.union([
763
803
  ChargeWebhookEventTypeSchema,
764
804
  WebhookDeliveryEventTypeSchema
765
805
  ]);
766
- var WebhookCategorySchema = import_zod11.z.enum(["payments", "webhooks"]).describe(
806
+ var WebhookCategorySchema = import_zod12.z.enum(["payments", "webhooks"]).describe(
767
807
  "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."
768
808
  );
769
809
  function buildCategoryMap() {
@@ -791,101 +831,101 @@ var TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([
791
831
  );
792
832
 
793
833
  // src/webhooks.ts
794
- var import_zod12 = require("zod");
834
+ var import_zod13 = require("zod");
795
835
  var WEBHOOK_EVENTS_WILDCARD = "*";
796
- var CreateWebhookSchema = import_zod12.z.object({
797
- url: import_zod12.z.string().max(2048).url().describe(
836
+ var CreateWebhookSchema = import_zod13.z.object({
837
+ url: import_zod13.z.string().max(2048).url().describe(
798
838
  "Must be HTTPS and resolve to a public address \u2014 private/internal IPs are rejected."
799
839
  ),
800
- events: import_zod12.z.array(import_zod12.z.union([WebhookEventTypeSchema, import_zod12.z.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
840
+ events: import_zod13.z.array(import_zod13.z.union([WebhookEventTypeSchema, import_zod13.z.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
801
841
  '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.'
802
842
  ),
803
- eventCategories: import_zod12.z.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
843
+ eventCategories: import_zod13.z.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
804
844
  "Subscribe to every event in these categories. At least one of `events` or `eventCategories` is required."
805
845
  ),
806
- excludeEvents: import_zod12.z.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
846
+ excludeEvents: import_zod13.z.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
807
847
  'Event types to exclude even if selected via `events: ["*"]` or `eventCategories`.'
808
848
  )
809
849
  }).refine((v) => v.events.length > 0 || v.eventCategories.length > 0, {
810
850
  message: "must select at least one event via `events` or `eventCategories`",
811
851
  path: ["events"]
812
852
  });
813
- var WebhookSchema = import_zod12.z.object({
814
- id: import_zod12.z.string(),
853
+ var WebhookSchema = import_zod13.z.object({
854
+ id: import_zod13.z.string(),
815
855
  environment: EnvironmentSchema.nullable().describe(
816
856
  "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)."
817
857
  ),
818
- url: import_zod12.z.string(),
819
- events: import_zod12.z.array(WebhookEventTypeSchema),
820
- eventCategories: import_zod12.z.array(WebhookCategorySchema),
821
- excludeEvents: import_zod12.z.array(WebhookEventTypeSchema),
822
- isWildcard: import_zod12.z.boolean(),
823
- secret: import_zod12.z.string().describe(
858
+ url: import_zod13.z.string(),
859
+ events: import_zod13.z.array(WebhookEventTypeSchema),
860
+ eventCategories: import_zod13.z.array(WebhookCategorySchema),
861
+ excludeEvents: import_zod13.z.array(WebhookEventTypeSchema),
862
+ isWildcard: import_zod13.z.boolean(),
863
+ secret: import_zod13.z.string().describe(
824
864
  "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."
825
865
  ),
826
- createdAt: import_zod12.z.string().datetime()
866
+ createdAt: import_zod13.z.string().datetime()
827
867
  });
828
868
  var WebhookListItemSchema = WebhookSchema.omit({ secret: true }).extend({
829
- hint: import_zod12.z.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
869
+ hint: import_zod13.z.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
830
870
  });
831
- var WebhookPayloadSchema = import_zod12.z.object({
832
- id: import_zod12.z.string().describe(
871
+ var WebhookPayloadSchema = import_zod13.z.object({
872
+ id: import_zod13.z.string().describe(
833
873
  "Unique id for this specific delivery \u2014 also sent as the `X-Klappay-Delivery` header."
834
874
  ),
835
875
  event: WebhookEventTypeSchema,
836
- createdAt: import_zod12.z.string().datetime(),
837
- data: import_zod12.z.unknown().describe(
876
+ createdAt: import_zod13.z.string().datetime(),
877
+ data: import_zod13.z.unknown().describe(
838
878
  "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."
839
879
  )
840
880
  });
841
- var WebhookDeliveryStatusSchema = import_zod12.z.enum(["pending", "delivered", "failed"]);
842
- var WebhookDeliverySchema = import_zod12.z.object({
843
- id: import_zod12.z.string(),
844
- webhookId: import_zod12.z.string(),
881
+ var WebhookDeliveryStatusSchema = import_zod13.z.enum(["pending", "delivered", "failed"]);
882
+ var WebhookDeliverySchema = import_zod13.z.object({
883
+ id: import_zod13.z.string(),
884
+ webhookId: import_zod13.z.string(),
845
885
  event: WebhookEventTypeSchema,
846
886
  status: WebhookDeliveryStatusSchema.describe(
847
887
  "`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."
848
888
  ),
849
- attempts: import_zod12.z.number(),
850
- responseCode: import_zod12.z.number().nullable().describe(
889
+ attempts: import_zod13.z.number(),
890
+ responseCode: import_zod13.z.number().nullable().describe(
851
891
  "HTTP status your endpoint returned on the most recent attempt. `null` if every attempt failed to connect at all."
852
892
  ),
853
- nextRetryAt: import_zod12.z.string().datetime().nullable(),
854
- deliveredAt: import_zod12.z.string().datetime().nullable(),
855
- createdAt: import_zod12.z.string().datetime()
893
+ nextRetryAt: import_zod13.z.string().datetime().nullable(),
894
+ deliveredAt: import_zod13.z.string().datetime().nullable(),
895
+ createdAt: import_zod13.z.string().datetime()
856
896
  });
857
897
  var ListWebhookDeliveriesSchema = PaginationQuerySchema;
858
898
  var PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema);
859
899
 
860
900
  // src/recipients.ts
861
- var import_zod13 = require("zod");
901
+ var import_zod14 = require("zod");
862
902
  var EVM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
863
- var CreateRecipientSchema = import_zod13.z.object({
864
- address: import_zod13.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."),
865
- label: import_zod13.z.string().min(1).max(64).optional().describe('Free-form label for your own bookkeeping (e.g. `"supplier"`) \u2014 never interpreted.')
903
+ var CreateRecipientSchema = import_zod14.z.object({
904
+ address: import_zod14.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."),
905
+ label: import_zod14.z.string().min(1).max(64).optional().describe('Free-form label for your own bookkeeping (e.g. `"supplier"`) \u2014 never interpreted.')
866
906
  });
867
- var RecipientSchema = import_zod13.z.object({
868
- id: import_zod13.z.string().describe(
907
+ var RecipientSchema = import_zod14.z.object({
908
+ id: import_zod14.z.string().describe(
869
909
  "Klappay-generated id, e.g. `rc_...` \u2014 this, not the raw address, is what a charge's `splitRecipients[].recipientId` references."
870
910
  ),
871
911
  environment: EnvironmentSchema,
872
- address: import_zod13.z.string(),
873
- label: import_zod13.z.string().nullable(),
874
- payout: import_zod13.z.boolean().describe(
912
+ address: import_zod14.z.string(),
913
+ label: import_zod14.z.string().nullable(),
914
+ payout: import_zod14.z.boolean().describe(
875
915
  "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`."
876
916
  ),
877
- createdAt: import_zod13.z.string().datetime()
917
+ createdAt: import_zod14.z.string().datetime()
878
918
  });
879
- var SetRecipientPayoutSchema = import_zod13.z.object({
880
- payout: import_zod13.z.boolean().describe("New payout-eligibility value for this recipient.")
919
+ var SetRecipientPayoutSchema = import_zod14.z.object({
920
+ payout: import_zod14.z.boolean().describe("New payout-eligibility value for this recipient.")
881
921
  });
882
922
 
883
923
  // src/timeline.ts
884
- var import_zod14 = require("zod");
885
- var TransactionSourceSchema = import_zod14.z.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
924
+ var import_zod15 = require("zod");
925
+ var TransactionSourceSchema = import_zod15.z.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
886
926
  "How this transfer was detected: `moralis_webhook` (the normal path), `reconciliation_job` (a fallback poller caught it after the webhook was missed or delayed), or `sandbox` (simulated via `POST /v1/sandbox/charges/{id}/trigger`, no real on-chain transfer)."
887
927
  );
888
- var TimelineEventTypeSchema = import_zod14.z.enum([
928
+ var TimelineEventTypeSchema = import_zod15.z.enum([
889
929
  "charge.created",
890
930
  "charge.expired",
891
931
  "transaction.detected",
@@ -896,11 +936,11 @@ var TimelineEventTypeSchema = import_zod14.z.enum([
896
936
  ]).describe(
897
937
  "`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)."
898
938
  );
899
- var TimelineEventSchema = import_zod14.z.object({
939
+ var TimelineEventSchema = import_zod15.z.object({
900
940
  type: TimelineEventTypeSchema,
901
- at: import_zod14.z.string().datetime(),
902
- txHash: import_zod14.z.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
903
- amount: import_zod14.z.number().optional().describe(
941
+ at: import_zod15.z.string().datetime(),
942
+ txHash: import_zod15.z.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
943
+ amount: import_zod15.z.number().optional().describe(
904
944
  "Present for `transaction.detected` events only \u2014 the amount that specific transfer carried."
905
945
  ),
906
946
  source: TransactionSourceSchema.optional().describe(
@@ -912,56 +952,112 @@ var TimelineEventSchema = import_zod14.z.object({
912
952
  network: NetworkSchema.optional().describe(
913
953
  "Present for `transaction.detected` and `split.distributed` events \u2014 which network this specific transfer, or settlement, used."
914
954
  ),
915
- causedTransition: import_zod14.z.boolean().optional().describe(
955
+ causedTransition: import_zod15.z.boolean().optional().describe(
916
956
  "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."
917
957
  ),
918
958
  event: WebhookEventTypeSchema.optional().describe(
919
959
  "Present for `webhook.*` events only \u2014 which event type this delivery was for."
920
960
  ),
921
- responseCode: import_zod14.z.number().nullable().optional().describe(
961
+ responseCode: import_zod15.z.number().nullable().optional().describe(
922
962
  "Present for `webhook.*` events only \u2014 HTTP status your endpoint returned, or `null` if the request never connected."
923
963
  ),
924
- attempts: import_zod14.z.number().optional().describe(
964
+ attempts: import_zod15.z.number().optional().describe(
925
965
  "Present for `webhook.*` events only \u2014 how many delivery attempts have been made so far."
926
966
  )
927
967
  });
928
968
 
929
969
  // src/health.ts
930
- var import_zod15 = require("zod");
931
- var HealthSchema = import_zod15.z.object({
932
- status: import_zod15.z.enum(["ok", "error"]).describe(
970
+ var import_zod16 = require("zod");
971
+ var HealthSchema = import_zod16.z.object({
972
+ status: import_zod16.z.enum(["ok", "error"]).describe(
933
973
  "`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."
934
974
  ),
935
- version: import_zod15.z.string(),
936
- timestamp: import_zod15.z.string().datetime(),
937
- db: import_zod15.z.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
938
- pendingWebhooks: import_zod15.z.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
939
- oldestPendingChargeAgeSeconds: import_zod15.z.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
940
- lastMoralisEventAgeSeconds: import_zod15.z.number().nullable().describe(
975
+ version: import_zod16.z.string(),
976
+ timestamp: import_zod16.z.string().datetime(),
977
+ db: import_zod16.z.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
978
+ pendingWebhooks: import_zod16.z.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
979
+ oldestPendingChargeAgeSeconds: import_zod16.z.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
980
+ lastMoralisEventAgeSeconds: import_zod16.z.number().nullable().describe(
941
981
  "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."
942
982
  )
943
983
  });
944
984
 
945
985
  // src/sandbox.ts
946
- var import_zod16 = require("zod");
947
- var SandboxTriggerSchema = import_zod16.z.object({
986
+ var import_zod17 = require("zod");
987
+ var SandboxTriggerSchema = import_zod17.z.object({
948
988
  event: TriggerableChargeEventSchema,
949
- amount: import_zod16.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
989
+ amount: import_zod17.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
950
990
  "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."
951
991
  )
952
992
  });
953
993
 
954
994
  // src/capabilities.ts
955
- var import_zod17 = require("zod");
956
- var CapabilitiesSchema = import_zod17.z.object({
957
- acceptedPayments: import_zod17.z.array(AcceptedPaymentSchema).describe(
995
+ var import_zod18 = require("zod");
996
+ var CapabilitiesSchema = import_zod18.z.object({
997
+ acceptedPayments: import_zod18.z.array(AcceptedPaymentSchema).describe(
958
998
  "Every `(token, network)` pair actually configured for your environment right now \u2014 read straight from the same lookup `POST /v1/charges` validates `acceptedPayments` against, so it can never list a pair that charge creation would then reject. Use this to build a picker UI instead of hardcoding the matrix client-side."
959
999
  )
960
1000
  });
1001
+
1002
+ // src/swap.ts
1003
+ var import_zod19 = require("zod");
1004
+ var CreateSwapQuoteSchema = import_zod19.z.object({
1005
+ inputToken: AltTokenSchema.describe(
1006
+ "Which alt-cryptocurrency the payer wants to send \u2014 must be one of this charge's `swapAlternatives`, or `422 token_not_supported`."
1007
+ ),
1008
+ inputNetwork: NetworkSchema.describe(
1009
+ "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 breaks the tie using its own trust ranking for that network (e.g. USDT over USDC on BNB Chain, where \"USDC\" is a third-party Binance-Peg token, not Circle's) \u2014 never a token the charge doesn't actually accept."
1010
+ ),
1011
+ takerAddress: import_zod19.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").describe(
1012
+ "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."
1013
+ )
1014
+ });
1015
+ var SwapQuoteSchema = import_zod19.z.object({
1016
+ inputToken: AltTokenSchema,
1017
+ inputNetwork: NetworkSchema,
1018
+ inputAmount: import_zod19.z.number().describe(
1019
+ "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."
1020
+ ),
1021
+ outputToken: TokenSchema.describe(
1022
+ "Which of this charge's `acceptedPayments` tokens the swap resolves to."
1023
+ ),
1024
+ outputNetwork: NetworkSchema,
1025
+ outputAmount: import_zod19.z.number().describe(
1026
+ "The exact remaining amount owed on this charge (`amount - amountReceived`), in `currency` units \u2014 always what the merchant's split address receives, regardless of `inputAmount`."
1027
+ ),
1028
+ fees: import_zod19.z.object({
1029
+ klappayFee: import_zod19.z.number().describe(
1030
+ "Klappay's own swap fee (1% today), in `outputToken` units \u2014 paid by the payer, on top of `inputAmount`, separate from the merchant's own `feePercent`. Never subtracted from `outputAmount`."
1031
+ ),
1032
+ zeroExFee: import_zod19.z.number().nullable().describe(
1033
+ "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. Also paid by the payer on top of `inputAmount`, also never subtracted from `outputAmount` \u2014 Klappay never sees this fee, it goes straight to 0x."
1034
+ )
1035
+ }).describe(
1036
+ "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`."
1037
+ ),
1038
+ expiresAt: import_zod19.z.string().datetime().describe(
1039
+ "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."
1040
+ ),
1041
+ transaction: import_zod19.z.object({
1042
+ to: import_zod19.z.string().describe("Contract address the payer's wallet must send this transaction to."),
1043
+ data: import_zod19.z.string().describe("Calldata \u2014 opaque, must be sent unmodified."),
1044
+ value: import_zod19.z.string().describe(
1045
+ "Native currency (ETH/BNB/MATIC/AVAX) to attach, in wei \u2014 `\"0\"` when `inputToken` isn't this network's native currency."
1046
+ )
1047
+ }).describe(
1048
+ "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."
1049
+ ),
1050
+ permit2: import_zod19.z.object({ eip712: import_zod19.z.record(import_zod19.z.unknown()) }).optional().describe(
1051
+ "Present only when `inputToken` is an ERC-20 (today, only `BTC`) \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. Absent when `inputToken` is a network's own native currency (ETH/BNB/MATIC/AVAX) \u2014 `transaction` is then ready to sign and send directly, no extra step."
1052
+ )
1053
+ });
961
1054
  // Annotate the CommonJS export names for ESM import in node:
962
1055
  0 && (module.exports = {
1056
+ ALT_TOKEN_ADDRESSES,
1057
+ ALT_TOKEN_DECIMALS,
963
1058
  API_KEY_SCOPES,
964
1059
  AcceptedPaymentSchema,
1060
+ AltTokenSchema,
965
1061
  ApiKeyScopeSchema,
966
1062
  CHARGE_ACCEPTED_PAYMENTS_MAX,
967
1063
  CHARGE_AMOUNT_MAX,
@@ -980,6 +1076,7 @@ var CapabilitiesSchema = import_zod17.z.object({
980
1076
  CheckoutProductSchema,
981
1077
  CreateChargeSchema,
982
1078
  CreateRecipientSchema,
1079
+ CreateSwapQuoteSchema,
983
1080
  CreateWebhookSchema,
984
1081
  DistributionsDateFieldSchema,
985
1082
  DistributionsMetricFieldSchema,
@@ -1029,6 +1126,7 @@ var CapabilitiesSchema = import_zod17.z.object({
1029
1126
  SplitDistributionStatusSchema,
1030
1127
  SplitRecipientInputSchema,
1031
1128
  SplitRecipientSchema,
1129
+ SwapQuoteSchema,
1032
1130
  TOKEN_ADDRESSES,
1033
1131
  TOKEN_DECIMALS,
1034
1132
  TimelineEventSchema,
@@ -1050,6 +1148,7 @@ var CapabilitiesSchema = import_zod17.z.object({
1050
1148
  WebhookPayloadSchema,
1051
1149
  WebhookSchema,
1052
1150
  findConflictingScopes,
1151
+ listAltTokensForNetworks,
1053
1152
  paginatedSchema
1054
1153
  });
1055
1154
  //# sourceMappingURL=index.js.map