@klappay/types 3.7.0 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/environment.ts","../src/api-key-scopes.ts","../src/networks.ts","../src/networks.constants.ts","../src/pagination.ts","../src/tokens.ts","../src/tokens.constants.ts","../src/alt-tokens.ts","../src/alt-tokens.constants.ts","../src/charges.ts","../src/checkout-metadata.ts","../src/escrow.ts","../src/charge-check.ts","../src/distributions.ts","../src/metrics.ts","../src/webhook-events.ts","../src/webhooks.ts","../src/recipients.ts","../src/timeline.ts","../src/health.ts","../src/sandbox.ts","../src/capabilities.ts","../src/swap.ts"],"sourcesContent":["export * from './errors'\nexport * from './environment'\nexport * from './api-key-scopes'\nexport * from './networks'\nexport * from './pagination'\nexport * from './tokens'\nexport * from './alt-tokens'\nexport * from './charges'\nexport * from './charge-check'\nexport * from './escrow'\nexport * from './checkout-metadata'\nexport * from './distributions'\nexport * from './metrics'\nexport * from './webhook-events'\nexport * from './webhook-event-data'\nexport * from './webhooks'\nexport * from './recipients'\nexport * from './timeline'\nexport * from './health'\nexport * from './sandbox'\nexport * from './capabilities'\nexport * from './swap'\n","import { z } from 'zod'\n\nexport const ErrorPayloadSchema = z.object({\n error: z.object({\n code: z\n .string()\n .describe(\n 'A stable, machine-readable error identifier (e.g. `validation_error`, `charge_not_found`).',\n ),\n message: z\n .string()\n .describe(\n 'Human-readable explanation, safe to log or show a developer — not meant for end users.',\n ),\n param: z\n .string()\n .optional()\n .describe('Which request field the error refers to, when applicable.'),\n }),\n})\n\nexport type ErrorPayload = z.infer<typeof ErrorPayloadSchema>\n","import { z } from 'zod'\n\nexport const EnvironmentSchema = z\n .enum(['live', 'test'])\n .describe(\n '`live` or `test`, matching the `klap_live_.../klap_test_...` prefix of the API key that created or is scoped to this resource. `live` settles on Base mainnet with real funds; `test` settles on Base Sepolia, a separate testnet — real on-chain activity, but never real money.',\n )\nexport type Environment = z.infer<typeof EnvironmentSchema>\n","import { z } from 'zod'\n\nexport const ApiKeyScopeSchema = z\n .enum([\n 'charges:read',\n 'charges:write',\n 'webhooks:read',\n 'webhooks:write',\n 'webhooks:manage_secret',\n 'metrics:read',\n 'metrics:charges:read',\n 'metrics:transactions:read',\n 'metrics:distributions:read',\n 'sandbox:trigger',\n 'charges:split_write',\n 'recipients:read',\n 'recipients:write',\n 'recipients:manage_payout',\n ])\n .describe(\n \"What an API key is allowed to do, independent of `tenantId`/`environment` (which scope *whose* data, not *what actions*). A key with none of these can still authenticate but every scoped route rejects it with `403 insufficient_scope`. `metrics:read` alone grants every metrics resource; `metrics:{resource}:read` grants only that one — a key can hold either or both. `charges:split_write` is required on top of `charges:write` whenever a charge request includes `splitRecipients` — a key without it can create ordinary charges but never redirect part of the payout. `recipients:write` registers/revokes recipients (addresses eligible to be *referenced* in a split); `recipients:manage_payout` is separate and strictly more sensitive — it is what lets a recipient actually become an API key's `payoutAddress`, and should be granted only to a key that already went through out-of-band approval for that (Dashboard's own internal key, never a merchant-facing or third-party integration key like a marketplace's). `charges:split_write` can never be combined with `recipients:write`/`recipients:manage_payout` on the same key (see `CONFLICTING_SCOPE_PAIRS`) — Core rejects such a key outright, before any route runs.\",\n )\nexport type ApiKeyScope = z.infer<typeof ApiKeyScopeSchema>\nexport const API_KEY_SCOPES = ApiKeyScopeSchema.options\n\nexport const CONFLICTING_SCOPE_PAIRS: ReadonlyArray<readonly [ApiKeyScope, ApiKeyScope]> = [\n ['charges:split_write', 'recipients:write'],\n ['charges:split_write', 'recipients:manage_payout'],\n]\n\nexport function findConflictingScopes(\n scopes: readonly ApiKeyScope[],\n): readonly [ApiKeyScope, ApiKeyScope] | null {\n const held = new Set(scopes)\n for (const [a, b] of CONFLICTING_SCOPE_PAIRS) {\n if (held.has(a) && held.has(b)) return [a, b]\n }\n return null\n}\n","import { z } from 'zod'\n\nexport const NetworkSchema = z\n .enum(['base', 'optimism', 'polygon', 'ethereum', 'arbitrum', 'avalanche', 'bnb'])\n .describe('The blockchain a charge/payment is on.')\n\nexport type Network = z.infer<typeof NetworkSchema>\n\nexport * from './networks.constants'\n","import type { Environment } from './environment'\nimport type { Network } from './networks'\n\nexport const NETWORK_LABELS: Record<Network, string> = {\n base: 'Base',\n optimism: 'Optimism',\n polygon: 'Polygon',\n ethereum: 'Ethereum',\n arbitrum: 'Arbitrum',\n avalanche: 'Avalanche',\n bnb: 'BNB Chain',\n}\n\nexport const NETWORK_EXPLORERS: Record<Network, string> = {\n base: 'https://basescan.org',\n optimism: 'https://optimistic.etherscan.io',\n polygon: 'https://polygonscan.com',\n ethereum: 'https://etherscan.io',\n arbitrum: 'https://arbiscan.io',\n avalanche: 'https://snowtrace.io',\n bnb: 'https://bscscan.com',\n}\n\nexport const EVM_NETWORKS = [\n 'base',\n 'optimism',\n 'polygon',\n 'ethereum',\n 'arbitrum',\n 'avalanche',\n 'bnb',\n] as const\nexport type EvmNetwork = (typeof EVM_NETWORKS)[number]\n\nexport const OPERATIONAL_NETWORKS = [\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'ethereum',\n 'avalanche',\n 'bnb',\n] as const\nexport type OperationalNetwork = (typeof OPERATIONAL_NETWORKS)[number]\n\nexport const CHAIN_IDS: Record<EvmNetwork, Partial<Record<Environment, number>>> = {\n base: { live: 8453, test: 84532 },\n optimism: { live: 10, test: 11155420 },\n ethereum: { live: 1, test: 11155111 },\n polygon: { live: 137 },\n arbitrum: { live: 42161 },\n avalanche: { live: 43114 },\n bnb: { live: 56 },\n}\n","import { z } from 'zod'\n\nexport const PAGINATION_LIMIT_MIN = 1\nexport const PAGINATION_LIMIT_MAX = 100\nexport const PAGINATION_LIMIT_DEFAULT = 20\n\nexport const PaginationQuerySchema = z.object({\n limit: z.coerce\n .number()\n .min(PAGINATION_LIMIT_MIN)\n .max(PAGINATION_LIMIT_MAX)\n .default(PAGINATION_LIMIT_DEFAULT)\n .describe(\n `Max items to return per page (${PAGINATION_LIMIT_MIN}–${PAGINATION_LIMIT_MAX}, default ${PAGINATION_LIMIT_DEFAULT}).`,\n ),\n cursor: z\n .string()\n .max(500)\n .optional()\n .describe(\n \"Opaque — 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.\",\n ),\n})\n\nexport type PaginationQuery = z.infer<typeof PaginationQuerySchema>\n\nexport type PaginationQueryRequest = z.input<typeof PaginationQuerySchema>\n\nexport function paginatedSchema<T extends z.ZodTypeAny>(itemSchema: T) {\n return z.object({\n data: z.array(itemSchema),\n nextCursor: z\n .string()\n .nullable()\n .describe('Pass as `cursor` to fetch the next page. `null` when there are no more results.'),\n hasMore: z.boolean(),\n })\n}\n","import { z } from 'zod'\nimport { OPERATIONAL_NETWORKS } from './networks'\n\nexport const TokenSchema = z\n .enum(['USDC', 'USDT'])\n .describe(\n `Which stablecoin the payer will send. Support depends on both \\`network\\` and \\`environment\\` — not every token/network/environment combination is deployed; today, both \\`USDC\\` and \\`USDT\\` are deployed on every operational network's \\`live\\` side except BNB Chain (\\`${OPERATIONAL_NETWORKS.join(', ')}\\`), but \\`test\\` coverage varies per network — Base, Optimism, and Ethereum each have a \\`test\\` environment (\\`USDC\\` only; none has an official Sepolia USDT), Arbitrum, Polygon, Avalanche, and BNB Chain have none yet (0xSplits hasn't deployed on Arbitrum Sepolia and has no Polygon, Avalanche Fuji, or BNB testnet support at all). An unconfigured combination is rejected with \\`422 token_not_supported\\`, not silently accepted. **BNB Chain's \\`USDC\\` address is Binance-Peg USDC, not an official Circle deployment** — Circle does not issue native USDC on BNB Chain at all; this is a Binance-custodied, 1:1-pegged BEP-20 token, a materially different trust model than every other \\`TOKEN_ADDRESSES\\` entry (all verified directly against their real issuer). Accepted at the payer's own risk — Klappay does not verify or guarantee Binance's collateral backing it. \\`USDT\\` on BNB Chain is Tether's own official issuance, same trust model as everywhere else. More tokens/networks are expected to be added over time — check \\`TOKEN_ADDRESSES\\` in \\`@klappay/types\\` (or a future \\`GET /v1/networks\\` capabilities endpoint) for the exact current matrix rather than assuming full coverage.`,\n )\nexport type Token = z.infer<typeof TokenSchema>\n\nexport * from './tokens.constants'\n","import type { Environment } from './environment'\nimport type { Network } from './networks'\nimport type { Token } from './tokens'\n\nexport const TOKEN_DECIMALS = 6\n\nexport const TOKEN_ADDRESSES: Record<\n Token,\n Partial<Record<Network, Partial<Record<Environment, `0x${string}`>>>>\n> = {\n USDC: {\n base: {\n live: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n test: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n },\n optimism: {\n live: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n test: '0x5fd84259d66Cd46123540766Be93DFE6D43130D7',\n },\n polygon: { live: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359' },\n ethereum: {\n live: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n test: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',\n },\n arbitrum: { live: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831' },\n avalanche: { live: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E' },\n bnb: { live: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d' },\n },\n USDT: {\n base: { live: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2' },\n optimism: { live: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58' },\n polygon: { live: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F' },\n ethereum: { live: '0xdAC17F958D2ee523a2206206994597C13D831ec7' },\n arbitrum: { live: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9' },\n avalanche: { live: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7' },\n bnb: { live: '0x55d398326f99059fF775485246999027B3197955' },\n },\n}\n","import { z } from 'zod'\nimport { ALT_TOKEN_ADDRESSES } from './alt-tokens.constants'\nimport { NetworkSchema } from './networks'\nimport type { Network } from './networks'\n\nexport * from './alt-tokens.constants'\n\nexport const AltTokenSchema = z\n .enum(['ETH', 'BNB', 'MATIC', 'AVAX', 'BTC'])\n .describe(\n \"A non-stablecoin cryptocurrency Klappay trusts as swap input for a charge, via the 0x Swap API — 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`) — never assume every value here is available on every network.\",\n )\nexport type AltToken = z.infer<typeof AltTokenSchema>\n\nexport const SwapAlternativeSchema = z.object({\n token: AltTokenSchema,\n network: NetworkSchema.describe(\n 'Which network to send `token` on — 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.',\n ),\n})\nexport type SwapAlternative = z.infer<typeof SwapAlternativeSchema>\n\nexport function listSwapAlternatives(networks: readonly Network[]): SwapAlternative[] {\n const alternatives: SwapAlternative[] = []\n for (const network of new Set(networks)) {\n for (const token of Object.keys(ALT_TOKEN_ADDRESSES[network] ?? {})) {\n alternatives.push({ token: token as AltToken, network })\n }\n }\n return alternatives\n}\n","import type { AltToken } from './alt-tokens'\nimport type { Network } from './networks'\n\nexport const ALT_TOKEN_DECIMALS: Record<AltToken, number> = {\n ETH: 18,\n BNB: 18,\n MATIC: 18,\n AVAX: 18,\n BTC: 8,\n}\n\nexport const ALT_TOKEN_ADDRESSES: Record<\n Network,\n Partial<Record<AltToken, 'native' | `0x${string}`>>\n> = {\n base: { ETH: 'native', BTC: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf' },\n optimism: { ETH: 'native', BTC: '0x68f180fcCe6836688e9084f035309E29Bf0A2095' },\n ethereum: { ETH: 'native', BTC: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599' },\n arbitrum: { ETH: 'native', BTC: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f' },\n polygon: { MATIC: 'native', BTC: '0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6' },\n avalanche: { AVAX: 'native' },\n bnb: { BNB: 'native' },\n}\n","import { z } from 'zod'\nimport { SwapAlternativeSchema } from './alt-tokens'\nimport { MetadataWithKlappaySchema } from './checkout-metadata'\nimport { EnvironmentSchema } from './environment'\nimport { EscrowConfigSchema } from './escrow'\nimport { NetworkSchema, OPERATIONAL_NETWORKS } from './networks'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\nimport { TokenSchema } from './tokens'\n\nexport const ChargeStatusSchema = z\n .enum(['pending', 'partially_paid', 'confirmed', 'expired', 'underpaid'])\n .describe(\n '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 — see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. Every status is reached automatically, on its own timeline — there is no merchant-initiated cancellation. This never reflects whether funds actually reached the merchant — see `settlementStatus` for that.',\n )\n\nexport type ChargeStatus = z.infer<typeof ChargeStatusSchema>\n\nexport const SettlementStatusSchema = z\n .enum(['pending', 'completed', 'failed'])\n .describe(\n \"Progress of the payout to the merchant's wallet, a separate step from `status` — `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 — nothing has been received, or the charge is still in progress.\",\n )\nexport type SettlementStatus = z.infer<typeof SettlementStatusSchema>\n\nexport const CHARGE_EXPIRES_IN_MIN_SECONDS = 60\nexport const CHARGE_EXPIRES_IN_MAX_SECONDS = 3600\n\nexport const CHARGE_ACCEPTED_PAYMENTS_MAX = 14\n\nexport const AcceptedPaymentSchema = z.object({\n token: TokenSchema,\n network: NetworkSchema,\n})\nexport type AcceptedPayment = z.infer<typeof AcceptedPaymentSchema>\n\nconst AcceptedPaymentsSchema = z\n .array(AcceptedPaymentSchema)\n .min(1, 'At least one accepted payment is required.')\n .max(CHARGE_ACCEPTED_PAYMENTS_MAX)\n .superRefine((pairs, ctx) => {\n const seen = new Set<string>()\n pairs.forEach((pair, index) => {\n const key = `${pair.token}:${pair.network}`\n if (seen.has(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,\n path: [index],\n })\n }\n seen.add(key)\n if (!(OPERATIONAL_NETWORKS as readonly string[]).includes(pair.network)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Network \"${pair.network}\" isn't live yet — only ${OPERATIONAL_NETWORKS.join(', ')} today.`,\n path: [index, 'network'],\n })\n }\n })\n })\n .describe(\n `Every \\`(token, network)\\` pair the payer is allowed to pay with — 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\\`) — 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 — 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) — an unconfigured \\`(token, network)\\` combination for your environment is rejected with \\`422 token_not_supported\\`.`,\n )\n\nexport const CHARGE_SPLIT_RECIPIENTS_MAX = 5\n\nexport const SplitRecipientSchema = z.object({\n address: z\n .string()\n .regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address')\n .describe('EVM address to send a slice of this charge to.'),\n percent: z\n .number()\n .positive()\n .max(100)\n .describe(\n \"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 — see `docs/payments.md`'s \\\"Settling the payout\\\" section for the exact math.\",\n ),\n label: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Free-form label for your own bookkeeping (e.g. `\"supplier\"`, `\"sales rep\"`) — echoed back unchanged, never interpreted by Klappay.',\n ),\n})\nexport type SplitRecipient = z.infer<typeof SplitRecipientSchema>\n\n// Response-only shape (echoed on `Charge.splitRecipients`) — the resolved\n// address, not the `recipientId` that was submitted, so a merchant reading\n// their own charge back can actually see where the money went without a\n// second lookup. `CreateChargeSchema` below never accepts this shape\n// directly; see `SplitRecipientInputSchema`.\n\nexport const SplitRecipientInputSchema = z.object({\n recipientId: z\n .string()\n .describe(\n 'id of a `Recipient` you already registered via `POST /v1/recipients` (not a raw address) — 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.',\n ),\n percent: z\n .number()\n .positive()\n .max(100)\n .describe(\n \"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 — see `docs/payments.md`'s \\\"Settling the payout\\\" section for the exact math.\",\n ),\n label: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Free-form label for your own bookkeeping (e.g. `\"supplier\"`, `\"sales rep\"`) — echoed back unchanged, never interpreted by Klappay. Independent of the label the recipient was registered with.',\n ),\n})\nexport type SplitRecipientInput = z.infer<typeof SplitRecipientInputSchema>\n\nconst SplitRecipientsInputSchema = z\n .array(SplitRecipientInputSchema)\n .max(CHARGE_SPLIT_RECIPIENTS_MAX)\n .superRefine((recipients, ctx) => {\n const seen = new Set<string>()\n recipients.forEach((recipient, index) => {\n if (seen.has(recipient.recipientId)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate split recipientId: ${recipient.recipientId}.`,\n path: [index, 'recipientId'],\n })\n }\n seen.add(recipient.recipientId)\n })\n })\n .describe(\n `Optional extra recipients for this charge's split — e.g. a supplier or the sales rep who closed the deal — 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) — a request that doesn't is rejected with \\`422 split_recipients_exceed_available_percent\\`.`,\n )\n\nexport const CHARGE_AMOUNT_MAX = 999_999_999_999\n\nexport const CreateChargeSchema = z.object({\n amount: z\n .number()\n .positive()\n .max(CHARGE_AMOUNT_MAX)\n .describe(\n 'Amount to charge, in `currency` units (e.g. `49.9` = $49.90) — up to 6 decimal places; anything more precise is silently truncated. Required — every charge has a target amount, the first credited transfer that reaches it confirms the charge.',\n ),\n currency: z\n .literal('USD')\n .default('USD')\n .describe('Always `USD` today — the only supported currency.'),\n acceptedPayments: AcceptedPaymentsSchema,\n expiresIn: z\n .number()\n .int()\n .min(CHARGE_EXPIRES_IN_MIN_SECONDS)\n .max(CHARGE_EXPIRES_IN_MAX_SECONDS)\n .describe(\n 'Seconds, not minutes or milliseconds — how long the charge stays open before it expires. Required, min 60, max 3600 (60 minutes) — 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.',\n ),\n idempotencyKey: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe(\n 'Scoped to your tenant. Replaying the same key with the exact same request body returns the original charge unchanged instead of creating a duplicate — 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.',\n ),\n externalRef: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe(\n 'An opaque correlation id from your own system (e.g. an order id) — echoed back on the charge and in every webhook payload. Not interpreted or validated by Klappay.',\n ),\n source: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Free-form label for what created this charge (e.g. `\"checkout\"`, `\"invoice\"`) — 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.',\n ),\n metadata: MetadataWithKlappaySchema.optional(),\n redirectUrl: z\n .string()\n .url()\n .refine((value) => /^https?:\\/\\//.test(value), 'must use http or https')\n .optional()\n .describe(\n \"Where to send the payer once this charge resolves, if you use Klappay's hosted checkout page (see `checkoutUrl` on the read shape) — ignored otherwise. Must be `http(s)` — 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.\",\n ),\n splitRecipients: SplitRecipientsInputSchema.optional(),\n escrow: EscrowConfigSchema.optional().describe(\n \"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 — 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.\",\n ),\n})\n\nexport type CreateChargeInput = z.infer<typeof CreateChargeSchema>\n\nexport type CreateChargeRequest = z.input<typeof CreateChargeSchema>\n\nexport const ChargeSchema = z.object({\n id: z\n .string()\n .describe('Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later.'),\n amount: z\n .number()\n .describe('The amount originally requested, in `currency` units (up to 6 decimal places).'),\n amountReceived: z\n .number()\n .nullable()\n .describe(\n '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` — see `isOverpaid`.',\n ),\n isOverpaid: z\n .boolean()\n .describe(\n '`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically — see the docs for why.',\n ),\n currency: z.string().describe('Always `USD` today — the only supported currency.'),\n acceptedPayments: z\n .array(AcceptedPaymentSchema)\n .describe(\n 'Every `(token, network)` pair this charge was configured to accept, unchanged after creation.',\n ),\n paidWith: z\n .array(AcceptedPaymentSchema)\n .describe(\n 'Every distinct `(token, network)` pair that has actually contributed a credited transfer so far — 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`.',\n ),\n swapAlternatives: z\n .array(SwapAlternativeSchema)\n .describe(\n \"Every `(token, network)` pair the payer can pay with instead, via `POST /v1/charges/{id}/quote` — 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 — 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 — `POST /v1/charges/{id}/quote` always rejects a test-environment charge with `422 swap_test_environment_unsupported`).\",\n ),\n address: z\n .string()\n .describe(\n 'The on-chain address the payer must send funds to — identical across every accepted network (0xSplits addresses are chain-agnostic). Unique per charge, predicted at creation time — funds sent here go directly to the merchant, Klappay never custodies them.',\n ),\n status: ChargeStatusSchema,\n settlementStatus: SettlementStatusSchema.nullable(),\n environment: EnvironmentSchema,\n apiKeyId: z\n .string()\n .nullable()\n .describe(\n 'Which of your API keys created this charge. `null` for a charge created before this field existed.',\n ),\n txHash: z\n .string()\n .nullable()\n .describe(\n 'Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected.',\n ),\n externalRef: z.string().nullable(),\n source: z.string().nullable(),\n metadata: MetadataWithKlappaySchema.nullable(),\n redirectUrl: z\n .string()\n .nullable()\n .describe('Echoes the `redirectUrl` set at creation, if any. `null` if none was set.'),\n checkoutUrl: z\n .string()\n .nullable()\n .describe(\n \"Link to Klappay's hosted checkout page for this charge. `null` if this deployment has no hosted checkout configured — build your own payment UI from `address`/`acceptedPayments` instead.\",\n ),\n splitRecipients: z\n .array(SplitRecipientSchema)\n .describe('Echoes whatever extra split recipients were set at creation — empty array if none.'),\n createdAt: z.string().datetime(),\n expiresAt: z\n .string()\n .datetime()\n .describe(\n 'When this charge stops accepting payment, if still `pending`/`partially_paid` by then.',\n ),\n confirmedAt: z\n .string()\n .datetime()\n .nullable()\n .describe('When `status` first reached `confirmed`. `null` until then.'),\n settledAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n \"When `settlementStatus` first reached `completed` — the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`.\",\n ),\n lastActivityAt: z\n .string()\n .datetime()\n .describe(\n 'When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet.',\n ),\n escrow: z\n .object({\n releaserAddress: z\n .string()\n .describe('The only address that can ever release this escrow — never Klappay.'),\n releasedAt: z\n .string()\n .datetime()\n .nullable()\n .describe('When the release actually executed on-chain. `null` until then.'),\n refundedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When the refund actually executed on-chain. `null` until then. Mutually exclusive with `releasedAt` — an escrow can only ever be released or refunded once, never both.',\n ),\n })\n .nullable()\n .describe(\n 'Present only when this charge was created as an escrow (see `escrow` on the create request) — `null` for a normal charge.',\n ),\n})\n\nexport type Charge = z.infer<typeof ChargeSchema>\n\nexport const ListChargesSchema = z\n .object({\n status: ChargeStatusSchema.optional(),\n token: TokenSchema.optional().describe(\n 'Filters on `paidWith.token` — the pair actually paid, not accepted.',\n ),\n network: NetworkSchema.optional().describe(\n 'Filters on `paidWith.network` — the pair actually paid, not accepted.',\n ),\n environment: EnvironmentSchema.optional(),\n since: z\n .string()\n .datetime()\n .optional()\n .describe(\n '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.',\n ),\n isOverpaid: z\n .enum(['true', 'false'])\n .transform((v) => v === 'true')\n .optional(),\n })\n .extend(PaginationQuerySchema.shape)\n\nexport type ListChargesInput = z.infer<typeof ListChargesSchema>\n\nexport type ListChargesRequest = z.input<typeof ListChargesSchema>\n\nexport const PaginatedChargesSchema = paginatedSchema(ChargeSchema)\n\nexport type PaginatedCharges = z.infer<typeof PaginatedChargesSchema>\n\nexport const GetChargeQrCodeQuerySchema = z.object({\n token: TokenSchema.optional().describe(\n 'Which accepted `(token, network)` pair to encode in the QR — 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.',\n ),\n network: NetworkSchema.optional(),\n})\n\nexport type GetChargeQrCodeQuery = z.infer<typeof GetChargeQrCodeQuerySchema>\n\nexport type GetChargeQrCodeQueryRequest = z.input<typeof GetChargeQrCodeQuerySchema>\n","import { z } from 'zod'\n\nexport const CHECKOUT_PRODUCTS_MAX = 20\n\nexport const CheckoutProductSchema = z.object({\n name: z\n .string()\n .min(1)\n .max(200)\n .describe('What the payer is buying, shown as-is on the hosted checkout page.'),\n quantity: z\n .number()\n .int()\n .positive()\n .max(9999)\n .optional()\n .describe('How many of this item. Omit for a single, unquantified item.'),\n imageUrl: z\n .string()\n .url()\n .max(2048)\n .refine((value) => /^https?:\\/\\//.test(value), 'must use http or https')\n .optional()\n .describe(\n \"Product image, fetched only by the payer's own browser — Klappay never fetches it server-side. Must be `http(s)`.\",\n ),\n})\nexport type CheckoutProduct = z.infer<typeof CheckoutProductSchema>\n\nexport const KlappayCheckoutMetadataSchema = z\n .object({\n products: z\n .array(CheckoutProductSchema)\n .max(CHECKOUT_PRODUCTS_MAX)\n .optional()\n .describe(\n `What the payer is buying, shown on the hosted checkout page — up to ${CHECKOUT_PRODUCTS_MAX} items. Purely informational: never validated against \\`amount\\`, never used by any payment or distribution logic.`,\n ),\n })\n .describe(\n 'Reserved for Klappay — 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.',\n )\nexport type KlappayCheckoutMetadata = z.infer<typeof KlappayCheckoutMetadataSchema>\n\nexport const MetadataWithKlappaySchema = z\n .object({ klappay: KlappayCheckoutMetadataSchema.optional() })\n .catchall(z.unknown())\n .describe(\n 'Arbitrary key/value data, returned as-is on every read. Put whatever you want in here — 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`.',\n )\n","import { z } from 'zod'\n\nexport const EscrowConfigSchema = z.object({\n releaserAddress: z\n .string()\n .regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address')\n .optional()\n .describe(\n \"The only address ever authorized to release this charge's escrowed funds — 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` — 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 — any well-formed address is accepted, since Klappay never custodies these funds.\",\n ),\n})\nexport type EscrowConfig = z.infer<typeof EscrowConfigSchema>\n\nexport const ReleaseEscrowRequestSchema = z.object({\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'must be hex-encoded signature bytes')\n .describe(\n \"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` — 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 — 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 — the Safe contract itself rejects a signature that isn't from `escrowReleaserAddress`, never trusted at face value by Klappay.\",\n ),\n})\nexport type ReleaseEscrowRequest = z.infer<typeof ReleaseEscrowRequestSchema>\n\nexport const RefundEscrowRequestSchema = z.object({\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'must be hex-encoded signature bytes')\n .describe(\n \"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` — 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 — 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 — the Safe contract itself rejects a signature that isn't from `escrowReleaserAddress`, never trusted at face value by Klappay.\",\n ),\n})\nexport type RefundEscrowRequest = z.infer<typeof RefundEscrowRequestSchema>\n","import { z } from 'zod'\nimport { ChargeSchema } from './charges'\nimport { NetworkSchema } from './networks'\n\nexport const CheckChargeRequestSchema = z\n .object({\n txHash: z\n .string()\n .regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 32-byte transaction hash')\n .optional()\n .describe(\n \"The on-chain transaction hash to verify directly, if you already have it — 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 — whatever this transaction actually contains on-chain is what gets credited, regardless of any amount/token implied elsewhere.\",\n ),\n network: NetworkSchema.optional().describe(\n \"Which network `txHash` is on — required together with `txHash`, since a transaction hash alone doesn't identify a chain. Must be one of the networks this charge actually accepts payment on, or `422 payment_pair_not_accepted`.\",\n ),\n })\n .refine((data) => Boolean(data.txHash) === Boolean(data.network), {\n message: '`txHash` and `network` must be provided together, or both omitted',\n })\nexport type CheckChargeRequest = z.infer<typeof CheckChargeRequestSchema>\n\nexport const CheckChargeResponseSchema = ChargeSchema.extend({\n transactionSender: z\n .string()\n .nullable()\n .describe(\n \"The `txHash` transaction's own sender (`from`) — 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 — a hint-less background scan, an unaccepted network, or a not-found/reverted transaction all leave this `null`.\",\n ),\n})\nexport type CheckChargeResponse = z.infer<typeof CheckChargeResponseSchema>\n","import { z } from 'zod'\nimport { NetworkSchema } from './networks'\nimport { PAGINATION_LIMIT_MAX, paginatedSchema } from './pagination'\nimport { TokenSchema } from './tokens'\n\nexport const SplitDistributionStatusSchema = z\n .enum(['pending', 'processing', 'completed', 'failed'])\n .describe(\n \"Status of one payout attempt to the merchant, for a single `(token, network)` pair — 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.\",\n )\nexport type SplitDistributionStatus = z.infer<typeof SplitDistributionStatusSchema>\n\nexport const PendingDistributionRecipientSchema = z.object({\n address: z.string().describe('On-chain recipient address.'),\n percentAllocation: z\n .number()\n .describe(\"This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).\"),\n})\n\nexport const PendingDistributionSchema = z.object({\n splitAddress: z.string().describe('The on-chain 0xSplits address to call `distribute()` on.'),\n network: NetworkSchema,\n token: TokenSchema,\n recipients: z\n .array(PendingDistributionRecipientSchema)\n .describe(\n 'The exact recipient list to pass to `distribute()` — 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.',\n ),\n distributorFeePercent: z\n .number()\n .describe(\n '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.',\n ),\n estimatedRewardAmount: z\n .number()\n .describe(\n \"Estimate only, in the charge's `currency` units, based on the amount Klappay detected on-chain — 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.\",\n ),\n availableSince: z\n .string()\n .datetime()\n .describe('When this distribution entered its grace period.'),\n graceEndsAt: z\n .string()\n .datetime()\n .describe(\n \"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.\",\n ),\n})\n\nexport type PendingDistribution = z.infer<typeof PendingDistributionSchema>\n\nexport const PaginatedPendingDistributionsSchema = paginatedSchema(PendingDistributionSchema)\n\nexport type PaginatedPendingDistributions = z.infer<typeof PaginatedPendingDistributionsSchema>\n\nexport const ListenPendingDistributionsQuerySchema = z.object({\n limit: z.coerce\n .number()\n .int()\n .min(0)\n .max(PAGINATION_LIMIT_MAX)\n .default(0)\n .describe(\n \"How many currently-claimable distributions to emit as an initial snapshot right after connecting — each as a synthetic `distribution.available` event — 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 — 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.\",\n ),\n})\n\nexport type ListenPendingDistributionsQuery = z.infer<typeof ListenPendingDistributionsQuerySchema>\n\nexport const PendingDistributionEventSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('distribution.available'),\n distribution: PendingDistributionSchema,\n }),\n z.object({\n type: z.literal('distribution.claimed'),\n splitAddress: z\n .string()\n .describe('No longer claimable — either settled by someone, or picked up by the worker.'),\n }),\n])\n\nexport type PendingDistributionEvent = z.infer<typeof PendingDistributionEventSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\n\nexport const MetricsResourceSchema = z\n .enum(['charges', 'transactions', 'distributions'])\n .describe(\n 'Which underlying dataset to query. `charges`: one row per charge. `transactions`: one row per detected on-chain transfer — 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.',\n )\nexport type MetricsResource = z.infer<typeof MetricsResourceSchema>\n\nexport const MetricsAggregationSchema = z\n .enum(['count', 'sum', 'avg', 'min', 'max'])\n .describe(\n '`count` counts matching rows and never takes `field`. `sum`/`avg`/`min`/`max` require `field` to be set to one of the resource’s numeric fields.',\n )\nexport type MetricsAggregation = z.infer<typeof MetricsAggregationSchema>\n\nexport const MetricsFilterOperatorSchema = z\n .enum(['eq', 'neq', 'in', 'gt', 'gte', 'lt', 'lte'])\n .describe(\n '`in` expects an array value (max 50 entries); every other operator expects a single scalar.',\n )\nexport type MetricsFilterOperator = z.infer<typeof MetricsFilterOperatorSchema>\n\nexport const MetricsDateGranularitySchema = z\n .enum(['day', 'week', 'month', 'year'])\n .describe(\n 'Bucket width for a `date_bucket` `groupBy` entry — Postgres `date_trunc` semantics (UTC).',\n )\nexport type MetricsDateGranularity = z.infer<typeof MetricsDateGranularitySchema>\n\nconst metricsQueryEnvironmentSchema = EnvironmentSchema.describe(\n \"Which environment's data to query — `live` or `test`. Must match the environment of the API key used to authenticate — scopes the query to charges/transactions/distributions created under a `live` or `test` API key respectively.\",\n)\n\nexport const MAX_METRICS_QUERY_DATE_RANGE_DAYS = 366\nexport const METRICS_QUERY_MAX_ROW_LIMIT = 1000\nexport const METRICS_QUERY_DEFAULT_ROW_LIMIT = 100\nexport const METRICS_QUERY_MAX_GROUP_BY = 3\nexport const METRICS_QUERY_MAX_FILTERS = 20\nexport const METRICS_QUERY_MAX_METRICS = 10\n\nconst METRIC_ALIAS_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\nconst metricAliasSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(\n METRIC_ALIAS_PATTERN,\n 'Must start with a letter or underscore, and contain only letters, digits, and underscores — this becomes a SQL column alias.',\n )\n .optional()\n\nconst MetricsFilterValueSchema = z.union([\n z.string().max(255),\n z.number(),\n z.boolean(),\n z\n .array(z.union([z.string().max(255), z.number()]))\n .min(1)\n .max(50),\n])\n\nconst orderBySchema = z\n .object({\n key: z\n .string()\n .min(1)\n .max(64)\n .regex(\n METRIC_ALIAS_PATTERN,\n 'Must start with a letter or underscore, and contain only letters, digits, and underscores — every valid output column name already looks like this.',\n )\n .describe(\n 'An output column name from this same query — either a `groupBy` field name, or a metric’s `alias` (or its default name: `${aggregation}` for `count`, `${aggregation}_${field}` otherwise, e.g. `sum_amount`). Must match `^[a-zA-Z_][a-zA-Z0-9_]*$` — every real output column name already does, so this only ever rejects a value that could never have been one.',\n ),\n direction: z.enum(['asc', 'desc']),\n })\n .describe(\n 'Sort the result rows by any output column — 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.',\n )\n\nconst limitSchema = z\n .number()\n .int()\n .min(1)\n .max(METRICS_QUERY_MAX_ROW_LIMIT)\n .default(METRICS_QUERY_DEFAULT_ROW_LIMIT)\n .describe(\n `Max rows to return, ${1}–${METRICS_QUERY_MAX_ROW_LIMIT}, default ${METRICS_QUERY_DEFAULT_ROW_LIMIT}. If more rows matched, \\`meta.truncated\\` is \\`true\\` on the response — narrow the query instead of just raising this.`,\n )\n\nexport const ChargesQueryFieldSchema = z\n .enum([\n 'status',\n 'source',\n 'apiKeyId',\n 'currency',\n 'isOverpaid',\n 'externalRef',\n 'escrowReleaserAddress',\n ])\n .describe(\n \"A `Charge` field to filter or group by — 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 — filter `escrowReleaserAddress` with operator `neq`/value `null` to isolate escrow-configured charges (see `escrow` in charges.md).\",\n )\nexport type ChargesQueryField = z.infer<typeof ChargesQueryFieldSchema>\n\nexport const ChargesMetricFieldSchema = z\n .enum(['amount', 'amountReceived', 'feePercent', 'escrowFeePercent'])\n .describe(\n 'A `Charge` numeric field to aggregate. `amount`/`amountReceived` are decimal currency amounts (requested vs. actually received — 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 — see `docs/payments.md`.',\n )\nexport type ChargesMetricField = z.infer<typeof ChargesMetricFieldSchema>\n\nexport const ChargesDateFieldSchema = z\n .enum(['createdAt', 'confirmedAt', 'lastActivityAt', 'expiresAt', 'escrowReleasedAt'])\n .describe(\n 'A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` — 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 — same implicit-exclusion behavior as `confirmedAt`, scoped to escrow charges only.',\n )\nexport type ChargesDateField = z.infer<typeof ChargesDateFieldSchema>\n\nconst ChargesFilterSchema = z.object({\n field: ChargesQueryFieldSchema,\n operator: MetricsFilterOperatorSchema,\n value: MetricsFilterValueSchema,\n})\n\nconst ChargesGroupBySchema = z.union([\n z.object({ type: z.literal('field'), field: ChargesQueryFieldSchema }),\n z.object({\n type: z.literal('date_bucket'),\n field: ChargesDateFieldSchema,\n granularity: MetricsDateGranularitySchema,\n }),\n])\n\nconst ChargesMetricSchema = z.object({\n aggregation: MetricsAggregationSchema,\n field: ChargesMetricFieldSchema.optional(),\n alias: metricAliasSchema,\n})\n\nconst ChargesMetricsQuerySchema = z.object({\n resource: z.literal('charges'),\n environment: metricsQueryEnvironmentSchema,\n dateRange: z.object({\n field: ChargesDateFieldSchema,\n from: z.string().max(64).datetime(),\n to: z.string().max(64).datetime(),\n }),\n groupBy: z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),\n metrics: z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),\n filters: z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),\n orderBy: orderBySchema.optional(),\n limit: limitSchema,\n})\n\nexport const TransactionsQueryFieldSchema = z\n .enum(['network', 'token', 'source', 'causedTransition'])\n .describe(\n \"A `Transaction` field to filter or group by — see `NetworkSchema`/`TokenSchema`/`TransactionSourceSchema` for their possible values. `causedTransition` is `true` only for the transfer(s) that actually flipped the charge's `status` — 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).\",\n )\nexport type TransactionsQueryField = z.infer<typeof TransactionsQueryFieldSchema>\n\nexport const TransactionsMetricFieldSchema = z\n .enum(['amount'])\n .describe(\"The transfer amount, in the charge's `currency` units.\")\nexport type TransactionsMetricField = z.infer<typeof TransactionsMetricFieldSchema>\n\nexport const TransactionsDateFieldSchema = z\n .enum(['detectedAt'])\n .describe('When Klappay detected this transfer on-chain (not when it was mined).')\nexport type TransactionsDateField = z.infer<typeof TransactionsDateFieldSchema>\n\nconst TransactionsFilterSchema = z.object({\n field: TransactionsQueryFieldSchema,\n operator: MetricsFilterOperatorSchema,\n value: MetricsFilterValueSchema,\n})\n\nconst TransactionsGroupBySchema = z.union([\n z.object({ type: z.literal('field'), field: TransactionsQueryFieldSchema }),\n z.object({\n type: z.literal('date_bucket'),\n field: TransactionsDateFieldSchema,\n granularity: MetricsDateGranularitySchema,\n }),\n])\n\nconst TransactionsMetricSchema = z.object({\n aggregation: MetricsAggregationSchema,\n field: TransactionsMetricFieldSchema.optional(),\n alias: metricAliasSchema,\n})\n\nconst TransactionsMetricsQuerySchema = z.object({\n resource: z.literal('transactions'),\n environment: metricsQueryEnvironmentSchema,\n dateRange: z.object({\n field: TransactionsDateFieldSchema,\n from: z.string().max(64).datetime(),\n to: z.string().max(64).datetime(),\n }),\n groupBy: z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),\n metrics: z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),\n filters: z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),\n orderBy: orderBySchema.optional(),\n limit: limitSchema,\n})\n\nexport const DistributionsQueryFieldSchema = z\n .enum(['status', 'network', 'token', 'distributorAddress'])\n .describe(\n \"A `SplitDistribution` field to filter or group by — see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values. `distributorAddress` is the public on-chain address that actually called `distribute()` for a `completed` distribution — 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.\",\n )\nexport type DistributionsQueryField = z.infer<typeof DistributionsQueryFieldSchema>\n\nexport const DistributionsMetricFieldSchema = z\n .enum(['attempts'])\n .describe(\n \"How many times a payout was attempted for this settlement so far — 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.\",\n )\nexport type DistributionsMetricField = z.infer<typeof DistributionsMetricFieldSchema>\n\nexport const DistributionsDateFieldSchema = z\n .enum(['createdAt', 'processingStartedAt', 'completedAt'])\n .describe(\n \"`createdAt`: when this settlement was queued. `processingStartedAt`: when a worker began its most recent attempt at the payout — `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 — `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed.\",\n )\nexport type DistributionsDateField = z.infer<typeof DistributionsDateFieldSchema>\n\nconst DistributionsFilterSchema = z.object({\n field: DistributionsQueryFieldSchema,\n operator: MetricsFilterOperatorSchema,\n value: MetricsFilterValueSchema,\n})\n\nconst DistributionsGroupBySchema = z.union([\n z.object({ type: z.literal('field'), field: DistributionsQueryFieldSchema }),\n z.object({\n type: z.literal('date_bucket'),\n field: DistributionsDateFieldSchema,\n granularity: MetricsDateGranularitySchema,\n }),\n])\n\nconst DistributionsMetricSchema = z.object({\n aggregation: MetricsAggregationSchema,\n field: DistributionsMetricFieldSchema.optional(),\n alias: metricAliasSchema,\n})\n\nconst DistributionsMetricsQuerySchema = z.object({\n resource: z.literal('distributions'),\n environment: metricsQueryEnvironmentSchema,\n dateRange: z.object({\n field: DistributionsDateFieldSchema,\n from: z.string().max(64).datetime(),\n to: z.string().max(64).datetime(),\n }),\n groupBy: z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),\n metrics: z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),\n filters: z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),\n orderBy: orderBySchema.optional(),\n limit: limitSchema,\n})\n\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000\n\nexport const MetricsQuerySchema = z\n .discriminatedUnion('resource', [\n ChargesMetricsQuerySchema,\n TransactionsMetricsQuerySchema,\n DistributionsMetricsQuerySchema,\n ])\n .superRefine((input, ctx) => {\n const from = new Date(input.dateRange.from)\n const to = new Date(input.dateRange.to)\n if (from >= to) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: '`dateRange.from` must be before `dateRange.to`.',\n path: ['dateRange', 'from'],\n })\n }\n const spanDays = (to.getTime() - from.getTime()) / ONE_DAY_MS\n if (spanDays > MAX_METRICS_QUERY_DATE_RANGE_DAYS) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `\\`dateRange\\` cannot span more than ${MAX_METRICS_QUERY_DATE_RANGE_DAYS} days.`,\n path: ['dateRange', 'to'],\n })\n }\n const dateBucketCount = input.groupBy.filter((entry) => entry.type === 'date_bucket').length\n if (dateBucketCount > 1) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'At most one `date_bucket` entry is allowed in `groupBy`.',\n path: ['groupBy'],\n })\n }\n input.metrics.forEach((metric, index) => {\n if (metric.aggregation !== 'count' && metric.field === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: '`field` is required unless `aggregation` is `count`.',\n path: ['metrics', index, 'field'],\n })\n }\n })\n const aliases = input.metrics\n .map((metric) => metric.alias)\n .filter((alias) => alias !== undefined)\n if (new Set(aliases).size !== aliases.length) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Every `metrics[].alias` must be unique.',\n path: ['metrics'],\n })\n }\n const reservedNames = new Set(['bucket', ...input.groupBy.map((entry) => entry.field)])\n input.metrics.forEach((metric, index) => {\n if (metric.alias !== undefined && reservedNames.has(metric.alias)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `\\`alias\\` \"${metric.alias}\" collides with a \\`groupBy\\` field name (or the reserved word \"bucket\") — choose a different alias.`,\n path: ['metrics', index, 'alias'],\n })\n }\n })\n })\n\nexport type MetricsQuery = z.infer<typeof MetricsQuerySchema>\nexport type MetricsQueryRequest = z.input<typeof MetricsQuerySchema>\n\nexport const MetricsQueryResultRowSchema = z.record(\n z.string(),\n z.union([z.string(), z.number(), z.boolean(), z.null()]),\n)\nexport type MetricsQueryResultRow = z.infer<typeof MetricsQueryResultRowSchema>\n\nexport const MetricsQueryResultSchema = z.object({\n data: z.array(MetricsQueryResultRowSchema),\n meta: z.object({\n resource: MetricsResourceSchema,\n environment: EnvironmentSchema,\n rowCount: z.number().int().describe('Number of rows in `data`.'),\n truncated: z\n .boolean()\n .describe(\n '`true` if more rows matched than `limit` allowed — `data` holds only the first `limit`.',\n ),\n }),\n})\nexport type MetricsQueryResult = z.infer<typeof MetricsQueryResultSchema>\n","import { z } from 'zod'\n\nexport const ChargeWebhookEventTypeSchema = z\n .enum([\n 'charge.created',\n 'charge.partially_paid',\n 'charge.confirmed',\n 'charge.expired',\n 'charge.underpaid',\n 'charge.settled',\n 'charge.settlement_failed',\n 'charge.overpaid',\n 'charge.escrow_released',\n 'charge.escrow_refunded',\n ])\n .describe(\n '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 — 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` — 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` — 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`.',\n )\n\nexport const WebhookDeliveryEventTypeSchema = z\n .enum(['webhook.delivery_failed', 'webhook.delivery_recovered', 'webhook.endpoint_unhealthy'])\n .describe(\n \"Meta-events about the health of your own webhook endpoints — 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`).\",\n )\n\nexport const WebhookEventTypeSchema = z.union([\n ChargeWebhookEventTypeSchema,\n WebhookDeliveryEventTypeSchema,\n])\n\nexport type WebhookEventType = z.infer<typeof WebhookEventTypeSchema>\n\nexport const WebhookCategorySchema = z\n .enum(['payments', 'webhooks'])\n .describe(\n 'Subscribe to every event in a category via `eventCategories` instead of listing events one by one — new events added to a category later arrive automatically, no subscription update needed.',\n )\nexport type WebhookCategory = z.infer<typeof WebhookCategorySchema>\n\nfunction buildCategoryMap(): Record<WebhookEventType, WebhookCategory> {\n const map = {} as Record<WebhookEventType, WebhookCategory>\n for (const event of ChargeWebhookEventTypeSchema.options) map[event] = 'payments'\n for (const event of WebhookDeliveryEventTypeSchema.options) map[event] = 'webhooks'\n\n for (const event of WebhookEventTypeSchema.options.flatMap((schema) => schema.options)) {\n if (!(event in map)) {\n throw new Error(\n `buildCategoryMap: \"${event}\" has no category — a new event sub-schema was unioned into WebhookEventTypeSchema without a matching loop added here.`,\n )\n }\n }\n\n return map\n}\n\nexport const EVENT_CATEGORY_MAP = buildCategoryMap()\n\nexport const WEBHOOK_EVENT_CATEGORIES: Record<WebhookCategory, readonly WebhookEventType[]> = {\n payments: ChargeWebhookEventTypeSchema.options,\n webhooks: WebhookDeliveryEventTypeSchema.options,\n}\n\nexport const TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([\n 'charge.created',\n 'charge.escrow_released',\n 'charge.escrow_refunded',\n]).describe(\n \"Every charge event that represents a payment-progress state transition a sandbox charge can be pushed into — everything except `charge.created` (a charge already exists by the time you have an id to trigger against) and the two escrow-terminal events, which are reached by actually calling `POST /v1/charges/{id}/release` or `POST /v1/charges/{id}/refund` on a test-environment escrow charge (a real Safe transaction on that network's testnet), not this generic trigger.\",\n)\n\nexport type TriggerableChargeEvent = z.infer<typeof TriggerableChargeEventSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\nimport { EVENT_CATEGORY_MAP, WebhookCategorySchema, WebhookEventTypeSchema } from './webhook-events'\n\nexport const WEBHOOK_EVENTS_WILDCARD = '*'\n\nexport const CreateWebhookSchema = z\n .object({\n url: z\n .string()\n .max(2048)\n .url()\n .describe(\n 'Must be HTTPS and resolve to a public address — private/internal IPs are rejected.',\n ),\n events: z\n .array(z.union([WebhookEventTypeSchema, z.literal(WEBHOOK_EVENTS_WILDCARD)]))\n .max(Object.keys(EVENT_CATEGORY_MAP).length + 1)\n .default([])\n .describe(\n '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.',\n ),\n eventCategories: z\n .array(WebhookCategorySchema)\n .max(WebhookCategorySchema.options.length)\n .default([])\n .describe(\n 'Subscribe to every event in these categories. At least one of `events` or `eventCategories` is required.',\n ),\n excludeEvents: z\n .array(WebhookEventTypeSchema)\n .max(Object.keys(EVENT_CATEGORY_MAP).length)\n .default([])\n .describe(\n 'Event types to exclude even if selected via `events: [\"*\"]` or `eventCategories`.',\n ),\n })\n .refine((v) => v.events.length > 0 || v.eventCategories.length > 0, {\n message: 'must select at least one event via `events` or `eventCategories`',\n path: ['events'],\n })\n\nexport type CreateWebhookInput = z.infer<typeof CreateWebhookSchema>\n\nexport type CreateWebhookRequest = z.input<typeof CreateWebhookSchema>\n\nexport const WebhookSchema = z.object({\n id: z.string(),\n environment: EnvironmentSchema.nullable().describe(\n \"Which environment's API key created this webhook — `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 — the case for every webhook created before this field existed).\",\n ),\n url: z.string(),\n events: z.array(WebhookEventTypeSchema),\n eventCategories: z.array(WebhookCategorySchema),\n excludeEvents: z.array(WebhookEventTypeSchema),\n isWildcard: z.boolean(),\n secret: z\n .string()\n .describe(\n \"The signing secret, used to verify the `X-Klappay-Signature` header on every delivery. Returned in full only this once — 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 — 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 — see github.com/klappay for available SDKs.\",\n ),\n createdAt: z.string().datetime(),\n})\n\nexport type Webhook = z.infer<typeof WebhookSchema>\n\nexport const WebhookListItemSchema = WebhookSchema.omit({ secret: true }).extend({\n hint: z\n .string()\n .describe('A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).'),\n})\nexport type WebhookListItem = z.infer<typeof WebhookListItemSchema>\n\nexport const WebhookPayloadSchema = z.object({\n id: z\n .string()\n .describe(\n 'Unique id for this specific delivery — also sent as the `X-Klappay-Delivery` header.',\n ),\n event: WebhookEventTypeSchema,\n createdAt: z.string().datetime(),\n data: z\n .unknown()\n .describe(\n 'Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; webhook-delivery events carry a smaller, event-specific object — see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md.',\n ),\n})\n\nexport type WebhookPayload = z.infer<typeof WebhookPayloadSchema>\n\nexport const WebhookDeliveryStatusSchema = z.enum(['pending', 'delivered', 'failed'])\nexport type WebhookDeliveryStatus = z.infer<typeof WebhookDeliveryStatusSchema>\n\nexport const WebhookDeliverySchema = z.object({\n id: z.string(),\n webhookId: z.string(),\n event: WebhookEventTypeSchema,\n status: WebhookDeliveryStatusSchema.describe(\n '`pending`: still retrying. `delivered`: got a 2xx response. `failed`: retries exhausted (5 attempts over ~24h) — use `POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry` to try again manually.',\n ),\n attempts: z.number(),\n responseCode: z\n .number()\n .nullable()\n .describe(\n 'HTTP status your endpoint returned on the most recent attempt. `null` if every attempt failed to connect at all.',\n ),\n nextRetryAt: z.string().datetime().nullable(),\n deliveredAt: z.string().datetime().nullable(),\n createdAt: z.string().datetime(),\n})\n\nexport type WebhookDelivery = z.infer<typeof WebhookDeliverySchema>\n\nexport const ListWebhookDeliveriesSchema = PaginationQuerySchema\n\nexport type ListWebhookDeliveriesInput = z.infer<typeof ListWebhookDeliveriesSchema>\n\nexport type ListWebhookDeliveriesRequest = z.input<typeof ListWebhookDeliveriesSchema>\n\nexport const PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema)\n\nexport type PaginatedWebhookDeliveries = z.infer<typeof PaginatedWebhookDeliveriesSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\n\nconst EVM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/\n\nexport const CreateRecipientSchema = z.object({\n address: z\n .string()\n .regex(EVM_ADDRESS_REGEX, 'must be a 20-byte hex address')\n .describe('EVM address to register as a trusted split recipient for your organization.'),\n label: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe('Free-form label for your own bookkeeping (e.g. `\"supplier\"`) — never interpreted.'),\n})\nexport type CreateRecipientInput = z.infer<typeof CreateRecipientSchema>\nexport type CreateRecipientRequest = z.input<typeof CreateRecipientSchema>\n\nexport const RecipientSchema = z.object({\n id: z\n .string()\n .describe(\n \"Klappay-generated id, e.g. `rc_...` — this, not the raw address, is what a charge's `splitRecipients[].recipientId` references.\",\n ),\n environment: EnvironmentSchema,\n address: z.string(),\n label: z.string().nullable(),\n payout: z\n .boolean()\n .describe(\n \"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}` — requires the `recipients:manage_payout` scope, deliberately separate from `recipients:write`.\",\n ),\n createdAt: z.string().datetime(),\n})\nexport type Recipient = z.infer<typeof RecipientSchema>\n\nexport const SetRecipientPayoutSchema = z.object({\n payout: z.boolean().describe('New payout-eligibility value for this recipient.'),\n})\nexport type SetRecipientPayoutInput = z.infer<typeof SetRecipientPayoutSchema>\n","import { z } from 'zod'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\nimport { WebhookEventTypeSchema } from './webhook-events'\n\nexport const TransactionSourceSchema = z\n .enum(['moralis_webhook', 'reconciliation_job', 'sandbox'])\n .describe(\n '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).',\n )\nexport type TransactionSource = z.infer<typeof TransactionSourceSchema>\n\nexport const TimelineEventTypeSchema = z\n .enum([\n 'charge.created',\n 'charge.expired',\n 'transaction.detected',\n 'split.distributed',\n 'webhook.dispatched',\n 'webhook.delivered',\n 'webhook.failed',\n ])\n .describe(\n '`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 — 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 — 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 — `failed` here means this single attempt failed, not that all retries were exhausted (see `WebhookDeliveryStatusSchema` for the exhausted-all-retries state).',\n )\nexport type TimelineEventType = z.infer<typeof TimelineEventTypeSchema>\n\nexport const TimelineEventSchema = z.object({\n type: TimelineEventTypeSchema,\n at: z.string().datetime(),\n txHash: z\n .string()\n .optional()\n .describe('Present for `transaction.detected` and `split.distributed` events only.'),\n amount: z\n .number()\n .optional()\n .describe(\n 'Present for `transaction.detected` events only — the amount that specific transfer carried.',\n ),\n source: TransactionSourceSchema.optional().describe(\n 'Present for `transaction.detected` events only.',\n ),\n token: TokenSchema.optional().describe(\n 'Present for `transaction.detected` and `split.distributed` events — which token this specific transfer, or settlement, used. A charge can accept (and be settled across) more than one `(token, network)` pair (see `Charge.acceptedPayments`); this is how to tell which one a given event actually used.',\n ),\n network: NetworkSchema.optional().describe(\n 'Present for `transaction.detected` and `split.distributed` events — which network this specific transfer, or settlement, used.',\n ),\n causedTransition: z\n .boolean()\n .optional()\n .describe(\n \"Present for `transaction.detected` events only. `true` if this specific transfer changed the charge's status (e.g. PENDING→CONFIRMED) — a charge paid in installments can have more than one such event.\",\n ),\n event: WebhookEventTypeSchema.optional().describe(\n 'Present for `webhook.*` events only — which event type this delivery was for.',\n ),\n responseCode: z\n .number()\n .nullable()\n .optional()\n .describe(\n 'Present for `webhook.*` events only — HTTP status your endpoint returned, or `null` if the request never connected.',\n ),\n attempts: z\n .number()\n .optional()\n .describe(\n 'Present for `webhook.*` events only — how many delivery attempts have been made so far.',\n ),\n})\nexport type TimelineEvent = z.infer<typeof TimelineEventSchema>\n","import { z } from 'zod'\n\nexport const HealthSchema = z.object({\n status: z\n .enum(['ok', 'error'])\n .describe(\n '`error` when the database connectivity check fails — 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.',\n ),\n version: z.string(),\n timestamp: z.string().datetime(),\n db: z\n .enum(['ok', 'error'])\n .describe('Result of a real database connectivity check, not just a process-alive check.'),\n pendingWebhooks: z\n .number()\n .describe('Count of webhook deliveries still awaiting a successful attempt.'),\n oldestPendingChargeAgeSeconds: z\n .number()\n .nullable()\n .describe('Age of the oldest still-unpaid charge, in seconds. `null` if there are none.'),\n lastMoralisEventAgeSeconds: z\n .number()\n .nullable()\n .describe(\n 'Seconds since the last on-chain payment notification was received — a cheap signal for whether payment detection is currently working. `null` if none have ever been received.',\n ),\n})\n\nexport type Health = z.infer<typeof HealthSchema>\n","import { z } from 'zod'\nimport { CHARGE_AMOUNT_MAX } from './charges'\nimport { TriggerableChargeEventSchema } from './webhook-events'\n\nexport const SandboxTriggerSchema = z.object({\n event: TriggerableChargeEventSchema,\n amount: z\n .number()\n .positive()\n .max(CHARGE_AMOUNT_MAX)\n .optional()\n .describe(\n 'Used with `charge.partially_paid` (amount to simulate as received so far — must be less than the charge amount, defaults to half of it if omitted) and with `charge.overpaid` (amount received — must be greater than the charge amount, defaults to 1.5x it if omitted). Ignored for every other event.',\n ),\n})\n\nexport type SandboxTriggerInput = z.infer<typeof SandboxTriggerSchema>\n","import { z } from 'zod'\nimport { AcceptedPaymentSchema } from './charges'\n\nexport const CapabilitiesSchema = z.object({\n acceptedPayments: z\n .array(AcceptedPaymentSchema)\n .describe(\n 'Every `(token, network)` pair actually configured for your environment right now — 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.',\n ),\n})\nexport type Capabilities = z.infer<typeof CapabilitiesSchema>\n","import { z } from 'zod'\nimport { AltTokenSchema } from './alt-tokens'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\n\nexport const CreateSwapQuoteSchema = z.object({\n inputToken: AltTokenSchema.describe(\n \"Which alt-cryptocurrency the payer wants to send — must be one of this charge's `swapAlternatives`, or `422 token_not_supported`.\",\n ),\n inputNetwork: NetworkSchema.describe(\n \"Which network the payer will send `inputToken` on. Also picks which of this charge's `acceptedPayments` pairs the swap resolves to — 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) — never a token the charge doesn't actually accept.\",\n ),\n takerAddress: z\n .string()\n .regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address')\n .describe(\n \"The payer's own wallet address — 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.\",\n ),\n})\nexport type CreateSwapQuoteInput = z.infer<typeof CreateSwapQuoteSchema>\n\nexport const SwapQuoteSchema = z.object({\n inputToken: AltTokenSchema,\n inputNetwork: NetworkSchema,\n inputAmount: z\n .number()\n .describe(\n 'The ceiling of `inputToken` the payer needs available to sign for, in whole units (not wei/base units) — 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 — never a separate step or a Klappay-side refund.',\n ),\n outputToken: TokenSchema.describe(\n \"Which of this charge's `acceptedPayments` tokens the swap resolves to.\",\n ),\n outputNetwork: NetworkSchema,\n outputAmount: z\n .number()\n .describe(\n \"The exact remaining amount owed on this charge (`amount - amountReceived`), in `currency` units — always what the merchant's split address receives, regardless of `inputAmount`.\",\n ),\n fees: z\n .object({\n klappayFee: z\n .number()\n .describe(\n \"Klappay's own swap fee (1% today), in `outputToken` units — paid by the payer, on top of `inputAmount`, separate from the merchant's own `feePercent`. Never subtracted from `outputAmount`.\",\n ),\n zeroExFee: z\n .number()\n .nullable()\n .describe(\n \"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` — Klappay never sees this fee, it goes straight to 0x.\",\n ),\n })\n .describe(\n 'Every fee the payer is charged for using swap-to-pay, broken out by who collects it — both already reflected in `inputAmount`, shown here separately for transparency. Neither ever reduces `outputAmount`.',\n ),\n expiresAt: z\n .string()\n .datetime()\n .describe(\n \"When this quote's price is no longer safely valid — 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 — submitting after it expires either reverts on-chain or simply gets re-quoted at the current price, never silently executes at a stale rate.\",\n ),\n transaction: z\n .object({\n to: z.string().describe(\"Contract address the payer's wallet must send this transaction to.\"),\n data: z.string().describe('Calldata — opaque, must be sent unmodified.'),\n value: z\n .string()\n .describe(\n 'Native currency (ETH/BNB/MATIC/AVAX) to attach, in wei — `\"0\"` when `inputToken` isn\\'t this network\\'s native currency.',\n ),\n })\n .describe(\n \"Pass this directly to the payer's wallet (e.g. viem/ethers `sendTransaction`) — 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.\",\n ),\n permit2: z\n .object({ eip712: z.record(z.unknown()) })\n .nullish()\n .describe(\n \"Present only when `inputToken` is an ERC-20 (today, only `BTC`) — 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/MATIC/AVAX) — `transaction` is then ready to sign and send directly, no extra step.\",\n ),\n})\nexport type SwapQuote = z.infer<typeof SwapQuoteSchema>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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Y,eAAe;AAAA,IACzB;AAAA,EACF;AAAA,EACA,cAAc,cAAc;AAAA,IAC1B;AAAA,EACF;AAAA,EACA,cAAc,eACX,OAAO,EACP,MAAM,uBAAuB,+BAA+B,EAC5D;AAAA,IACC;AAAA,EACF;AACJ,CAAC;AAGM,IAAM,kBAAkB,eAAE,OAAO;AAAA,EACtC,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,aAAa,eACV,OAAO,EACP;AAAA,IACC;AAAA,EACF;AAAA,EACF,aAAa,YAAY;AAAA,IACvB;AAAA,EACF;AAAA,EACA,eAAe;AAAA,EACf,cAAc,eACX,OAAO,EACP;AAAA,IACC;AAAA,EACF;AAAA,EACF,MAAM,eACH,OAAO;AAAA,IACN,YAAY,eACT,OAAO,EACP;AAAA,MACC;AAAA,IACF;AAAA,IACF,WAAW,eACR,OAAO,EACP,SAAS,EACT;AAAA,MACC;AAAA,IACF;AAAA,EACJ,CAAC,EACA;AAAA,IACC;AAAA,EACF;AAAA,EACF,WAAW,eACR,OAAO,EACP,SAAS,EACT;AAAA,IACC;AAAA,EACF;AAAA,EACF,aAAa,eACV,OAAO;AAAA,IACN,IAAI,eAAE,OAAO,EAAE,SAAS,oEAAoE;AAAA,IAC5F,MAAM,eAAE,OAAO,EAAE,SAAS,kDAA6C;AAAA,IACvE,OAAO,eACJ,OAAO,EACP;AAAA,MACC;AAAA,IACF;AAAA,EACJ,CAAC,EACA;AAAA,IACC;AAAA,EACF;AAAA,EACF,SAAS,eACN,OAAO,EAAE,QAAQ,eAAE,OAAO,eAAE,QAAQ,CAAC,EAAE,CAAC,EACxC,QAAQ,EACR;AAAA,IACC;AAAA,EACF;AACJ,CAAC;","names":["import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/environment.ts","../src/api-key-scopes.ts","../src/networks.ts","../src/networks.constants.ts","../src/pagination.ts","../src/tokens.ts","../src/tokens.constants.ts","../src/alt-tokens.ts","../src/alt-tokens.constants.ts","../src/charges.ts","../src/checkout-metadata.ts","../src/escrow.ts","../src/charge-check.ts","../src/confirmation-progress.ts","../src/distributions.ts","../src/metrics.ts","../src/webhook-events.ts","../src/webhooks.ts","../src/recipients.ts","../src/timeline.ts","../src/health.ts","../src/sandbox.ts","../src/capabilities.ts","../src/swap.ts"],"sourcesContent":["export * from './errors'\nexport * from './environment'\nexport * from './api-key-scopes'\nexport * from './networks'\nexport * from './pagination'\nexport * from './tokens'\nexport * from './alt-tokens'\nexport * from './charges'\nexport * from './charge-check'\nexport * from './confirmation-progress'\nexport * from './escrow'\nexport * from './checkout-metadata'\nexport * from './distributions'\nexport * from './metrics'\nexport * from './webhook-events'\nexport * from './webhook-event-data'\nexport * from './webhooks'\nexport * from './recipients'\nexport * from './timeline'\nexport * from './health'\nexport * from './sandbox'\nexport * from './capabilities'\nexport * from './swap'\n","import { z } from 'zod'\n\nexport const ErrorPayloadSchema = z.object({\n error: z.object({\n code: z\n .string()\n .describe(\n 'A stable, machine-readable error identifier (e.g. `validation_error`, `charge_not_found`).',\n ),\n message: z\n .string()\n .describe(\n 'Human-readable explanation, safe to log or show a developer — not meant for end users.',\n ),\n param: z\n .string()\n .optional()\n .describe('Which request field the error refers to, when applicable.'),\n }),\n})\n\nexport type ErrorPayload = z.infer<typeof ErrorPayloadSchema>\n","import { z } from 'zod'\n\nexport const EnvironmentSchema = z\n .enum(['live', 'test'])\n .describe(\n '`live` or `test`, matching the `klap_live_.../klap_test_...` prefix of the API key that created or is scoped to this resource. `live` settles on Base mainnet with real funds; `test` settles on Base Sepolia, a separate testnet — real on-chain activity, but never real money.',\n )\nexport type Environment = z.infer<typeof EnvironmentSchema>\n","import { z } from 'zod'\n\nexport const ApiKeyScopeSchema = z\n .enum([\n 'charges:read',\n 'charges:write',\n 'webhooks:read',\n 'webhooks:write',\n 'webhooks:manage_secret',\n 'metrics:read',\n 'metrics:charges:read',\n 'metrics:transactions:read',\n 'metrics:distributions:read',\n 'sandbox:trigger',\n 'charges:split_write',\n 'recipients:read',\n 'recipients:write',\n 'recipients:manage_payout',\n ])\n .describe(\n \"What an API key is allowed to do, independent of `tenantId`/`environment` (which scope *whose* data, not *what actions*). A key with none of these can still authenticate but every scoped route rejects it with `403 insufficient_scope`. `metrics:read` alone grants every metrics resource; `metrics:{resource}:read` grants only that one — a key can hold either or both. `charges:split_write` is required on top of `charges:write` whenever a charge request includes `splitRecipients` — a key without it can create ordinary charges but never redirect part of the payout. `recipients:write` registers/revokes recipients (addresses eligible to be *referenced* in a split); `recipients:manage_payout` is separate and strictly more sensitive — it is what lets a recipient actually become an API key's `payoutAddress`, and should be granted only to a key that already went through out-of-band approval for that (Dashboard's own internal key, never a merchant-facing or third-party integration key like a marketplace's). `charges:split_write` can never be combined with `recipients:write`/`recipients:manage_payout` on the same key (see `CONFLICTING_SCOPE_PAIRS`) — Core rejects such a key outright, before any route runs.\",\n )\nexport type ApiKeyScope = z.infer<typeof ApiKeyScopeSchema>\nexport const API_KEY_SCOPES = ApiKeyScopeSchema.options\n\nexport const CONFLICTING_SCOPE_PAIRS: ReadonlyArray<readonly [ApiKeyScope, ApiKeyScope]> = [\n ['charges:split_write', 'recipients:write'],\n ['charges:split_write', 'recipients:manage_payout'],\n]\n\nexport function findConflictingScopes(\n scopes: readonly ApiKeyScope[],\n): readonly [ApiKeyScope, ApiKeyScope] | null {\n const held = new Set(scopes)\n for (const [a, b] of CONFLICTING_SCOPE_PAIRS) {\n if (held.has(a) && held.has(b)) return [a, b]\n }\n return null\n}\n","import { z } from 'zod'\n\nexport const NetworkSchema = z\n .enum(['base', 'optimism', 'polygon', 'ethereum', 'arbitrum', 'avalanche', 'bnb'])\n .describe('The blockchain a charge/payment is on.')\n\nexport type Network = z.infer<typeof NetworkSchema>\n\nexport * from './networks.constants'\n","import type { Environment } from './environment'\nimport type { Network } from './networks'\n\nexport const NETWORK_LABELS: Record<Network, string> = {\n base: 'Base',\n optimism: 'Optimism',\n polygon: 'Polygon',\n ethereum: 'Ethereum',\n arbitrum: 'Arbitrum',\n avalanche: 'Avalanche',\n bnb: 'BNB Chain',\n}\n\nexport const NETWORK_EXPLORERS: Record<Network, string> = {\n base: 'https://basescan.org',\n optimism: 'https://optimistic.etherscan.io',\n polygon: 'https://polygonscan.com',\n ethereum: 'https://etherscan.io',\n arbitrum: 'https://arbiscan.io',\n avalanche: 'https://snowtrace.io',\n bnb: 'https://bscscan.com',\n}\n\nexport const EVM_NETWORKS = [\n 'base',\n 'optimism',\n 'polygon',\n 'ethereum',\n 'arbitrum',\n 'avalanche',\n 'bnb',\n] as const\nexport type EvmNetwork = (typeof EVM_NETWORKS)[number]\n\nexport const OPERATIONAL_NETWORKS = [\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'ethereum',\n 'avalanche',\n 'bnb',\n] as const\nexport type OperationalNetwork = (typeof OPERATIONAL_NETWORKS)[number]\n\nexport const CHAIN_IDS: Record<EvmNetwork, Partial<Record<Environment, number>>> = {\n base: { live: 8453, test: 84532 },\n optimism: { live: 10, test: 11155420 },\n ethereum: { live: 1, test: 11155111 },\n polygon: { live: 137 },\n arbitrum: { live: 42161 },\n avalanche: { live: 43114 },\n bnb: { live: 56 },\n}\n","import { z } from 'zod'\n\nexport const PAGINATION_LIMIT_MIN = 1\nexport const PAGINATION_LIMIT_MAX = 100\nexport const PAGINATION_LIMIT_DEFAULT = 20\n\nexport const PaginationQuerySchema = z.object({\n limit: z.coerce\n .number()\n .min(PAGINATION_LIMIT_MIN)\n .max(PAGINATION_LIMIT_MAX)\n .default(PAGINATION_LIMIT_DEFAULT)\n .describe(\n `Max items to return per page (${PAGINATION_LIMIT_MIN}–${PAGINATION_LIMIT_MAX}, default ${PAGINATION_LIMIT_DEFAULT}).`,\n ),\n cursor: z\n .string()\n .max(500)\n .optional()\n .describe(\n \"Opaque — 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.\",\n ),\n})\n\nexport type PaginationQuery = z.infer<typeof PaginationQuerySchema>\n\nexport type PaginationQueryRequest = z.input<typeof PaginationQuerySchema>\n\nexport function paginatedSchema<T extends z.ZodTypeAny>(itemSchema: T) {\n return z.object({\n data: z.array(itemSchema),\n nextCursor: z\n .string()\n .nullable()\n .describe('Pass as `cursor` to fetch the next page. `null` when there are no more results.'),\n hasMore: z.boolean(),\n })\n}\n","import { z } from 'zod'\nimport { OPERATIONAL_NETWORKS } from './networks'\n\nexport const TokenSchema = z\n .enum(['USDC', 'USDT'])\n .describe(\n `Which stablecoin the payer will send. Support depends on both \\`network\\` and \\`environment\\` — not every token/network/environment combination is deployed; today, both \\`USDC\\` and \\`USDT\\` are deployed on every operational network's \\`live\\` side except BNB Chain (\\`${OPERATIONAL_NETWORKS.join(', ')}\\`), but \\`test\\` coverage varies per network — Base, Optimism, and Ethereum each have a \\`test\\` environment (\\`USDC\\` only; none has an official Sepolia USDT), Arbitrum, Polygon, Avalanche, and BNB Chain have none yet (0xSplits hasn't deployed on Arbitrum Sepolia and has no Polygon, Avalanche Fuji, or BNB testnet support at all). An unconfigured combination is rejected with \\`422 token_not_supported\\`, not silently accepted. **BNB Chain's \\`USDC\\` address is Binance-Peg USDC, not an official Circle deployment** — Circle does not issue native USDC on BNB Chain at all; this is a Binance-custodied, 1:1-pegged BEP-20 token, a materially different trust model than every other \\`TOKEN_ADDRESSES\\` entry (all verified directly against their real issuer). Accepted at the payer's own risk — Klappay does not verify or guarantee Binance's collateral backing it. \\`USDT\\` on BNB Chain is Tether's own official issuance, same trust model as everywhere else. More tokens/networks are expected to be added over time — check \\`TOKEN_ADDRESSES\\` in \\`@klappay/types\\` (or a future \\`GET /v1/networks\\` capabilities endpoint) for the exact current matrix rather than assuming full coverage.`,\n )\nexport type Token = z.infer<typeof TokenSchema>\n\nexport * from './tokens.constants'\n","import type { Environment } from './environment'\nimport type { Network } from './networks'\nimport type { Token } from './tokens'\n\nexport const TOKEN_DECIMALS = 6\n\nexport const TOKEN_ADDRESSES: Record<\n Token,\n Partial<Record<Network, Partial<Record<Environment, `0x${string}`>>>>\n> = {\n USDC: {\n base: {\n live: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n test: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n },\n optimism: {\n live: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n test: '0x5fd84259d66Cd46123540766Be93DFE6D43130D7',\n },\n polygon: { live: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359' },\n ethereum: {\n live: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n test: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',\n },\n arbitrum: { live: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831' },\n avalanche: { live: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E' },\n bnb: { live: '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d' },\n },\n USDT: {\n base: { live: '0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2' },\n optimism: { live: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58' },\n polygon: { live: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F' },\n ethereum: { live: '0xdAC17F958D2ee523a2206206994597C13D831ec7' },\n arbitrum: { live: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9' },\n avalanche: { live: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7' },\n bnb: { live: '0x55d398326f99059fF775485246999027B3197955' },\n },\n}\n","import { z } from 'zod'\nimport { ALT_TOKEN_ADDRESSES } from './alt-tokens.constants'\nimport { NetworkSchema } from './networks'\nimport type { Network } from './networks'\n\nexport * from './alt-tokens.constants'\n\nexport const AltTokenSchema = z\n .enum(['ETH', 'BNB', 'MATIC', 'AVAX', 'BTC'])\n .describe(\n \"A non-stablecoin cryptocurrency Klappay trusts as swap input for a charge, via the 0x Swap API — 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`) — never assume every value here is available on every network.\",\n )\nexport type AltToken = z.infer<typeof AltTokenSchema>\n\nexport const SwapAlternativeSchema = z.object({\n token: AltTokenSchema,\n network: NetworkSchema.describe(\n 'Which network to send `token` on — 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.',\n ),\n})\nexport type SwapAlternative = z.infer<typeof SwapAlternativeSchema>\n\nexport function listSwapAlternatives(networks: readonly Network[]): SwapAlternative[] {\n const alternatives: SwapAlternative[] = []\n for (const network of new Set(networks)) {\n for (const token of Object.keys(ALT_TOKEN_ADDRESSES[network] ?? {})) {\n alternatives.push({ token: token as AltToken, network })\n }\n }\n return alternatives\n}\n","import type { AltToken } from './alt-tokens'\nimport type { Network } from './networks'\n\nexport const ALT_TOKEN_DECIMALS: Record<AltToken, number> = {\n ETH: 18,\n BNB: 18,\n MATIC: 18,\n AVAX: 18,\n BTC: 8,\n}\n\nexport const ALT_TOKEN_ADDRESSES: Record<\n Network,\n Partial<Record<AltToken, 'native' | `0x${string}`>>\n> = {\n base: { ETH: 'native', BTC: '0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf' },\n optimism: { ETH: 'native', BTC: '0x68f180fcCe6836688e9084f035309E29Bf0A2095' },\n ethereum: { ETH: 'native', BTC: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599' },\n arbitrum: { ETH: 'native', BTC: '0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f' },\n polygon: { MATIC: 'native', BTC: '0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6' },\n avalanche: { AVAX: 'native' },\n bnb: { BNB: 'native' },\n}\n","import { z } from 'zod'\nimport { SwapAlternativeSchema } from './alt-tokens'\nimport { MetadataWithKlappaySchema } from './checkout-metadata'\nimport { EnvironmentSchema } from './environment'\nimport { EscrowConfigSchema } from './escrow'\nimport { NetworkSchema, OPERATIONAL_NETWORKS } from './networks'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\nimport { TokenSchema } from './tokens'\n\nexport const ChargeStatusSchema = z\n .enum(['pending', 'partially_paid', 'confirmed', 'expired', 'underpaid'])\n .describe(\n '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 — see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. Every status is reached automatically, on its own timeline — there is no merchant-initiated cancellation. This never reflects whether funds actually reached the merchant — see `settlementStatus` for that.',\n )\n\nexport type ChargeStatus = z.infer<typeof ChargeStatusSchema>\n\nexport const SettlementStatusSchema = z\n .enum(['pending', 'completed', 'failed'])\n .describe(\n \"Progress of the payout to the merchant's wallet, a separate step from `status` — `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 — nothing has been received, or the charge is still in progress.\",\n )\nexport type SettlementStatus = z.infer<typeof SettlementStatusSchema>\n\nexport const ChargeFeePayerSchema = z\n .enum(['merchant', 'payer'])\n .describe(\n \"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 — 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 — 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.\",\n )\nexport type ChargeFeePayer = z.infer<typeof ChargeFeePayerSchema>\n\nexport const CHARGE_EXPIRES_IN_MIN_SECONDS = 60\nexport const CHARGE_EXPIRES_IN_MAX_SECONDS = 3600\n\nexport const CHARGE_ACCEPTED_PAYMENTS_MAX = 14\n\nexport const AcceptedPaymentSchema = z.object({\n token: TokenSchema,\n network: NetworkSchema,\n})\nexport type AcceptedPayment = z.infer<typeof AcceptedPaymentSchema>\n\nconst AcceptedPaymentsSchema = z\n .array(AcceptedPaymentSchema)\n .min(1, 'At least one accepted payment is required.')\n .max(CHARGE_ACCEPTED_PAYMENTS_MAX)\n .superRefine((pairs, ctx) => {\n const seen = new Set<string>()\n pairs.forEach((pair, index) => {\n const key = `${pair.token}:${pair.network}`\n if (seen.has(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,\n path: [index],\n })\n }\n seen.add(key)\n if (!(OPERATIONAL_NETWORKS as readonly string[]).includes(pair.network)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Network \"${pair.network}\" isn't live yet — only ${OPERATIONAL_NETWORKS.join(', ')} today.`,\n path: [index, 'network'],\n })\n }\n })\n })\n .describe(\n `Every \\`(token, network)\\` pair the payer is allowed to pay with — 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\\`) — 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 — 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) — an unconfigured \\`(token, network)\\` combination for your environment is rejected with \\`422 token_not_supported\\`.`,\n )\n\nexport const CHARGE_SPLIT_RECIPIENTS_MAX = 5\n\nexport const SplitRecipientSchema = z.object({\n address: z\n .string()\n .regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address')\n .describe('EVM address to send a slice of this charge to.'),\n percent: z\n .number()\n .positive()\n .max(100)\n .describe(\n \"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 — see `docs/payments.md`'s \\\"Settling the payout\\\" section for the exact math.\",\n ),\n label: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Free-form label for your own bookkeeping (e.g. `\"supplier\"`, `\"sales rep\"`) — echoed back unchanged, never interpreted by Klappay.',\n ),\n})\nexport type SplitRecipient = z.infer<typeof SplitRecipientSchema>\n\n// Response-only shape (echoed on `Charge.splitRecipients`) — the resolved\n// address, not the `recipientId` that was submitted, so a merchant reading\n// their own charge back can actually see where the money went without a\n// second lookup. `CreateChargeSchema` below never accepts this shape\n// directly; see `SplitRecipientInputSchema`.\n\nexport const SplitRecipientInputSchema = z.object({\n recipientId: z\n .string()\n .describe(\n 'id of a `Recipient` you already registered via `POST /v1/recipients` (not a raw address) — 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.',\n ),\n percent: z\n .number()\n .positive()\n .max(100)\n .describe(\n \"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 — see `docs/payments.md`'s \\\"Settling the payout\\\" section for the exact math.\",\n ),\n label: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Free-form label for your own bookkeeping (e.g. `\"supplier\"`, `\"sales rep\"`) — echoed back unchanged, never interpreted by Klappay. Independent of the label the recipient was registered with.',\n ),\n})\nexport type SplitRecipientInput = z.infer<typeof SplitRecipientInputSchema>\n\nconst SplitRecipientsInputSchema = z\n .array(SplitRecipientInputSchema)\n .max(CHARGE_SPLIT_RECIPIENTS_MAX)\n .superRefine((recipients, ctx) => {\n const seen = new Set<string>()\n recipients.forEach((recipient, index) => {\n if (seen.has(recipient.recipientId)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate split recipientId: ${recipient.recipientId}.`,\n path: [index, 'recipientId'],\n })\n }\n seen.add(recipient.recipientId)\n })\n })\n .describe(\n `Optional extra recipients for this charge's split — e.g. a supplier or the sales rep who closed the deal — 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) — a request that doesn't is rejected with \\`422 split_recipients_exceed_available_percent\\`.`,\n )\n\nexport const CHARGE_AMOUNT_MAX = 999_999_999_999\n\nexport const CreateChargeSchema = z.object({\n amount: z\n .number()\n .positive()\n .max(CHARGE_AMOUNT_MAX)\n .describe(\n \"Amount to charge, in `currency` units (e.g. `49.9` = $49.90) — up to 6 decimal places; anything more precise is silently truncated. Required — 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 — the response's `amount` is grossed up to cover `feePercent`, while `merchantAmount` on the response echoes back this exact value.\",\n ),\n feePayer: ChargeFeePayerSchema.optional().default('merchant'),\n currency: z\n .literal('USD')\n .default('USD')\n .describe('Always `USD` today — the only supported currency.'),\n acceptedPayments: AcceptedPaymentsSchema,\n expiresIn: z\n .number()\n .int()\n .min(CHARGE_EXPIRES_IN_MIN_SECONDS)\n .max(CHARGE_EXPIRES_IN_MAX_SECONDS)\n .describe(\n 'Seconds, not minutes or milliseconds — how long the charge stays open before it expires. Required, min 60, max 3600 (60 minutes) — 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.',\n ),\n idempotencyKey: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe(\n 'Scoped to your tenant. Replaying the same key with the exact same request body returns the original charge unchanged instead of creating a duplicate — 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.',\n ),\n externalRef: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe(\n 'An opaque correlation id from your own system (e.g. an order id) — echoed back on the charge and in every webhook payload. Not interpreted or validated by Klappay.',\n ),\n source: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe(\n 'Free-form label for what created this charge (e.g. `\"checkout\"`, `\"invoice\"`) — 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.',\n ),\n metadata: MetadataWithKlappaySchema.optional(),\n redirectUrl: z\n .string()\n .url()\n .refine((value) => /^https?:\\/\\//.test(value), 'must use http or https')\n .optional()\n .describe(\n \"Where to send the payer once this charge resolves, if you use Klappay's hosted checkout page (see `checkoutUrl` on the read shape) — ignored otherwise. Must be `http(s)` — 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.\",\n ),\n splitRecipients: SplitRecipientsInputSchema.optional(),\n escrow: EscrowConfigSchema.optional().describe(\n \"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 — 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.\",\n ),\n})\n\nexport type CreateChargeInput = z.infer<typeof CreateChargeSchema>\n\nexport type CreateChargeRequest = z.input<typeof CreateChargeSchema>\n\nexport const ChargeSchema = z.object({\n id: z\n .string()\n .describe('Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later.'),\n amount: z\n .number()\n .describe(\n \"The exact total the payer must send, in `currency` units (up to 6 decimal places). With `feePayer: 'merchant'` (the default) this is exactly what you requested at creation. With `feePayer: 'payer'` this is grossed up to cover `feePercent` — see `merchantAmount` for what you requested/will actually net.\",\n ),\n feePayer: ChargeFeePayerSchema,\n feePercent: z\n .number()\n .describe(\n \"Klappay's fee for this charge, as a percent of `amount` (e.g. `2` = 2%) — includes any escrow surcharge if this charge is an escrow. Frozen at creation; see `feeAmount`/`merchantAmount` for the actual amounts this works out to.\",\n ),\n feeAmount: z\n .number()\n .describe(\"`amount * feePercent / 100`, in `currency` units — Klappay's cut of this charge.\"),\n merchantAmount: z\n .number()\n .describe(\n '`amount - feeAmount`, in `currency` units — 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).',\n ),\n amountReceived: z\n .number()\n .nullable()\n .describe(\n '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` — see `isOverpaid`.',\n ),\n isOverpaid: z\n .boolean()\n .describe(\n '`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically — see the docs for why.',\n ),\n currency: z.string().describe('Always `USD` today — the only supported currency.'),\n acceptedPayments: z\n .array(AcceptedPaymentSchema)\n .describe(\n 'Every `(token, network)` pair this charge was configured to accept, unchanged after creation.',\n ),\n paidWith: z\n .array(AcceptedPaymentSchema)\n .describe(\n 'Every distinct `(token, network)` pair that has actually contributed a credited transfer so far — 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`.',\n ),\n swapAlternatives: z\n .array(SwapAlternativeSchema)\n .describe(\n \"Every `(token, network)` pair the payer can pay with instead, via `POST /v1/charges/{id}/quote` — 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 — 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 — `POST /v1/charges/{id}/quote` always rejects a test-environment charge with `422 swap_test_environment_unsupported`).\",\n ),\n address: z\n .string()\n .describe(\n 'The on-chain address the payer must send funds to — identical across every accepted network (0xSplits addresses are chain-agnostic). Unique per charge, predicted at creation time — funds sent here go directly to the merchant, Klappay never custodies them.',\n ),\n status: ChargeStatusSchema,\n settlementStatus: SettlementStatusSchema.nullable(),\n environment: EnvironmentSchema,\n apiKeyId: z\n .string()\n .nullable()\n .describe(\n 'Which of your API keys created this charge. `null` for a charge created before this field existed.',\n ),\n txHash: z\n .string()\n .nullable()\n .describe(\n 'Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected.',\n ),\n externalRef: z.string().nullable(),\n source: z.string().nullable(),\n metadata: MetadataWithKlappaySchema.nullable(),\n redirectUrl: z\n .string()\n .nullable()\n .describe('Echoes the `redirectUrl` set at creation, if any. `null` if none was set.'),\n checkoutUrl: z\n .string()\n .nullable()\n .describe(\n \"Link to Klappay's hosted checkout page for this charge. `null` if this deployment has no hosted checkout configured — build your own payment UI from `address`/`acceptedPayments` instead.\",\n ),\n splitRecipients: z\n .array(SplitRecipientSchema)\n .describe('Echoes whatever extra split recipients were set at creation — empty array if none.'),\n createdAt: z.string().datetime(),\n expiresAt: z\n .string()\n .datetime()\n .describe(\n 'When this charge stops accepting payment, if still `pending`/`partially_paid` by then.',\n ),\n confirmedAt: z\n .string()\n .datetime()\n .nullable()\n .describe('When `status` first reached `confirmed`. `null` until then.'),\n settledAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n \"When `settlementStatus` first reached `completed` — the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`.\",\n ),\n lastActivityAt: z\n .string()\n .datetime()\n .describe(\n 'When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet.',\n ),\n escrow: z\n .object({\n releaserAddress: z\n .string()\n .describe('The only address that can ever release this escrow — never Klappay.'),\n releasedAt: z\n .string()\n .datetime()\n .nullable()\n .describe('When the release actually executed on-chain. `null` until then.'),\n refundedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When the refund actually executed on-chain. `null` until then. Mutually exclusive with `releasedAt` — an escrow can only ever be released or refunded once, never both.',\n ),\n })\n .nullable()\n .describe(\n 'Present only when this charge was created as an escrow (see `escrow` on the create request) — `null` for a normal charge.',\n ),\n})\n\nexport type Charge = z.infer<typeof ChargeSchema>\n\nexport const ListChargesSchema = z\n .object({\n status: ChargeStatusSchema.optional(),\n token: TokenSchema.optional().describe(\n 'Filters on `paidWith.token` — the pair actually paid, not accepted.',\n ),\n network: NetworkSchema.optional().describe(\n 'Filters on `paidWith.network` — the pair actually paid, not accepted.',\n ),\n environment: EnvironmentSchema.optional(),\n since: z\n .string()\n .datetime()\n .optional()\n .describe(\n '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.',\n ),\n isOverpaid: z\n .enum(['true', 'false'])\n .transform((v) => v === 'true')\n .optional(),\n })\n .extend(PaginationQuerySchema.shape)\n\nexport type ListChargesInput = z.infer<typeof ListChargesSchema>\n\nexport type ListChargesRequest = z.input<typeof ListChargesSchema>\n\nexport const PaginatedChargesSchema = paginatedSchema(ChargeSchema)\n\nexport type PaginatedCharges = z.infer<typeof PaginatedChargesSchema>\n\nexport const GetChargeQrCodeQuerySchema = z.object({\n token: TokenSchema.optional().describe(\n 'Which accepted `(token, network)` pair to encode in the QR — 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.',\n ),\n network: NetworkSchema.optional(),\n})\n\nexport type GetChargeQrCodeQuery = z.infer<typeof GetChargeQrCodeQuerySchema>\n\nexport type GetChargeQrCodeQueryRequest = z.input<typeof GetChargeQrCodeQuerySchema>\n","import { z } from 'zod'\n\nexport const CHECKOUT_PRODUCTS_MAX = 20\n\nexport const CheckoutProductSchema = z.object({\n name: z\n .string()\n .min(1)\n .max(200)\n .describe('What the payer is buying, shown as-is on the hosted checkout page.'),\n quantity: z\n .number()\n .int()\n .positive()\n .max(9999)\n .optional()\n .describe('How many of this item. Omit for a single, unquantified item.'),\n imageUrl: z\n .string()\n .url()\n .max(2048)\n .refine((value) => /^https?:\\/\\//.test(value), 'must use http or https')\n .optional()\n .describe(\n \"Product image, fetched only by the payer's own browser — Klappay never fetches it server-side. Must be `http(s)`.\",\n ),\n})\nexport type CheckoutProduct = z.infer<typeof CheckoutProductSchema>\n\nexport const KlappayCheckoutMetadataSchema = z\n .object({\n products: z\n .array(CheckoutProductSchema)\n .max(CHECKOUT_PRODUCTS_MAX)\n .optional()\n .describe(\n `What the payer is buying, shown on the hosted checkout page — up to ${CHECKOUT_PRODUCTS_MAX} items. Purely informational: never validated against \\`amount\\`, never used by any payment or distribution logic.`,\n ),\n })\n .describe(\n 'Reserved for Klappay — 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.',\n )\nexport type KlappayCheckoutMetadata = z.infer<typeof KlappayCheckoutMetadataSchema>\n\nexport const MetadataWithKlappaySchema = z\n .object({ klappay: KlappayCheckoutMetadataSchema.optional() })\n .catchall(z.unknown())\n .describe(\n 'Arbitrary key/value data, returned as-is on every read. Put whatever you want in here — 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`.',\n )\n","import { z } from 'zod'\n\nexport const EscrowConfigSchema = z.object({\n releaserAddress: z\n .string()\n .regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address')\n .optional()\n .describe(\n \"The only address ever authorized to release this charge's escrowed funds — 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` — 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 — any well-formed address is accepted, since Klappay never custodies these funds.\",\n ),\n})\nexport type EscrowConfig = z.infer<typeof EscrowConfigSchema>\n\nexport const ReleaseEscrowRequestSchema = z.object({\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'must be hex-encoded signature bytes')\n .describe(\n \"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` — 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 — 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 — the Safe contract itself rejects a signature that isn't from `escrowReleaserAddress`, never trusted at face value by Klappay.\",\n ),\n})\nexport type ReleaseEscrowRequest = z.infer<typeof ReleaseEscrowRequestSchema>\n\nexport const RefundEscrowRequestSchema = z.object({\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'must be hex-encoded signature bytes')\n .describe(\n \"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` — 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 — 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 — the Safe contract itself rejects a signature that isn't from `escrowReleaserAddress`, never trusted at face value by Klappay.\",\n ),\n})\nexport type RefundEscrowRequest = z.infer<typeof RefundEscrowRequestSchema>\n","import { z } from 'zod'\nimport { ChargeSchema } from './charges'\nimport { ConfirmationProgressSchema } from './confirmation-progress'\nimport { NetworkSchema } from './networks'\n\nexport const CheckChargeRequestSchema = z\n .object({\n txHash: z\n .string()\n .regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 32-byte transaction hash')\n .optional()\n .describe(\n \"The on-chain transaction hash to verify directly, if you already have it — 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 — whatever this transaction actually contains on-chain is what gets credited, regardless of any amount/token implied elsewhere.\",\n ),\n network: NetworkSchema.optional().describe(\n \"Which network `txHash` is on — required together with `txHash`, since a transaction hash alone doesn't identify a chain. Must be one of the networks this charge actually accepts payment on, or `422 payment_pair_not_accepted`.\",\n ),\n })\n .refine((data) => Boolean(data.txHash) === Boolean(data.network), {\n message: '`txHash` and `network` must be provided together, or both omitted',\n })\nexport type CheckChargeRequest = z.infer<typeof CheckChargeRequestSchema>\n\nexport const CheckChargeResponseSchema = ChargeSchema.extend({\n transactionSender: z\n .string()\n .nullable()\n .describe(\n \"The `txHash` transaction's own sender (`from`) — 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 — a hint-less background scan, an unaccepted network, or a not-found/reverted transaction all leave this `null`.\",\n ),\n confirmationProgress: ConfirmationProgressSchema.nullable().describe(\n \"Present when this check found a real matching transfer on-chain that has not yet reached its network's required confirmation depth — use it to render a progress bar while waiting. `null` when nothing new was found, when the charge is already terminal (this check short-circuits with no RPC call), or once the transfer is deep enough to have already been credited (the charge's own `status` field is the signal for that, not this one).\",\n ),\n})\nexport type CheckChargeResponse = z.infer<typeof CheckChargeResponseSchema>\n","import { z } from 'zod'\nimport { NetworkSchema } from './networks'\n\nexport const ConfirmationProgressSchema = z\n .object({\n network: NetworkSchema.describe('Which network the transfer was seen on.'),\n blocksSeen: z\n .number()\n .int()\n .min(0)\n .describe(\n \"How many blocks have passed since the transfer's own block, as of this update — a raw block count, not seconds. Grows toward `blocksRequired` as the network's blocks keep arriving.\",\n ),\n blocksRequired: z\n .number()\n .int()\n .min(1)\n .describe(\n \"This network's minimum confirmation depth (a fixed, per-network constant) — the transfer is only credited once `blocksSeen` reaches this value.\",\n ),\n percent: z\n .number()\n .int()\n .min(0)\n .max(99)\n .describe(\n '`blocksSeen`/`blocksRequired` as a rounded-down 0-99 percentage, for a progress bar. Never reaches 100 by construction — 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).',\n ),\n })\n .describe(\n \"How close an already-detected transfer is to being trusted as final and credited, before its network's minimum confirmation depth is reached (see `docs/payments.md`'s \\\"Confirmation depth\\\" section). Only ever present for a transfer that's been seen on-chain but isn't deep enough yet — absent/null once it's credited (the charge's own status change is what signals that) or if nothing has been detected at all.\",\n )\n\nexport type ConfirmationProgress = z.infer<typeof ConfirmationProgressSchema>\n","import { z } from 'zod'\nimport { NetworkSchema } from './networks'\nimport { PAGINATION_LIMIT_MAX, paginatedSchema } from './pagination'\nimport { TokenSchema } from './tokens'\n\nexport const SplitDistributionStatusSchema = z\n .enum(['pending', 'processing', 'completed', 'failed'])\n .describe(\n \"Status of one payout attempt to the merchant, for a single `(token, network)` pair — 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.\",\n )\nexport type SplitDistributionStatus = z.infer<typeof SplitDistributionStatusSchema>\n\nexport const PendingDistributionRecipientSchema = z.object({\n address: z.string().describe('On-chain recipient address.'),\n percentAllocation: z\n .number()\n .describe(\"This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).\"),\n})\n\nexport const PendingDistributionSchema = z.object({\n splitAddress: z.string().describe('The on-chain 0xSplits address to call `distribute()` on.'),\n network: NetworkSchema,\n token: TokenSchema,\n recipients: z\n .array(PendingDistributionRecipientSchema)\n .describe(\n 'The exact recipient list to pass to `distribute()` — 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.',\n ),\n distributorFeePercent: z\n .number()\n .describe(\n '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.',\n ),\n estimatedRewardAmount: z\n .number()\n .describe(\n \"Estimate only, in the charge's `currency` units, based on the amount Klappay detected on-chain — 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.\",\n ),\n availableSince: z\n .string()\n .datetime()\n .describe('When this distribution entered its grace period.'),\n graceEndsAt: z\n .string()\n .datetime()\n .describe(\n \"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.\",\n ),\n})\n\nexport type PendingDistribution = z.infer<typeof PendingDistributionSchema>\n\nexport const PaginatedPendingDistributionsSchema = paginatedSchema(PendingDistributionSchema)\n\nexport type PaginatedPendingDistributions = z.infer<typeof PaginatedPendingDistributionsSchema>\n\nexport const ListenPendingDistributionsQuerySchema = z.object({\n limit: z.coerce\n .number()\n .int()\n .min(0)\n .max(PAGINATION_LIMIT_MAX)\n .default(0)\n .describe(\n \"How many currently-claimable distributions to emit as an initial snapshot right after connecting — each as a synthetic `distribution.available` event — 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 — 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.\",\n ),\n})\n\nexport type ListenPendingDistributionsQuery = z.infer<typeof ListenPendingDistributionsQuerySchema>\n\nexport const PendingDistributionEventSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('distribution.available'),\n distribution: PendingDistributionSchema,\n }),\n z.object({\n type: z.literal('distribution.claimed'),\n splitAddress: z\n .string()\n .describe('No longer claimable — either settled by someone, or picked up by the worker.'),\n }),\n])\n\nexport type PendingDistributionEvent = z.infer<typeof PendingDistributionEventSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\n\nexport const MetricsResourceSchema = z\n .enum(['charges', 'transactions', 'distributions'])\n .describe(\n 'Which underlying dataset to query. `charges`: one row per charge. `transactions`: one row per detected on-chain transfer — 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.',\n )\nexport type MetricsResource = z.infer<typeof MetricsResourceSchema>\n\nexport const MetricsAggregationSchema = z\n .enum(['count', 'sum', 'avg', 'min', 'max'])\n .describe(\n '`count` counts matching rows and never takes `field`. `sum`/`avg`/`min`/`max` require `field` to be set to one of the resource’s numeric fields.',\n )\nexport type MetricsAggregation = z.infer<typeof MetricsAggregationSchema>\n\nexport const MetricsFilterOperatorSchema = z\n .enum(['eq', 'neq', 'in', 'gt', 'gte', 'lt', 'lte'])\n .describe(\n '`in` expects an array value (max 50 entries); every other operator expects a single scalar.',\n )\nexport type MetricsFilterOperator = z.infer<typeof MetricsFilterOperatorSchema>\n\nexport const MetricsDateGranularitySchema = z\n .enum(['day', 'week', 'month', 'year'])\n .describe(\n 'Bucket width for a `date_bucket` `groupBy` entry — Postgres `date_trunc` semantics (UTC).',\n )\nexport type MetricsDateGranularity = z.infer<typeof MetricsDateGranularitySchema>\n\nconst metricsQueryEnvironmentSchema = EnvironmentSchema.describe(\n \"Which environment's data to query — `live` or `test`. Must match the environment of the API key used to authenticate — scopes the query to charges/transactions/distributions created under a `live` or `test` API key respectively.\",\n)\n\nexport const MAX_METRICS_QUERY_DATE_RANGE_DAYS = 366\nexport const METRICS_QUERY_MAX_ROW_LIMIT = 1000\nexport const METRICS_QUERY_DEFAULT_ROW_LIMIT = 100\nexport const METRICS_QUERY_MAX_GROUP_BY = 3\nexport const METRICS_QUERY_MAX_FILTERS = 20\nexport const METRICS_QUERY_MAX_METRICS = 10\n\nconst METRIC_ALIAS_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\nconst metricAliasSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(\n METRIC_ALIAS_PATTERN,\n 'Must start with a letter or underscore, and contain only letters, digits, and underscores — this becomes a SQL column alias.',\n )\n .optional()\n\nconst MetricsFilterValueSchema = z.union([\n z.string().max(255),\n z.number(),\n z.boolean(),\n z\n .array(z.union([z.string().max(255), z.number()]))\n .min(1)\n .max(50),\n])\n\nconst orderBySchema = z\n .object({\n key: z\n .string()\n .min(1)\n .max(64)\n .regex(\n METRIC_ALIAS_PATTERN,\n 'Must start with a letter or underscore, and contain only letters, digits, and underscores — every valid output column name already looks like this.',\n )\n .describe(\n 'An output column name from this same query — either a `groupBy` field name, or a metric’s `alias` (or its default name: `${aggregation}` for `count`, `${aggregation}_${field}` otherwise, e.g. `sum_amount`). Must match `^[a-zA-Z_][a-zA-Z0-9_]*$` — every real output column name already does, so this only ever rejects a value that could never have been one.',\n ),\n direction: z.enum(['asc', 'desc']),\n })\n .describe(\n 'Sort the result rows by any output column — 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.',\n )\n\nconst limitSchema = z\n .number()\n .int()\n .min(1)\n .max(METRICS_QUERY_MAX_ROW_LIMIT)\n .default(METRICS_QUERY_DEFAULT_ROW_LIMIT)\n .describe(\n `Max rows to return, ${1}–${METRICS_QUERY_MAX_ROW_LIMIT}, default ${METRICS_QUERY_DEFAULT_ROW_LIMIT}. If more rows matched, \\`meta.truncated\\` is \\`true\\` on the response — narrow the query instead of just raising this.`,\n )\n\nexport const ChargesQueryFieldSchema = z\n .enum([\n 'status',\n 'source',\n 'apiKeyId',\n 'currency',\n 'isOverpaid',\n 'externalRef',\n 'escrowReleaserAddress',\n ])\n .describe(\n \"A `Charge` field to filter or group by — 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 — filter `escrowReleaserAddress` with operator `neq`/value `null` to isolate escrow-configured charges (see `escrow` in charges.md).\",\n )\nexport type ChargesQueryField = z.infer<typeof ChargesQueryFieldSchema>\n\nexport const ChargesMetricFieldSchema = z\n .enum(['amount', 'amountReceived', 'feePercent', 'escrowFeePercent'])\n .describe(\n 'A `Charge` numeric field to aggregate. `amount`/`amountReceived` are decimal currency amounts (requested vs. actually received — 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 — see `docs/payments.md`.',\n )\nexport type ChargesMetricField = z.infer<typeof ChargesMetricFieldSchema>\n\nexport const ChargesDateFieldSchema = z\n .enum(['createdAt', 'confirmedAt', 'lastActivityAt', 'expiresAt', 'escrowReleasedAt'])\n .describe(\n 'A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` — 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 — same implicit-exclusion behavior as `confirmedAt`, scoped to escrow charges only.',\n )\nexport type ChargesDateField = z.infer<typeof ChargesDateFieldSchema>\n\nconst ChargesFilterSchema = z.object({\n field: ChargesQueryFieldSchema,\n operator: MetricsFilterOperatorSchema,\n value: MetricsFilterValueSchema,\n})\n\nconst ChargesGroupBySchema = z.union([\n z.object({ type: z.literal('field'), field: ChargesQueryFieldSchema }),\n z.object({\n type: z.literal('date_bucket'),\n field: ChargesDateFieldSchema,\n granularity: MetricsDateGranularitySchema,\n }),\n])\n\nconst ChargesMetricSchema = z.object({\n aggregation: MetricsAggregationSchema,\n field: ChargesMetricFieldSchema.optional(),\n alias: metricAliasSchema,\n})\n\nconst ChargesMetricsQuerySchema = z.object({\n resource: z.literal('charges'),\n environment: metricsQueryEnvironmentSchema,\n dateRange: z.object({\n field: ChargesDateFieldSchema,\n from: z.string().max(64).datetime(),\n to: z.string().max(64).datetime(),\n }),\n groupBy: z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),\n metrics: z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),\n filters: z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),\n orderBy: orderBySchema.optional(),\n limit: limitSchema,\n})\n\nexport const TransactionsQueryFieldSchema = z\n .enum(['network', 'token', 'source', 'causedTransition'])\n .describe(\n \"A `Transaction` field to filter or group by — see `NetworkSchema`/`TokenSchema`/`TransactionSourceSchema` for their possible values. `causedTransition` is `true` only for the transfer(s) that actually flipped the charge's `status` — 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).\",\n )\nexport type TransactionsQueryField = z.infer<typeof TransactionsQueryFieldSchema>\n\nexport const TransactionsMetricFieldSchema = z\n .enum(['amount'])\n .describe(\"The transfer amount, in the charge's `currency` units.\")\nexport type TransactionsMetricField = z.infer<typeof TransactionsMetricFieldSchema>\n\nexport const TransactionsDateFieldSchema = z\n .enum(['detectedAt'])\n .describe('When Klappay detected this transfer on-chain (not when it was mined).')\nexport type TransactionsDateField = z.infer<typeof TransactionsDateFieldSchema>\n\nconst TransactionsFilterSchema = z.object({\n field: TransactionsQueryFieldSchema,\n operator: MetricsFilterOperatorSchema,\n value: MetricsFilterValueSchema,\n})\n\nconst TransactionsGroupBySchema = z.union([\n z.object({ type: z.literal('field'), field: TransactionsQueryFieldSchema }),\n z.object({\n type: z.literal('date_bucket'),\n field: TransactionsDateFieldSchema,\n granularity: MetricsDateGranularitySchema,\n }),\n])\n\nconst TransactionsMetricSchema = z.object({\n aggregation: MetricsAggregationSchema,\n field: TransactionsMetricFieldSchema.optional(),\n alias: metricAliasSchema,\n})\n\nconst TransactionsMetricsQuerySchema = z.object({\n resource: z.literal('transactions'),\n environment: metricsQueryEnvironmentSchema,\n dateRange: z.object({\n field: TransactionsDateFieldSchema,\n from: z.string().max(64).datetime(),\n to: z.string().max(64).datetime(),\n }),\n groupBy: z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),\n metrics: z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),\n filters: z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),\n orderBy: orderBySchema.optional(),\n limit: limitSchema,\n})\n\nexport const DistributionsQueryFieldSchema = z\n .enum(['status', 'network', 'token', 'distributorAddress'])\n .describe(\n \"A `SplitDistribution` field to filter or group by — see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values. `distributorAddress` is the public on-chain address that actually called `distribute()` for a `completed` distribution — 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.\",\n )\nexport type DistributionsQueryField = z.infer<typeof DistributionsQueryFieldSchema>\n\nexport const DistributionsMetricFieldSchema = z\n .enum(['attempts'])\n .describe(\n \"How many times a payout was attempted for this settlement so far — 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.\",\n )\nexport type DistributionsMetricField = z.infer<typeof DistributionsMetricFieldSchema>\n\nexport const DistributionsDateFieldSchema = z\n .enum(['createdAt', 'processingStartedAt', 'completedAt'])\n .describe(\n \"`createdAt`: when this settlement was queued. `processingStartedAt`: when a worker began its most recent attempt at the payout — `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 — `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed.\",\n )\nexport type DistributionsDateField = z.infer<typeof DistributionsDateFieldSchema>\n\nconst DistributionsFilterSchema = z.object({\n field: DistributionsQueryFieldSchema,\n operator: MetricsFilterOperatorSchema,\n value: MetricsFilterValueSchema,\n})\n\nconst DistributionsGroupBySchema = z.union([\n z.object({ type: z.literal('field'), field: DistributionsQueryFieldSchema }),\n z.object({\n type: z.literal('date_bucket'),\n field: DistributionsDateFieldSchema,\n granularity: MetricsDateGranularitySchema,\n }),\n])\n\nconst DistributionsMetricSchema = z.object({\n aggregation: MetricsAggregationSchema,\n field: DistributionsMetricFieldSchema.optional(),\n alias: metricAliasSchema,\n})\n\nconst DistributionsMetricsQuerySchema = z.object({\n resource: z.literal('distributions'),\n environment: metricsQueryEnvironmentSchema,\n dateRange: z.object({\n field: DistributionsDateFieldSchema,\n from: z.string().max(64).datetime(),\n to: z.string().max(64).datetime(),\n }),\n groupBy: z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),\n metrics: z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),\n filters: z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),\n orderBy: orderBySchema.optional(),\n limit: limitSchema,\n})\n\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000\n\nexport const MetricsQuerySchema = z\n .discriminatedUnion('resource', [\n ChargesMetricsQuerySchema,\n TransactionsMetricsQuerySchema,\n DistributionsMetricsQuerySchema,\n ])\n .superRefine((input, ctx) => {\n const from = new Date(input.dateRange.from)\n const to = new Date(input.dateRange.to)\n if (from >= to) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: '`dateRange.from` must be before `dateRange.to`.',\n path: ['dateRange', 'from'],\n })\n }\n const spanDays = (to.getTime() - from.getTime()) / ONE_DAY_MS\n if (spanDays > MAX_METRICS_QUERY_DATE_RANGE_DAYS) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `\\`dateRange\\` cannot span more than ${MAX_METRICS_QUERY_DATE_RANGE_DAYS} days.`,\n path: ['dateRange', 'to'],\n })\n }\n const dateBucketCount = input.groupBy.filter((entry) => entry.type === 'date_bucket').length\n if (dateBucketCount > 1) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'At most one `date_bucket` entry is allowed in `groupBy`.',\n path: ['groupBy'],\n })\n }\n input.metrics.forEach((metric, index) => {\n if (metric.aggregation !== 'count' && metric.field === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: '`field` is required unless `aggregation` is `count`.',\n path: ['metrics', index, 'field'],\n })\n }\n })\n const aliases = input.metrics\n .map((metric) => metric.alias)\n .filter((alias) => alias !== undefined)\n if (new Set(aliases).size !== aliases.length) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Every `metrics[].alias` must be unique.',\n path: ['metrics'],\n })\n }\n const reservedNames = new Set(['bucket', ...input.groupBy.map((entry) => entry.field)])\n input.metrics.forEach((metric, index) => {\n if (metric.alias !== undefined && reservedNames.has(metric.alias)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `\\`alias\\` \"${metric.alias}\" collides with a \\`groupBy\\` field name (or the reserved word \"bucket\") — choose a different alias.`,\n path: ['metrics', index, 'alias'],\n })\n }\n })\n })\n\nexport type MetricsQuery = z.infer<typeof MetricsQuerySchema>\nexport type MetricsQueryRequest = z.input<typeof MetricsQuerySchema>\n\nexport const MetricsQueryResultRowSchema = z.record(\n z.string(),\n z.union([z.string(), z.number(), z.boolean(), z.null()]),\n)\nexport type MetricsQueryResultRow = z.infer<typeof MetricsQueryResultRowSchema>\n\nexport const MetricsQueryResultSchema = z.object({\n data: z.array(MetricsQueryResultRowSchema),\n meta: z.object({\n resource: MetricsResourceSchema,\n environment: EnvironmentSchema,\n rowCount: z.number().int().describe('Number of rows in `data`.'),\n truncated: z\n .boolean()\n .describe(\n '`true` if more rows matched than `limit` allowed — `data` holds only the first `limit`.',\n ),\n }),\n})\nexport type MetricsQueryResult = z.infer<typeof MetricsQueryResultSchema>\n","import { z } from 'zod'\n\nexport const ChargeWebhookEventTypeSchema = z\n .enum([\n 'charge.created',\n 'charge.partially_paid',\n 'charge.confirmed',\n 'charge.expired',\n 'charge.underpaid',\n 'charge.settled',\n 'charge.settlement_failed',\n 'charge.overpaid',\n 'charge.escrow_released',\n 'charge.escrow_refunded',\n ])\n .describe(\n '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 — 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` — 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` — 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`.',\n )\n\nexport const WebhookDeliveryEventTypeSchema = z\n .enum(['webhook.delivery_failed', 'webhook.delivery_recovered', 'webhook.endpoint_unhealthy'])\n .describe(\n \"Meta-events about the health of your own webhook endpoints — 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`).\",\n )\n\nexport const WebhookEventTypeSchema = z.union([\n ChargeWebhookEventTypeSchema,\n WebhookDeliveryEventTypeSchema,\n])\n\nexport type WebhookEventType = z.infer<typeof WebhookEventTypeSchema>\n\nexport const WebhookCategorySchema = z\n .enum(['payments', 'webhooks'])\n .describe(\n 'Subscribe to every event in a category via `eventCategories` instead of listing events one by one — new events added to a category later arrive automatically, no subscription update needed.',\n )\nexport type WebhookCategory = z.infer<typeof WebhookCategorySchema>\n\nfunction buildCategoryMap(): Record<WebhookEventType, WebhookCategory> {\n const map = {} as Record<WebhookEventType, WebhookCategory>\n for (const event of ChargeWebhookEventTypeSchema.options) map[event] = 'payments'\n for (const event of WebhookDeliveryEventTypeSchema.options) map[event] = 'webhooks'\n\n for (const event of WebhookEventTypeSchema.options.flatMap((schema) => schema.options)) {\n if (!(event in map)) {\n throw new Error(\n `buildCategoryMap: \"${event}\" has no category — a new event sub-schema was unioned into WebhookEventTypeSchema without a matching loop added here.`,\n )\n }\n }\n\n return map\n}\n\nexport const EVENT_CATEGORY_MAP = buildCategoryMap()\n\nexport const WEBHOOK_EVENT_CATEGORIES: Record<WebhookCategory, readonly WebhookEventType[]> = {\n payments: ChargeWebhookEventTypeSchema.options,\n webhooks: WebhookDeliveryEventTypeSchema.options,\n}\n\nexport const TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([\n 'charge.created',\n 'charge.escrow_released',\n 'charge.escrow_refunded',\n]).describe(\n \"Every charge event that represents a payment-progress state transition a sandbox charge can be pushed into — everything except `charge.created` (a charge already exists by the time you have an id to trigger against) and the two escrow-terminal events, which are reached by actually calling `POST /v1/charges/{id}/release` or `POST /v1/charges/{id}/refund` on a test-environment escrow charge (a real Safe transaction on that network's testnet), not this generic trigger.\",\n)\n\nexport type TriggerableChargeEvent = z.infer<typeof TriggerableChargeEventSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\nimport { EVENT_CATEGORY_MAP, WebhookCategorySchema, WebhookEventTypeSchema } from './webhook-events'\n\nexport const WEBHOOK_EVENTS_WILDCARD = '*'\n\nexport const CreateWebhookSchema = z\n .object({\n url: z\n .string()\n .max(2048)\n .url()\n .describe(\n 'Must be HTTPS and resolve to a public address — private/internal IPs are rejected.',\n ),\n events: z\n .array(z.union([WebhookEventTypeSchema, z.literal(WEBHOOK_EVENTS_WILDCARD)]))\n .max(Object.keys(EVENT_CATEGORY_MAP).length + 1)\n .default([])\n .describe(\n '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.',\n ),\n eventCategories: z\n .array(WebhookCategorySchema)\n .max(WebhookCategorySchema.options.length)\n .default([])\n .describe(\n 'Subscribe to every event in these categories. At least one of `events` or `eventCategories` is required.',\n ),\n excludeEvents: z\n .array(WebhookEventTypeSchema)\n .max(Object.keys(EVENT_CATEGORY_MAP).length)\n .default([])\n .describe(\n 'Event types to exclude even if selected via `events: [\"*\"]` or `eventCategories`.',\n ),\n })\n .refine((v) => v.events.length > 0 || v.eventCategories.length > 0, {\n message: 'must select at least one event via `events` or `eventCategories`',\n path: ['events'],\n })\n\nexport type CreateWebhookInput = z.infer<typeof CreateWebhookSchema>\n\nexport type CreateWebhookRequest = z.input<typeof CreateWebhookSchema>\n\nexport const WebhookSchema = z.object({\n id: z.string(),\n environment: EnvironmentSchema.nullable().describe(\n \"Which environment's API key created this webhook — `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 — the case for every webhook created before this field existed).\",\n ),\n url: z.string(),\n events: z.array(WebhookEventTypeSchema),\n eventCategories: z.array(WebhookCategorySchema),\n excludeEvents: z.array(WebhookEventTypeSchema),\n isWildcard: z.boolean(),\n secret: z\n .string()\n .describe(\n \"The signing secret, used to verify the `X-Klappay-Signature` header on every delivery. Returned in full only this once — 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 — 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 — see github.com/klappay for available SDKs.\",\n ),\n createdAt: z.string().datetime(),\n})\n\nexport type Webhook = z.infer<typeof WebhookSchema>\n\nexport const WebhookListItemSchema = WebhookSchema.omit({ secret: true }).extend({\n hint: z\n .string()\n .describe('A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).'),\n})\nexport type WebhookListItem = z.infer<typeof WebhookListItemSchema>\n\nexport const WebhookPayloadSchema = z.object({\n id: z\n .string()\n .describe(\n 'Unique id for this specific delivery — also sent as the `X-Klappay-Delivery` header.',\n ),\n event: WebhookEventTypeSchema,\n createdAt: z.string().datetime(),\n data: z\n .unknown()\n .describe(\n 'Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; webhook-delivery events carry a smaller, event-specific object — see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md.',\n ),\n})\n\nexport type WebhookPayload = z.infer<typeof WebhookPayloadSchema>\n\nexport const WebhookDeliveryStatusSchema = z.enum(['pending', 'delivered', 'failed'])\nexport type WebhookDeliveryStatus = z.infer<typeof WebhookDeliveryStatusSchema>\n\nexport const WebhookDeliverySchema = z.object({\n id: z.string(),\n webhookId: z.string(),\n event: WebhookEventTypeSchema,\n status: WebhookDeliveryStatusSchema.describe(\n '`pending`: still retrying. `delivered`: got a 2xx response. `failed`: retries exhausted (5 attempts over ~24h) — use `POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry` to try again manually.',\n ),\n attempts: z.number(),\n responseCode: z\n .number()\n .nullable()\n .describe(\n 'HTTP status your endpoint returned on the most recent attempt. `null` if every attempt failed to connect at all.',\n ),\n nextRetryAt: z.string().datetime().nullable(),\n deliveredAt: z.string().datetime().nullable(),\n createdAt: z.string().datetime(),\n})\n\nexport type WebhookDelivery = z.infer<typeof WebhookDeliverySchema>\n\nexport const ListWebhookDeliveriesSchema = PaginationQuerySchema\n\nexport type ListWebhookDeliveriesInput = z.infer<typeof ListWebhookDeliveriesSchema>\n\nexport type ListWebhookDeliveriesRequest = z.input<typeof ListWebhookDeliveriesSchema>\n\nexport const PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema)\n\nexport type PaginatedWebhookDeliveries = z.infer<typeof PaginatedWebhookDeliveriesSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\n\nconst EVM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/\n\nexport const CreateRecipientSchema = z.object({\n address: z\n .string()\n .regex(EVM_ADDRESS_REGEX, 'must be a 20-byte hex address')\n .describe('EVM address to register as a trusted split recipient for your organization.'),\n label: z\n .string()\n .min(1)\n .max(64)\n .optional()\n .describe('Free-form label for your own bookkeeping (e.g. `\"supplier\"`) — never interpreted.'),\n})\nexport type CreateRecipientInput = z.infer<typeof CreateRecipientSchema>\nexport type CreateRecipientRequest = z.input<typeof CreateRecipientSchema>\n\nexport const RecipientSchema = z.object({\n id: z\n .string()\n .describe(\n \"Klappay-generated id, e.g. `rc_...` — this, not the raw address, is what a charge's `splitRecipients[].recipientId` references.\",\n ),\n environment: EnvironmentSchema,\n address: z.string(),\n label: z.string().nullable(),\n payout: z\n .boolean()\n .describe(\n \"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}` — requires the `recipients:manage_payout` scope, deliberately separate from `recipients:write`.\",\n ),\n createdAt: z.string().datetime(),\n})\nexport type Recipient = z.infer<typeof RecipientSchema>\n\nexport const SetRecipientPayoutSchema = z.object({\n payout: z.boolean().describe('New payout-eligibility value for this recipient.'),\n})\nexport type SetRecipientPayoutInput = z.infer<typeof SetRecipientPayoutSchema>\n","import { z } from 'zod'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\nimport { WebhookEventTypeSchema } from './webhook-events'\n\nexport const TransactionSourceSchema = z\n .enum(['moralis_webhook', 'reconciliation_job', 'sandbox'])\n .describe(\n '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).',\n )\nexport type TransactionSource = z.infer<typeof TransactionSourceSchema>\n\nexport const TimelineEventTypeSchema = z\n .enum([\n 'charge.created',\n 'charge.expired',\n 'transaction.detected',\n 'split.distributed',\n 'webhook.dispatched',\n 'webhook.delivered',\n 'webhook.failed',\n 'transfer.reclaimed',\n ])\n .describe(\n \"`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 — 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 — 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 — `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) — see `txHash` below for which transfer.\",\n )\nexport type TimelineEventType = z.infer<typeof TimelineEventTypeSchema>\n\nexport const TimelineEventSchema = z.object({\n type: TimelineEventTypeSchema,\n at: z.string().datetime(),\n txHash: z\n .string()\n .optional()\n .describe(\n 'Present for `transaction.detected`, `split.distributed`, and `transfer.reclaimed` events only.',\n ),\n amount: z\n .number()\n .optional()\n .describe(\n 'Present for `transaction.detected` events only — the amount that specific transfer carried.',\n ),\n source: TransactionSourceSchema.optional().describe(\n 'Present for `transaction.detected` events only.',\n ),\n token: TokenSchema.optional().describe(\n 'Present for `transaction.detected` and `split.distributed` events — which token this specific transfer, or settlement, used. A charge can accept (and be settled across) more than one `(token, network)` pair (see `Charge.acceptedPayments`); this is how to tell which one a given event actually used.',\n ),\n network: NetworkSchema.optional().describe(\n 'Present for `transaction.detected` and `split.distributed` events — which network this specific transfer, or settlement, used.',\n ),\n causedTransition: z\n .boolean()\n .optional()\n .describe(\n \"Present for `transaction.detected` events only. `true` if this specific transfer changed the charge's status (e.g. PENDING→CONFIRMED) — a charge paid in installments can have more than one such event.\",\n ),\n event: WebhookEventTypeSchema.optional().describe(\n 'Present for `webhook.*` events only — which event type this delivery was for.',\n ),\n responseCode: z\n .number()\n .nullable()\n .optional()\n .describe(\n 'Present for `webhook.*` events only — HTTP status your endpoint returned, or `null` if the request never connected.',\n ),\n attempts: z\n .number()\n .optional()\n .describe(\n 'Present for `webhook.*` events only — how many delivery attempts have been made so far.',\n ),\n})\nexport type TimelineEvent = z.infer<typeof TimelineEventSchema>\n","import { z } from 'zod'\n\nexport const HealthSchema = z.object({\n status: z\n .enum(['ok', 'error'])\n .describe(\n '`error` when the database connectivity check fails — 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.',\n ),\n version: z.string(),\n timestamp: z.string().datetime(),\n db: z\n .enum(['ok', 'error'])\n .describe('Result of a real database connectivity check, not just a process-alive check.'),\n pendingWebhooks: z\n .number()\n .describe('Count of webhook deliveries still awaiting a successful attempt.'),\n oldestPendingChargeAgeSeconds: z\n .number()\n .nullable()\n .describe('Age of the oldest still-unpaid charge, in seconds. `null` if there are none.'),\n lastMoralisEventAgeSeconds: z\n .number()\n .nullable()\n .describe(\n 'Seconds since the last on-chain payment notification was received — a cheap signal for whether payment detection is currently working. `null` if none have ever been received.',\n ),\n})\n\nexport type Health = z.infer<typeof HealthSchema>\n","import { z } from 'zod'\nimport { CHARGE_AMOUNT_MAX } from './charges'\nimport { TriggerableChargeEventSchema } from './webhook-events'\n\nexport const SandboxTriggerSchema = z.object({\n event: TriggerableChargeEventSchema,\n amount: z\n .number()\n .positive()\n .max(CHARGE_AMOUNT_MAX)\n .optional()\n .describe(\n 'Used with `charge.partially_paid` (amount to simulate as received so far — must be less than the charge amount, defaults to half of it if omitted) and with `charge.overpaid` (amount received — must be greater than the charge amount, defaults to 1.5x it if omitted). Ignored for every other event.',\n ),\n})\n\nexport type SandboxTriggerInput = z.infer<typeof SandboxTriggerSchema>\n","import { z } from 'zod'\nimport { AcceptedPaymentSchema } from './charges'\n\nexport const CapabilitiesSchema = z.object({\n acceptedPayments: z\n .array(AcceptedPaymentSchema)\n .describe(\n 'Every `(token, network)` pair actually configured for your environment right now — 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.',\n ),\n})\nexport type Capabilities = z.infer<typeof CapabilitiesSchema>\n","import { z } from 'zod'\nimport { AltTokenSchema } from './alt-tokens'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\n\nexport const CreateSwapQuoteSchema = z.object({\n inputToken: AltTokenSchema.describe(\n \"Which alt-cryptocurrency the payer wants to send — must be one of this charge's `swapAlternatives`, or `422 token_not_supported`.\",\n ),\n inputNetwork: NetworkSchema.describe(\n \"Which network the payer will send `inputToken` on. Also picks which of this charge's `acceptedPayments` pairs the swap resolves to — 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) — never a token the charge doesn't actually accept.\",\n ),\n takerAddress: z\n .string()\n .regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address')\n .describe(\n \"The payer's own wallet address — 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.\",\n ),\n})\nexport type CreateSwapQuoteInput = z.infer<typeof CreateSwapQuoteSchema>\n\nexport const SwapQuoteSchema = z.object({\n inputToken: AltTokenSchema,\n inputNetwork: NetworkSchema,\n inputAmount: z\n .number()\n .describe(\n 'The ceiling of `inputToken` the payer needs available to sign for, in whole units (not wei/base units) — 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 — never a separate step or a Klappay-side refund.',\n ),\n outputToken: TokenSchema.describe(\n \"Which of this charge's `acceptedPayments` tokens the swap resolves to.\",\n ),\n outputNetwork: NetworkSchema,\n outputAmount: z\n .number()\n .describe(\n \"The exact remaining amount owed on this charge (`amount - amountReceived`), in `currency` units — always what the merchant's split address receives, regardless of `inputAmount`.\",\n ),\n fees: z\n .object({\n klappayFee: z\n .number()\n .describe(\n \"Klappay's own swap fee (1% today), in `outputToken` units — paid by the payer, on top of `inputAmount`, separate from the merchant's own `feePercent`. Never subtracted from `outputAmount`.\",\n ),\n zeroExFee: z\n .number()\n .nullable()\n .describe(\n \"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` — Klappay never sees this fee, it goes straight to 0x.\",\n ),\n })\n .describe(\n 'Every fee the payer is charged for using swap-to-pay, broken out by who collects it — both already reflected in `inputAmount`, shown here separately for transparency. Neither ever reduces `outputAmount`.',\n ),\n expiresAt: z\n .string()\n .datetime()\n .describe(\n \"When this quote's price is no longer safely valid — 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 — submitting after it expires either reverts on-chain or simply gets re-quoted at the current price, never silently executes at a stale rate.\",\n ),\n transaction: z\n .object({\n to: z.string().describe(\"Contract address the payer's wallet must send this transaction to.\"),\n data: z.string().describe('Calldata — opaque, must be sent unmodified.'),\n value: z\n .string()\n .describe(\n 'Native currency (ETH/BNB/MATIC/AVAX) to attach, in wei — `\"0\"` when `inputToken` isn\\'t this network\\'s native currency.',\n ),\n })\n .describe(\n \"Pass this directly to the payer's wallet (e.g. viem/ethers `sendTransaction`) — 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.\",\n ),\n permit2: z\n .object({ eip712: z.record(z.unknown()) })\n .nullish()\n .describe(\n \"Present only when `inputToken` is an ERC-20 (today, only `BTC`) — 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/MATIC/AVAX) — `transaction` is then ready to sign and send directly, no extra step.\",\n ),\n})\nexport type SwapQuote = z.infer<typeof SwapQuoteSchema>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAEX,IAAM,qBAAqB,aAAE,OAAO;AAAA,EACzC,OAAO,aAAE,OAAO;AAAA,IACd,MAAM,aACH,OAAO,EACP;AAAA,MACC;AAAA,IACF;AAAA,IACF,SAAS,aACN,OAAO,EACP;AAAA,MACC;AAAA,IACF;AAAA,IACF,OAAO,aACJ,OAAO,EACP,SAAS,EACT,SAAS,2DAA2D;AA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AACJ,CAAC;","names":["import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod"]}