@klappay/types 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/environment.ts","../src/networks.ts","../src/pagination.ts","../src/tokens.ts","../src/charges.ts","../src/distributions.ts","../src/webhook-events.ts","../src/webhooks.ts","../src/api-keys.ts","../src/users.ts","../src/auth.ts","../src/organization.ts","../src/invitations.ts","../src/timeline.ts","../src/verify.ts","../src/health.ts","../src/sandbox.ts","../src/capabilities.ts"],"sourcesContent":["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`, `invalid_credentials`).',\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 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 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","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 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 type { Environment } from './environment'\nimport { OPERATIONAL_NETWORKS } from './networks'\nimport type { Network } 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 — Klap 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 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 { EnvironmentSchema } from './environment'\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`. 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 ChargeModeSchema = z\n .enum(['standard', 'continuous'])\n .describe(\n \"`standard` (default): the usual lifecycle — accumulates transfers toward one resolution (`confirmed`/`expired`/`underpaid`), settles once. `continuous`: never resolves — `status` stays `pending` for the charge's entire life, and every credited transfer settles independently instead of accumulating toward one confirmation (see `charge.contribution_received`/`charge.contribution_settled`). Requires both `amount` and `expiresIn` to be omitted — there's no goal to accumulate toward and no deadline for something meant to run indefinitely (a link in a creator's bio, a permanent collection address). Not inferred from omitting those two fields — an explicit, deliberate choice, since silently changing a charge's entire settlement lifecycle based on which optional fields happened to be left out would be a footgun.\",\n )\nexport type ChargeMode = z.infer<typeof ChargeModeSchema>\n\nexport const CHARGE_EXPIRES_IN_MIN_SECONDS = 60\nexport const CHARGE_EXPIRES_IN_MAX_SECONDS = 365 * 24 * 60 * 60\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_AMOUNT_MAX = 999_999_999_999\n\nexport const CreateChargeSchema = z\n .object({\n mode: ChargeModeSchema.default('standard'),\n amount: z\n .number()\n .positive()\n .max(CHARGE_AMOUNT_MAX)\n .optional()\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. Omit entirely for a charge that accepts any amount — the first credited transfer of any size confirms it, and `isOverpaid` never applies (there is no target to exceed).',\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 .optional()\n .describe(\n 'Seconds, not minutes or milliseconds — how long the charge stays open, min 60, max 31,536,000 = 365 days. Omit entirely for a charge that never expires (`expiresAt` is `null`) — useful for donations, investments, or any charge with no natural deadline. Cannot be extended or shortened after creation either way.',\n ),\n idempotencyKey: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe(\n 'Scoped to your organization. Replaying the same key returns the original charge unchanged instead of creating a duplicate — safe to retry a request after a timeout without double-charging.',\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 Klap.',\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: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Arbitrary key/value data to attach to the charge, returned as-is on every read.'),\n })\n .superRefine((input, ctx) => {\n if (\n input.mode === 'continuous' &&\n (input.amount !== undefined || input.expiresIn !== undefined)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'mode: \"continuous\" requires both amount and expiresIn to be omitted.',\n path: ['mode'],\n })\n }\n })\n\nexport type CreateChargeInput = z.infer<typeof CreateChargeSchema>\n\nexport const ChargeSchema = z.object({\n id: z\n .string()\n .describe('Klap-generated id, e.g. `ch_...`. Use this to look up the charge later.'),\n mode: ChargeModeSchema,\n amount: z\n .number()\n .nullable()\n .describe(\n 'The amount originally requested, in `currency` units (up to 6 decimal places). `null` if `amount` was omitted at creation — this charge accepts any amount, and the first credited transfer confirms it.',\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` — unless `amount` itself is `null`, in which case `isOverpaid` never applies.',\n ),\n isOverpaid: z\n .boolean()\n .describe(\n '`true` if `amountReceived` ended up greater than `amount`. Klap 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 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, Klap 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: z.record(z.string(), z.unknown()).nullable(),\n createdAt: z.string().datetime(),\n expiresAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When this charge stops accepting payment, if still `pending`/`partially_paid` by then. `null` if `expiresIn` was omitted at creation — the charge never expires on its own and must be dealt with manually (or left open indefinitely).',\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. Only meaningful for a charge with no `expiresAt` — see `pausedAt`.',\n ),\n pausedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'Only ever set for a charge with no `expiresAt`: `null` means Klap is actively watching this address in real time (the normal case). A timestamp means no contribution arrived for longer than the inactivity window (90 days for a charge with a goal `amount`, 365 days for one without), so real-time watching was stopped — the charge itself is never closed, a transfer can still arrive and land, just detected on a much slower fallback poll instead of instantly. Clears automatically (and real-time watching resumes) the moment that happens.',\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 const PaginatedChargesSchema = paginatedSchema(ChargeSchema)\n\nexport type PaginatedCharges = z.infer<typeof PaginatedChargesSchema>\n\nexport const ChargeStatusEventSchema = z.object({\n id: z.string(),\n status: ChargeStatusSchema,\n settlementStatus: SettlementStatusSchema.nullable(),\n amount: z.number().nullable(),\n amountReceived: z.number().nullable(),\n paidWith: z.array(AcceptedPaymentSchema),\n})\n\nexport type ChargeStatusEvent = z.infer<typeof ChargeStatusEventSchema>\n","import { z } from 'zod'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\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 Klap 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 Klap'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 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'\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.paused',\n 'charge.reactivated',\n 'charge.contribution_received',\n 'charge.contribution_settled',\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`). Every event in this category carries the full `Charge` object as `data`, except `charge.paused`/`charge.reactivated`/`charge.contribution_received`/`charge.contribution_settled` (see below). `charge.paused` fires when a charge with no `expiresAt` has had no contribution for longer than its inactivity window (90 days for a charge with a goal `amount`, 365 days for one without) — Klap stops watching its address in real time, but the charge itself is never closed; `charge.reactivated` fires the moment a transfer lands on a paused charge, detected by the same fallback poller used for missed webhooks (so with much higher latency than normal — pausing trades that away deliberately, see `docs/payments.md`). `charge.contribution_received`/`charge.contribution_settled` are exclusive to `mode: continuous` charges (see `Charge.mode`) — a continuous charge never fires `charge.confirmed`/`charge.settled` at all, since `status` never leaves `pending`; instead every individual transfer fires `contribution_received` on detection and `contribution_settled` once its payout completes, one pair-scoped event per contribution instead of one event for the whole charge. `data` for `charge.paused`: `{ chargeId, lastActivityAt, pausedAt }`; for `charge.reactivated`: `{ chargeId, reactivatedAt }`; for `charge.contribution_received`: `{ chargeId, token, network, amount, txHash, payerAddress }`; for `charge.contribution_settled`: `{ chargeId, token, network, amount, txHash, distributorAddress }`.',\n )\n\nexport const AccountWebhookEventTypeSchema = z\n .enum([\n 'payout_address.changed',\n 'api_key.created',\n 'api_key.revoked',\n 'webhook.created',\n 'webhook.deleted',\n 'webhook.secret_rotated',\n 'fee_tier.updated',\n 'member.removed',\n 'member.role_changed',\n 'member.invited',\n ])\n .describe(\n 'Account and configuration changes — not tied to any single charge. `data` per event: `payout_address.changed`: `{ organizationId, from, to }` (`from` nullable); `api_key.created`/`api_key.revoked`: `{ apiKeyId, name, environment, hint }`; `webhook.created`/`webhook.deleted`/`webhook.secret_rotated`: `{ webhookId, url }`; `fee_tier.updated`: `{ organizationId, previousFeePercent, newFeePercent }`; `member.removed`: `{ userId, email, role }`; `member.role_changed`: `{ userId, email, role, previousRole }`; `member.invited`: `{ organizationId, email, role, invitedByUserId }`.',\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 SecurityWebhookEventTypeSchema = z\n .enum([\n 'auth.login',\n 'auth.login_failed',\n 'auth.suspicious_activity',\n 'auth.email_verified',\n 'auth.password_reset_requested',\n 'auth.password_reset_completed',\n ])\n .describe(\n 'Account security signals. `auth.suspicious_activity` is a soft heuristic (login from an IP not seen on this account before), not a block — evaluate it, not enforce against it. `auth.password_reset_requested` only ever dispatches when the requested email actually matches an account (there is nowhere to notify otherwise) — `POST /v1/auth/forgot-password` itself always returns the same generic response either way, so this event never becomes a second channel for the same enumeration question the endpoint response deliberately avoids answering. `data` per event: `auth.login`: `{ userId, ipAddress }`; `auth.login_failed`: `{ email, ipAddress }`; `auth.suspicious_activity`: `{ userId, ipAddress, previousIpAddress }`; `auth.email_verified`/`auth.password_reset_requested`/`auth.password_reset_completed`: `{ userId, email }`.',\n )\n\nexport const WebhookEventTypeSchema = z.union([\n ChargeWebhookEventTypeSchema,\n AccountWebhookEventTypeSchema,\n WebhookDeliveryEventTypeSchema,\n SecurityWebhookEventTypeSchema,\n])\n\nexport type WebhookEventType = z.infer<typeof WebhookEventTypeSchema>\n\nexport const WebhookCategorySchema = z\n .enum(['payments', 'account', 'webhooks', 'security'])\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 AccountWebhookEventTypeSchema.options) map[event] = 'account'\n for (const event of WebhookDeliveryEventTypeSchema.options) map[event] = 'webhooks'\n for (const event of SecurityWebhookEventTypeSchema.options) map[event] = 'security'\n return map\n}\n\n/** Single source of truth for which category each event belongs to — see `webhook-events.test.ts` for the completeness check. */\nexport const EVENT_CATEGORY_MAP = buildCategoryMap()\n\nexport const WEBHOOK_EVENT_CATEGORIES: Record<WebhookCategory, readonly WebhookEventType[]> = {\n payments: ChargeWebhookEventTypeSchema.options,\n account: AccountWebhookEventTypeSchema.options,\n webhooks: WebhookDeliveryEventTypeSchema.options,\n security: SecurityWebhookEventTypeSchema.options,\n}\n\nexport const TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([\n 'charge.created',\n 'charge.paused',\n 'charge.reactivated',\n 'charge.contribution_received',\n 'charge.contribution_settled',\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), `charge.paused`/`charge.reactivated` (driven by a background worker on real inactivity, not a payment state — nothing meaningful to simulate or wait for on a fresh sandbox charge), and `charge.contribution_received`/`charge.contribution_settled` (exclusive to `mode: continuous` charges, which this trigger endpoint does not support simulating today — see `POST /v1/charges/{id}/trigger`'s own description).\",\n)\n\nexport type TriggerableChargeEvent = z.infer<typeof TriggerableChargeEventSchema>\n\nexport const NonChargeTriggerableEventSchema = z.union([\n AccountWebhookEventTypeSchema,\n WebhookDeliveryEventTypeSchema,\n SecurityWebhookEventTypeSchema,\n])\nexport type NonChargeTriggerableEvent = z.infer<typeof NonChargeTriggerableEventSchema>\n","import { z } from 'zod'\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 const WebhookSchema = z.object({\n id: z.string(),\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-Klap-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 — Klap does not enforce or check any particular tolerance server-side, so the exact threshold is entirely the receiver's own policy call. `@klappay/sdk`'s `constructEvent()`/`verifySignature()` do this for you, defaulting to a 300-second tolerance, overridable via `constructEvent`'s `toleranceSeconds` option.\",\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('Unique id for this specific delivery — also sent as the `X-Klap-Delivery` header.'),\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; account/security/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 const PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema)\n\nexport type PaginatedWebhookDeliveries = z.infer<typeof PaginatedWebhookDeliveriesSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\n\nexport const CreateApiKeySchema = z.object({\n name: z\n .string()\n .min(1)\n .max(64)\n .describe(\n 'A label to help you tell keys apart (e.g. `\"production backend\"`). Not used for anything functional.',\n ),\n environment: EnvironmentSchema.describe(\n '`live` keys move real funds on Base mainnet; `test` keys settle on Base Sepolia (a real testnet, no real money) and additionally unlock `POST /v1/sandbox/*` for simulating events with zero on-chain activity at all.',\n ),\n})\n\nexport type CreateApiKeyInput = z.infer<typeof CreateApiKeySchema>\n\nexport const ApiKeySchema = z.object({\n id: z.string(),\n name: z.string(),\n environment: EnvironmentSchema.describe(\n '`live` keys authenticate real charges on Base mainnet; `test` keys authenticate the same charge lifecycle on Base Sepolia (a real testnet) and additionally unlock `/v1/sandbox/*` for synthetic event simulation.',\n ),\n key: z\n .string()\n .optional()\n .describe(\n 'The full secret key (`klap_live_...` / `klap_test_...`), used as the `Authorization: Bearer` value on `/v1/charges`, `/v1/webhooks`, and `/v1/sandbox` requests. Present only in the response to `POST /v1/api-keys` — never returned again afterward, so store it immediately.',\n ),\n hint: z\n .string()\n .describe(\n \"A truncated, always-safe-to-display form of the key (e.g. `klap_live_...ab12`), returned everywhere the full key isn't.\",\n ),\n createdAt: z.string().datetime(),\n lastUsedAt: z\n .string()\n .datetime()\n .nullable()\n .describe('Updated on every successful authenticated request. `null` if never used.'),\n createdByUserId: z\n .string()\n .nullable()\n .describe(\n 'Which member of the organization created this key. `null` for a key created before this field existed.',\n ),\n})\n\nexport type ApiKey = z.infer<typeof ApiKeySchema>\n\nexport const ListApiKeysSchema = PaginationQuerySchema\n\nexport type ListApiKeysInput = z.infer<typeof ListApiKeysSchema>\n\nexport const PaginatedApiKeysSchema = paginatedSchema(ApiKeySchema)\n\nexport type PaginatedApiKeys = z.infer<typeof PaginatedApiKeysSchema>\n","import { z } from 'zod'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\n\nexport const UserRoleSchema = z\n .enum(['owner', 'admin', 'member'])\n .describe(\n \"`owner`: full access, and the organization must always keep at least one. `admin`: can manage `member`s but not other `admin`s. `member`: no management permissions. You can only manage a member with a strictly lower role than your own, unless you're an `owner`.\",\n )\nexport type UserRole = z.infer<typeof UserRoleSchema>\n\nexport const UpdateUserRoleSchema = z.object({\n role: UserRoleSchema,\n})\n\nexport type UpdateUserRoleInput = z.infer<typeof UpdateUserRoleSchema>\n\nexport const UserSchema = z.object({\n id: z.string(),\n email: z.string(),\n name: z.string().nullable(),\n role: UserRoleSchema.describe('Your role within the organization this user was fetched from.'),\n emailVerifiedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When this address was confirmed via the emailed verification link. `null` until then. Required (non-null) for two specific actions: creating a `live` API key (`POST /v1/api-keys`) and changing `Organization.payoutAddress` (`PATCH /v1/organization`) — everything else works regardless of verification status.',\n ),\n createdAt: z.string().datetime(),\n})\n\nexport type User = z.infer<typeof UserSchema>\n\nexport const ListUsersSchema = PaginationQuerySchema\n\nexport type ListUsersInput = z.infer<typeof ListUsersSchema>\n\nexport const PaginatedUsersSchema = paginatedSchema(UserSchema)\n\nexport type PaginatedUsers = z.infer<typeof PaginatedUsersSchema>\n","import { z } from 'zod'\nimport { UserSchema } from './users'\n\nexport const NormalizedEmailSchema = z\n .string()\n .trim()\n .max(255)\n .toLowerCase()\n .email()\n .transform((email) => email.normalize('NFC'))\n .describe(\n \"Trimmed, lowercased, and NFC-normalized server-side before use — case/whitespace don't matter.\",\n )\n\nexport const SignupSchema = z.object({\n email: NormalizedEmailSchema,\n password: z.string().min(8).max(128).describe('8-128 characters. No other complexity rule.'),\n})\n\nexport type SignupInput = z.infer<typeof SignupSchema>\n\nexport const LoginSchema = z.object({\n email: NormalizedEmailSchema,\n password: z.string().min(1).max(128),\n})\n\nexport type LoginInput = z.infer<typeof LoginSchema>\n\nexport const VerifyEmailSchema = z.object({\n token: z\n .string()\n .min(1)\n .describe('The token from the verification email — passed as-is, not the account email.'),\n})\nexport type VerifyEmailInput = z.infer<typeof VerifyEmailSchema>\n\nexport const ForgotPasswordSchema = z.object({\n email: NormalizedEmailSchema,\n})\nexport type ForgotPasswordInput = z.infer<typeof ForgotPasswordSchema>\n\nexport const ResetPasswordSchema = z.object({\n token: z.string().min(1).describe('The token from the password reset email.'),\n newPassword: z.string().min(8).max(128),\n})\nexport type ResetPasswordInput = z.infer<typeof ResetPasswordSchema>\n\nexport const MessageResponseSchema = z.object({\n message: z.string().describe('Human-readable confirmation, safe to show a user directly.'),\n})\nexport type MessageResponse = z.infer<typeof MessageResponseSchema>\n\nexport const AuthResponseSchema = z.object({\n token: z\n .string()\n .describe(\n 'Session JWT, valid 7 days — use as `Authorization: Bearer <token>` on every `/v1/organizations/*` request (which nests API keys, members, and invitations — see `GET /v1/organizations`). This token identifies only you; it carries no organization or role — every `/v1/organizations/{id}/*` request is authorized fresh against your actual membership in that specific organization. This is a separate credential from an API key: it authenticates a human/dashboard session, not payment operations. Create an API key with it before you can create charges.',\n ),\n user: UserSchema.omit({ createdAt: true, role: true }),\n})\n\nexport type AuthResponse = z.infer<typeof AuthResponseSchema>\n","import { z } from 'zod'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\nimport { UserRoleSchema } from './users'\n\nexport const UpdateOrganizationSchema = z.object({\n name: z.string().min(1).max(255).optional().describe(\"The organization's display name.\"),\n payoutAddress: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/, 'must be a valid EVM address')\n .optional()\n .describe(\n \"The wallet that receives the merchant's share of every future charge. Changing this only affects charges created after the change — an already-created charge's payout split is frozen from creation and is never retroactively affected. Required before you can create any charge. Any casing is accepted — EIP-55 checksum casing is not required or verified.\",\n ),\n})\n\nexport type UpdateOrganizationInput = z.infer<typeof UpdateOrganizationSchema>\n\nexport const OrganizationSchema = z.object({\n id: z.string(),\n name: z.string(),\n payoutAddress: z\n .string()\n .nullable()\n .describe('`null` until configured — `POST /v1/charges` fails until this is set.'),\n currentFeePercent: z\n .number()\n .describe(\n 'Your current platform fee percentage, based on trailing monthly volume — lower volume tiers pay a higher percentage. `1.5` means 1.5%, not a 0–1 fraction. Frozen onto each charge at creation, so this can change between charges without affecting ones already created.',\n ),\n feeUpdatedAt: z.string().datetime().nullable(),\n createdAt: z.string().datetime(),\n})\n\nexport type Organization = z.infer<typeof OrganizationSchema>\n\nexport const OrganizationWithRoleSchema = OrganizationSchema.extend({\n role: UserRoleSchema.describe('Your own role within this specific organization.'),\n})\n\nexport type OrganizationWithRole = z.infer<typeof OrganizationWithRoleSchema>\n\nexport const PaginatedOrganizationsSchema = paginatedSchema(OrganizationWithRoleSchema)\n\nexport type PaginatedOrganizations = z.infer<typeof PaginatedOrganizationsSchema>\n\nexport const ListOrganizationsSchema = PaginationQuerySchema\n\nexport type ListOrganizationsInput = z.infer<typeof ListOrganizationsSchema>\n","import { z } from 'zod'\nimport { NormalizedEmailSchema } from './auth'\nimport { UserRoleSchema } from './users'\n\nexport const InviteUserSchema = z.object({\n email: NormalizedEmailSchema,\n role: UserRoleSchema.default('member').describe(\n 'The role the invitee will hold once they accept — subject to the same management-hierarchy rule as `PATCH /v1/organizations/{id}/users/{userId}`: an `admin` inviter cannot invite an `admin` or `owner`.',\n ),\n})\n\nexport type InviteUserInput = z.infer<typeof InviteUserSchema>\n\nexport const AcceptInvitationSchema = z.object({\n token: z.string().min(1).describe('The token from the invitation email.'),\n password: z\n .string()\n .min(8)\n .max(128)\n .optional()\n .describe(\n 'Required only if the invited email has no existing Klap account — a new account is created along with the membership. Ignored if the account already exists.',\n ),\n})\n\nexport type AcceptInvitationInput = z.infer<typeof AcceptInvitationSchema>\n\nexport const InvitationSchema = z.object({\n id: z.string(),\n organizationId: z.string(),\n email: z.string(),\n role: UserRoleSchema,\n invitedByUserId: z.string().describe('Which member of the organization sent this invitation.'),\n expiresAt: z.string().datetime(),\n createdAt: z.string().datetime(),\n})\n\nexport type Invitation = z.infer<typeof InvitationSchema>\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'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\n\nexport const SplitRecipientRoleSchema = z\n .enum(['merchant', 'klap_fee', 'distributor_incentive'])\n .describe(\n '`merchant`: the payout recipient. `klap_fee`: the platform fee. `distributor_incentive`: the (usually small) reward paid to whoever triggered the on-chain settlement — may be Klap or a third party, see `address`.',\n )\nexport type SplitRecipientRole = z.infer<typeof SplitRecipientRoleSchema>\n\nexport const VerifySplitEntrySchema = z.object({\n role: SplitRecipientRoleSchema,\n address: z\n .string()\n .nullable()\n .describe(\n 'On-chain recipient address for this share. For `distributor_incentive`, this is `null` until settlement actually happens — there is no fixed address, it goes to whoever calls the settlement transaction.',\n ),\n percentAllocation: z\n .number()\n .describe(\"This entry's share of `amountReceived`, as a percentage (e.g. `99` = 99%).\"),\n amountUSD: z.number(),\n})\n\nexport const VerifyPaymentSchema = z.object({\n token: TokenSchema,\n network: NetworkSchema,\n amountReceived: z\n .number()\n .describe('Cumulative amount received on this specific `(token, network)` pair.'),\n txHash: z\n .string()\n .describe('The on-chain transaction hash of the most recent transfer on this pair.'),\n explorerTxUrl: z.string().describe('Direct link to `txHash` on the relevant block explorer.'),\n split: z\n .array(VerifySplitEntrySchema)\n .describe(\n \"The exact breakdown of where this pair's payment went — merchant's share, Klap's fee, and (once settled) the settlement incentive.\",\n ),\n splitTxHash: z\n .string()\n .nullable()\n .describe(\n 'Transaction hash of the payout to the merchant for this pair, once settlement has happened. `null` until then.',\n ),\n settledAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n \"When settlement completed for this pair — the merchant's wallet actually has the funds. `null` until then.\",\n ),\n})\nexport type VerifyPayment = z.infer<typeof VerifyPaymentSchema>\n\nexport const VerifyChargeSchema = z.object({\n id: z.string(),\n amount: z\n .number()\n .nullable()\n .describe('The amount originally requested. `null` if the charge accepted any amount.'),\n amountReceived: z\n .number()\n .describe(\n 'The actual cumulative amount received across every contributing pair — can exceed `amount` on an overpayment.',\n ),\n confirmedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When the charge reached `confirmed`. `null` for a `mode: continuous` charge — it never reaches a single confirmed moment (`status` stays `pending` for its whole life, see `Charge.mode`); use each entry in `payments[].settledAt` for per-contribution timing instead.',\n ),\n splitAddress: z\n .string()\n .describe(\n 'The on-chain address the payment was sent to — identical across every accepted network.',\n ),\n payments: z\n .array(VerifyPaymentSchema)\n .describe(\n 'One entry per `(token, network)` pair that actually contributed funds — a charge accepting several pairs can be confirmed by a combination of them, each proven and settled independently.',\n ),\n})\n\nexport type VerifyCharge = z.infer<typeof VerifyChargeSchema>\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 { NonChargeTriggerableEventSchema, 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\nexport const SandboxEventTriggerSchema = z.object({\n event: NonChargeTriggerableEventSchema.describe(\n 'Any account, security, or webhook-delivery event — simulates it with synthetic data against your own webhooks, no real state change or precondition required (unlike `POST /v1/sandbox/charges/{id}/trigger`, which acts on a real charge).',\n ),\n})\n\nexport type SandboxEventTriggerInput = z.infer<typeof SandboxEventTriggerSchema>\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"],"mappings":";AAAA,SAAS,SAAS;AAEX,IAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,OAAO,EAAE,OAAO;AAAA,IACd,MAAM,EACH,OAAO,EACP;AAAA,MACC;AAAA,IACF;AAAA,IACF,SAAS,EACN,OAAO,EACP;AAAA,MACC;AAAA,IACF;AAAA,IACF,OAAO,EACJ,OAAO,EACP,SAAS,EACT,SAAS,2DAA2D;AAAA,EACzE,CAAC;AACH,CAAC;;;ACnBD,SAAS,KAAAA,UAAS;AAEX,IAAM,oBAAoBA,GAC9B,KAAK,CAAC,QAAQ,MAAM,CAAC,EACrB;AAAA,EACC;AACF;;;ACNF,SAAS,KAAAC,UAAS;AAEX,IAAM,gBAAgBA,GAC1B,KAAK,CAAC,QAAQ,YAAY,WAAW,YAAY,YAA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OAAO,EACP,SAAS,EACT,IAAI,iBAAiB,EACrB,SAAS,EACT;AAAA,IACC;AAAA,EACF;AACJ,CAAC;AAIM,IAAM,4BAA4BA,IAAE,OAAO;AAAA,EAChD,OAAO,gCAAgC;AAAA,IACrC;AAAA,EACF;AACF,CAAC;;;ACtBD,SAAS,KAAAC,WAAS;AAGX,IAAM,qBAAqBC,IAAE,OAAO;AAAA,EACzC,kBAAkBA,IACf,MAAM,qBAAqB,EAC3B;AAAA,IACC;AAAA,EACF;AACJ,CAAC;","names":["z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/environment.ts","../src/networks.ts","../src/pagination.ts","../src/tokens.ts","../src/charges.ts","../src/distributions.ts","../src/webhook-events.ts","../src/webhooks.ts","../src/api-keys.ts","../src/users.ts","../src/auth.ts","../src/organization.ts","../src/invitations.ts","../src/timeline.ts","../src/verify.ts","../src/health.ts","../src/sandbox.ts","../src/capabilities.ts"],"sourcesContent":["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`, `invalid_credentials`).',\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 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 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","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 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 type { Environment } from './environment'\nimport { OPERATIONAL_NETWORKS } from './networks'\nimport type { Network } 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 — Klap 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 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 { EnvironmentSchema } from './environment'\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`. 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 ChargeModeSchema = z\n .enum(['standard', 'continuous'])\n .describe(\n \"`standard` (default): the usual lifecycle — accumulates transfers toward one resolution (`confirmed`/`expired`/`underpaid`), settles once. `continuous`: never resolves — `status` stays `pending` for the charge's entire life, and every credited transfer settles independently instead of accumulating toward one confirmation (see `charge.contribution_received`/`charge.contribution_settled`). Requires both `amount` and `expiresIn` to be omitted — there's no goal to accumulate toward and no deadline for something meant to run indefinitely (a link in a creator's bio, a permanent collection address). Not inferred from omitting those two fields — an explicit, deliberate choice, since silently changing a charge's entire settlement lifecycle based on which optional fields happened to be left out would be a footgun.\",\n )\nexport type ChargeMode = z.infer<typeof ChargeModeSchema>\n\nexport const CHARGE_EXPIRES_IN_MIN_SECONDS = 60\nexport const CHARGE_EXPIRES_IN_MAX_SECONDS = 365 * 24 * 60 * 60\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_AMOUNT_MAX = 999_999_999_999\n\nexport const CreateChargeSchema = z\n .object({\n mode: ChargeModeSchema.default('standard'),\n amount: z\n .number()\n .positive()\n .max(CHARGE_AMOUNT_MAX)\n .optional()\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. Omit entirely for a charge that accepts any amount — the first credited transfer of any size confirms it, and `isOverpaid` never applies (there is no target to exceed).',\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 .optional()\n .describe(\n 'Seconds, not minutes or milliseconds — how long the charge stays open, min 60, max 31,536,000 = 365 days. Omit entirely for a charge that never expires (`expiresAt` is `null`) — useful for donations, investments, or any charge with no natural deadline. Cannot be extended or shortened after creation either way.',\n ),\n idempotencyKey: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .describe(\n 'Scoped to your organization. Replaying the same key returns the original charge unchanged instead of creating a duplicate — safe to retry a request after a timeout without double-charging.',\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 Klap.',\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: z\n .record(z.string(), z.unknown())\n .optional()\n .describe('Arbitrary key/value data to attach to the charge, returned as-is on every read.'),\n })\n .superRefine((input, ctx) => {\n if (\n input.mode === 'continuous' &&\n (input.amount !== undefined || input.expiresIn !== undefined)\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'mode: \"continuous\" requires both amount and expiresIn to be omitted.',\n path: ['mode'],\n })\n }\n })\n\nexport type CreateChargeInput = z.infer<typeof CreateChargeSchema>\n\nexport const ChargeSchema = z.object({\n id: z\n .string()\n .describe('Klap-generated id, e.g. `ch_...`. Use this to look up the charge later.'),\n mode: ChargeModeSchema,\n amount: z\n .number()\n .nullable()\n .describe(\n 'The amount originally requested, in `currency` units (up to 6 decimal places). `null` if `amount` was omitted at creation — this charge accepts any amount, and the first credited transfer confirms it.',\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` — unless `amount` itself is `null`, in which case `isOverpaid` never applies.',\n ),\n isOverpaid: z\n .boolean()\n .describe(\n '`true` if `amountReceived` ended up greater than `amount`. Klap 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 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, Klap 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: z.record(z.string(), z.unknown()).nullable(),\n createdAt: z.string().datetime(),\n expiresAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When this charge stops accepting payment, if still `pending`/`partially_paid` by then. `null` if `expiresIn` was omitted at creation — the charge never expires on its own and must be dealt with manually (or left open indefinitely).',\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. Only meaningful for a charge with no `expiresAt` — see `pausedAt`.',\n ),\n pausedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'Only ever set for a charge with no `expiresAt`: `null` means Klap is actively watching this address in real time (the normal case). A timestamp means no contribution arrived for longer than the inactivity window (90 days for a charge with a goal `amount`, 365 days for one without), so real-time watching was stopped — the charge itself is never closed, a transfer can still arrive and land, just detected on a much slower fallback poll instead of instantly. Clears automatically (and real-time watching resumes) the moment that happens.',\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 const PaginatedChargesSchema = paginatedSchema(ChargeSchema)\n\nexport type PaginatedCharges = z.infer<typeof PaginatedChargesSchema>\n\nexport const ChargeStatusEventSchema = z.object({\n id: z.string(),\n status: ChargeStatusSchema,\n settlementStatus: SettlementStatusSchema.nullable(),\n amount: z.number().nullable(),\n amountReceived: z.number().nullable(),\n paidWith: z.array(AcceptedPaymentSchema),\n})\n\nexport type ChargeStatusEvent = z.infer<typeof ChargeStatusEventSchema>\n","import { z } from 'zod'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\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 Klap 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 Klap'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 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'\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.paused',\n 'charge.reactivated',\n 'charge.contribution_received',\n 'charge.contribution_settled',\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`). Every event in this category carries the full `Charge` object as `data`, except `charge.paused`/`charge.reactivated`/`charge.contribution_received`/`charge.contribution_settled` (see below). `charge.paused` fires when a charge with no `expiresAt` has had no contribution for longer than its inactivity window (90 days for a charge with a goal `amount`, 365 days for one without) — Klap stops watching its address in real time, but the charge itself is never closed; `charge.reactivated` fires the moment a transfer lands on a paused charge, detected by the same fallback poller used for missed webhooks (so with much higher latency than normal — pausing trades that away deliberately, see `docs/payments.md`). `charge.contribution_received`/`charge.contribution_settled` are exclusive to `mode: continuous` charges (see `Charge.mode`) — a continuous charge never fires `charge.confirmed`/`charge.settled` at all, since `status` never leaves `pending`; instead every individual transfer fires `contribution_received` on detection and `contribution_settled` once its payout completes, one pair-scoped event per contribution instead of one event for the whole charge. `data` for `charge.paused`: `{ chargeId, lastActivityAt, pausedAt }`; for `charge.reactivated`: `{ chargeId, reactivatedAt }`; for `charge.contribution_received`: `{ chargeId, token, network, amount, txHash, payerAddress }`; for `charge.contribution_settled`: `{ chargeId, token, network, amount, txHash, distributorAddress }`.',\n )\n\nexport const AccountWebhookEventTypeSchema = z\n .enum([\n 'payout_address.changed',\n 'api_key.created',\n 'api_key.revoked',\n 'webhook.created',\n 'webhook.deleted',\n 'webhook.secret_rotated',\n 'fee_tier.updated',\n 'member.removed',\n 'member.role_changed',\n 'member.invited',\n ])\n .describe(\n 'Account and configuration changes — not tied to any single charge. `data` per event: `payout_address.changed`: `{ organizationId, from, to }` (`from` nullable); `api_key.created`/`api_key.revoked`: `{ apiKeyId, name, environment, hint }`; `webhook.created`/`webhook.deleted`/`webhook.secret_rotated`: `{ webhookId, url }`; `fee_tier.updated`: `{ organizationId, previousFeePercent, newFeePercent }`; `member.removed`: `{ userId, email, role }`; `member.role_changed`: `{ userId, email, role, previousRole }`; `member.invited`: `{ organizationId, email, role, invitedByUserId }`.',\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 SecurityWebhookEventTypeSchema = z\n .enum([\n 'auth.login',\n 'auth.login_failed',\n 'auth.suspicious_activity',\n 'auth.email_verified',\n 'auth.password_reset_requested',\n 'auth.password_reset_completed',\n ])\n .describe(\n 'Account security signals. `auth.suspicious_activity` is a soft heuristic (login from an IP not seen on this account before), not a block — evaluate it, not enforce against it. `auth.password_reset_requested` only ever dispatches when the requested email actually matches an account (there is nowhere to notify otherwise) — `POST /v1/auth/forgot-password` itself always returns the same generic response either way, so this event never becomes a second channel for the same enumeration question the endpoint response deliberately avoids answering. `data` per event: `auth.login`: `{ userId, ipAddress }`; `auth.login_failed`: `{ email, ipAddress }`; `auth.suspicious_activity`: `{ userId, ipAddress, previousIpAddress }`; `auth.email_verified`/`auth.password_reset_requested`/`auth.password_reset_completed`: `{ userId, email }`.',\n )\n\nexport const WebhookEventTypeSchema = z.union([\n ChargeWebhookEventTypeSchema,\n AccountWebhookEventTypeSchema,\n WebhookDeliveryEventTypeSchema,\n SecurityWebhookEventTypeSchema,\n])\n\nexport type WebhookEventType = z.infer<typeof WebhookEventTypeSchema>\n\nexport const WebhookCategorySchema = z\n .enum(['payments', 'account', 'webhooks', 'security'])\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 AccountWebhookEventTypeSchema.options) map[event] = 'account'\n for (const event of WebhookDeliveryEventTypeSchema.options) map[event] = 'webhooks'\n for (const event of SecurityWebhookEventTypeSchema.options) map[event] = 'security'\n return map\n}\n\n/** Single source of truth for which category each event belongs to — see `webhook-events.test.ts` for the completeness check. */\nexport const EVENT_CATEGORY_MAP = buildCategoryMap()\n\nexport const WEBHOOK_EVENT_CATEGORIES: Record<WebhookCategory, readonly WebhookEventType[]> = {\n payments: ChargeWebhookEventTypeSchema.options,\n account: AccountWebhookEventTypeSchema.options,\n webhooks: WebhookDeliveryEventTypeSchema.options,\n security: SecurityWebhookEventTypeSchema.options,\n}\n\nexport const TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([\n 'charge.created',\n 'charge.paused',\n 'charge.reactivated',\n 'charge.contribution_received',\n 'charge.contribution_settled',\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), `charge.paused`/`charge.reactivated` (driven by a background worker on real inactivity, not a payment state — nothing meaningful to simulate or wait for on a fresh sandbox charge), and `charge.contribution_received`/`charge.contribution_settled` (exclusive to `mode: continuous` charges, which this trigger endpoint does not support simulating today — see `POST /v1/charges/{id}/trigger`'s own description).\",\n)\n\nexport type TriggerableChargeEvent = z.infer<typeof TriggerableChargeEventSchema>\n\nexport const NonChargeTriggerableEventSchema = z.union([\n AccountWebhookEventTypeSchema,\n WebhookDeliveryEventTypeSchema,\n SecurityWebhookEventTypeSchema,\n])\nexport type NonChargeTriggerableEvent = z.infer<typeof NonChargeTriggerableEventSchema>\n","import { z } from 'zod'\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 const WebhookSchema = z.object({\n id: z.string(),\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-Klap-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 — Klap 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('Unique id for this specific delivery — also sent as the `X-Klap-Delivery` header.'),\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; account/security/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 const PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema)\n\nexport type PaginatedWebhookDeliveries = z.infer<typeof PaginatedWebhookDeliveriesSchema>\n","import { z } from 'zod'\nimport { EnvironmentSchema } from './environment'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\n\nexport const CreateApiKeySchema = z.object({\n name: z\n .string()\n .min(1)\n .max(64)\n .describe(\n 'A label to help you tell keys apart (e.g. `\"production backend\"`). Not used for anything functional.',\n ),\n environment: EnvironmentSchema.describe(\n '`live` keys move real funds on Base mainnet; `test` keys settle on Base Sepolia (a real testnet, no real money) and additionally unlock `POST /v1/sandbox/*` for simulating events with zero on-chain activity at all.',\n ),\n})\n\nexport type CreateApiKeyInput = z.infer<typeof CreateApiKeySchema>\n\nexport const ApiKeySchema = z.object({\n id: z.string(),\n name: z.string(),\n environment: EnvironmentSchema.describe(\n '`live` keys authenticate real charges on Base mainnet; `test` keys authenticate the same charge lifecycle on Base Sepolia (a real testnet) and additionally unlock `/v1/sandbox/*` for synthetic event simulation.',\n ),\n key: z\n .string()\n .optional()\n .describe(\n 'The full secret key (`klap_live_...` / `klap_test_...`), used as the `Authorization: Bearer` value on `/v1/charges`, `/v1/webhooks`, and `/v1/sandbox` requests. Present only in the response to `POST /v1/api-keys` — never returned again afterward, so store it immediately.',\n ),\n hint: z\n .string()\n .describe(\n \"A truncated, always-safe-to-display form of the key (e.g. `klap_live_...ab12`), returned everywhere the full key isn't.\",\n ),\n createdAt: z.string().datetime(),\n lastUsedAt: z\n .string()\n .datetime()\n .nullable()\n .describe('Updated on every successful authenticated request. `null` if never used.'),\n createdByUserId: z\n .string()\n .nullable()\n .describe(\n 'Which member of the organization created this key. `null` for a key created before this field existed.',\n ),\n})\n\nexport type ApiKey = z.infer<typeof ApiKeySchema>\n\nexport const ListApiKeysSchema = PaginationQuerySchema\n\nexport type ListApiKeysInput = z.infer<typeof ListApiKeysSchema>\n\nexport const PaginatedApiKeysSchema = paginatedSchema(ApiKeySchema)\n\nexport type PaginatedApiKeys = z.infer<typeof PaginatedApiKeysSchema>\n","import { z } from 'zod'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\n\nexport const UserRoleSchema = z\n .enum(['owner', 'admin', 'member'])\n .describe(\n \"`owner`: full access, and the organization must always keep at least one. `admin`: can manage `member`s but not other `admin`s. `member`: no management permissions. You can only manage a member with a strictly lower role than your own, unless you're an `owner`.\",\n )\nexport type UserRole = z.infer<typeof UserRoleSchema>\n\nexport const UpdateUserRoleSchema = z.object({\n role: UserRoleSchema,\n})\n\nexport type UpdateUserRoleInput = z.infer<typeof UpdateUserRoleSchema>\n\nexport const UserSchema = z.object({\n id: z.string(),\n email: z.string(),\n name: z.string().nullable(),\n role: UserRoleSchema.describe('Your role within the organization this user was fetched from.'),\n emailVerifiedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When this address was confirmed via the emailed verification link. `null` until then. Required (non-null) for two specific actions: creating a `live` API key (`POST /v1/api-keys`) and changing `Organization.payoutAddress` (`PATCH /v1/organization`) — everything else works regardless of verification status.',\n ),\n createdAt: z.string().datetime(),\n})\n\nexport type User = z.infer<typeof UserSchema>\n\nexport const ListUsersSchema = PaginationQuerySchema\n\nexport type ListUsersInput = z.infer<typeof ListUsersSchema>\n\nexport const PaginatedUsersSchema = paginatedSchema(UserSchema)\n\nexport type PaginatedUsers = z.infer<typeof PaginatedUsersSchema>\n","import { z } from 'zod'\nimport { UserSchema } from './users'\n\nexport const NormalizedEmailSchema = z\n .string()\n .trim()\n .max(255)\n .toLowerCase()\n .email()\n .transform((email) => email.normalize('NFC'))\n .describe(\n \"Trimmed, lowercased, and NFC-normalized server-side before use — case/whitespace don't matter.\",\n )\n\nexport const SignupSchema = z.object({\n email: NormalizedEmailSchema,\n password: z.string().min(8).max(128).describe('8-128 characters. No other complexity rule.'),\n})\n\nexport type SignupInput = z.infer<typeof SignupSchema>\n\nexport const LoginSchema = z.object({\n email: NormalizedEmailSchema,\n password: z.string().min(1).max(128),\n})\n\nexport type LoginInput = z.infer<typeof LoginSchema>\n\nexport const VerifyEmailSchema = z.object({\n token: z\n .string()\n .min(1)\n .describe('The token from the verification email — passed as-is, not the account email.'),\n})\nexport type VerifyEmailInput = z.infer<typeof VerifyEmailSchema>\n\nexport const ForgotPasswordSchema = z.object({\n email: NormalizedEmailSchema,\n})\nexport type ForgotPasswordInput = z.infer<typeof ForgotPasswordSchema>\n\nexport const ResetPasswordSchema = z.object({\n token: z.string().min(1).describe('The token from the password reset email.'),\n newPassword: z.string().min(8).max(128),\n})\nexport type ResetPasswordInput = z.infer<typeof ResetPasswordSchema>\n\nexport const MessageResponseSchema = z.object({\n message: z.string().describe('Human-readable confirmation, safe to show a user directly.'),\n})\nexport type MessageResponse = z.infer<typeof MessageResponseSchema>\n\nexport const AuthResponseSchema = z.object({\n token: z\n .string()\n .describe(\n 'Session JWT, valid 7 days — use as `Authorization: Bearer <token>` on every `/v1/organizations/*` request (which nests API keys, members, and invitations — see `GET /v1/organizations`). This token identifies only you; it carries no organization or role — every `/v1/organizations/{id}/*` request is authorized fresh against your actual membership in that specific organization. This is a separate credential from an API key: it authenticates a human/dashboard session, not payment operations. Create an API key with it before you can create charges.',\n ),\n user: UserSchema.omit({ createdAt: true, role: true }),\n})\n\nexport type AuthResponse = z.infer<typeof AuthResponseSchema>\n","import { z } from 'zod'\nimport { PaginationQuerySchema, paginatedSchema } from './pagination'\nimport { UserRoleSchema } from './users'\n\nexport const UpdateOrganizationSchema = z.object({\n name: z.string().min(1).max(255).optional().describe(\"The organization's display name.\"),\n payoutAddress: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/, 'must be a valid EVM address')\n .optional()\n .describe(\n \"The wallet that receives the merchant's share of every future charge. Changing this only affects charges created after the change — an already-created charge's payout split is frozen from creation and is never retroactively affected. Required before you can create any charge. Any casing is accepted — EIP-55 checksum casing is not required or verified.\",\n ),\n})\n\nexport type UpdateOrganizationInput = z.infer<typeof UpdateOrganizationSchema>\n\nexport const OrganizationSchema = z.object({\n id: z.string(),\n name: z.string(),\n payoutAddress: z\n .string()\n .nullable()\n .describe('`null` until configured — `POST /v1/charges` fails until this is set.'),\n currentFeePercent: z\n .number()\n .describe(\n 'Your current platform fee percentage, based on trailing monthly volume — lower volume tiers pay a higher percentage. `1.5` means 1.5%, not a 0–1 fraction. Frozen onto each charge at creation, so this can change between charges without affecting ones already created.',\n ),\n feeUpdatedAt: z.string().datetime().nullable(),\n createdAt: z.string().datetime(),\n})\n\nexport type Organization = z.infer<typeof OrganizationSchema>\n\nexport const OrganizationWithRoleSchema = OrganizationSchema.extend({\n role: UserRoleSchema.describe('Your own role within this specific organization.'),\n})\n\nexport type OrganizationWithRole = z.infer<typeof OrganizationWithRoleSchema>\n\nexport const PaginatedOrganizationsSchema = paginatedSchema(OrganizationWithRoleSchema)\n\nexport type PaginatedOrganizations = z.infer<typeof PaginatedOrganizationsSchema>\n\nexport const ListOrganizationsSchema = PaginationQuerySchema\n\nexport type ListOrganizationsInput = z.infer<typeof ListOrganizationsSchema>\n","import { z } from 'zod'\nimport { NormalizedEmailSchema } from './auth'\nimport { UserRoleSchema } from './users'\n\nexport const InviteUserSchema = z.object({\n email: NormalizedEmailSchema,\n role: UserRoleSchema.default('member').describe(\n 'The role the invitee will hold once they accept — subject to the same management-hierarchy rule as `PATCH /v1/organizations/{id}/users/{userId}`: an `admin` inviter cannot invite an `admin` or `owner`.',\n ),\n})\n\nexport type InviteUserInput = z.infer<typeof InviteUserSchema>\n\nexport const AcceptInvitationSchema = z.object({\n token: z.string().min(1).describe('The token from the invitation email.'),\n password: z\n .string()\n .min(8)\n .max(128)\n .optional()\n .describe(\n 'Required only if the invited email has no existing Klap account — a new account is created along with the membership. Ignored if the account already exists.',\n ),\n})\n\nexport type AcceptInvitationInput = z.infer<typeof AcceptInvitationSchema>\n\nexport const InvitationSchema = z.object({\n id: z.string(),\n organizationId: z.string(),\n email: z.string(),\n role: UserRoleSchema,\n invitedByUserId: z.string().describe('Which member of the organization sent this invitation.'),\n expiresAt: z.string().datetime(),\n createdAt: z.string().datetime(),\n})\n\nexport type Invitation = z.infer<typeof InvitationSchema>\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'\nimport { NetworkSchema } from './networks'\nimport { TokenSchema } from './tokens'\n\nexport const SplitRecipientRoleSchema = z\n .enum(['merchant', 'klap_fee', 'distributor_incentive'])\n .describe(\n '`merchant`: the payout recipient. `klap_fee`: the platform fee. `distributor_incentive`: the (usually small) reward paid to whoever triggered the on-chain settlement — may be Klap or a third party, see `address`.',\n )\nexport type SplitRecipientRole = z.infer<typeof SplitRecipientRoleSchema>\n\nexport const VerifySplitEntrySchema = z.object({\n role: SplitRecipientRoleSchema,\n address: z\n .string()\n .nullable()\n .describe(\n 'On-chain recipient address for this share. For `distributor_incentive`, this is `null` until settlement actually happens — there is no fixed address, it goes to whoever calls the settlement transaction.',\n ),\n percentAllocation: z\n .number()\n .describe(\"This entry's share of `amountReceived`, as a percentage (e.g. `99` = 99%).\"),\n amountUSD: z.number(),\n})\n\nexport const VerifyPaymentSchema = z.object({\n token: TokenSchema,\n network: NetworkSchema,\n amountReceived: z\n .number()\n .describe('Cumulative amount received on this specific `(token, network)` pair.'),\n txHash: z\n .string()\n .describe('The on-chain transaction hash of the most recent transfer on this pair.'),\n explorerTxUrl: z.string().describe('Direct link to `txHash` on the relevant block explorer.'),\n split: z\n .array(VerifySplitEntrySchema)\n .describe(\n \"The exact breakdown of where this pair's payment went — merchant's share, Klap's fee, and (once settled) the settlement incentive.\",\n ),\n splitTxHash: z\n .string()\n .nullable()\n .describe(\n 'Transaction hash of the payout to the merchant for this pair, once settlement has happened. `null` until then.',\n ),\n settledAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n \"When settlement completed for this pair — the merchant's wallet actually has the funds. `null` until then.\",\n ),\n})\nexport type VerifyPayment = z.infer<typeof VerifyPaymentSchema>\n\nexport const VerifyChargeSchema = z.object({\n id: z.string(),\n amount: z\n .number()\n .nullable()\n .describe('The amount originally requested. `null` if the charge accepted any amount.'),\n amountReceived: z\n .number()\n .describe(\n 'The actual cumulative amount received across every contributing pair — can exceed `amount` on an overpayment.',\n ),\n confirmedAt: z\n .string()\n .datetime()\n .nullable()\n .describe(\n 'When the charge reached `confirmed`. `null` for a `mode: continuous` charge — it never reaches a single confirmed moment (`status` stays `pending` for its whole life, see `Charge.mode`); use each entry in `payments[].settledAt` for per-contribution timing instead.',\n ),\n splitAddress: z\n .string()\n .describe(\n 'The on-chain address the payment was sent to — identical across every accepted network.',\n ),\n payments: z\n .array(VerifyPaymentSchema)\n .describe(\n 'One entry per `(token, network)` pair that actually contributed funds — a charge accepting several pairs can be confirmed by a combination of them, each proven and settled independently.',\n ),\n})\n\nexport type VerifyCharge = z.infer<typeof VerifyChargeSchema>\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 { NonChargeTriggerableEventSchema, 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\nexport const SandboxEventTriggerSchema = z.object({\n event: NonChargeTriggerableEventSchema.describe(\n 'Any account, security, or webhook-delivery event — simulates it with synthetic data against your own webhooks, no real state change or precondition required (unlike `POST /v1/sandbox/charges/{id}/trigger`, which acts on a real charge).',\n ),\n})\n\nexport type SandboxEventTriggerInput = z.infer<typeof SandboxEventTriggerSchema>\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"],"mappings":";AAAA,SAAS,SAAS;AAEX,IAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,OAAO,EAAE,OAAO;AAAA,IACd,MAAM,EACH,OAAO,EACP;AAAA,MACC;AAAA,IACF;AAAA,IACF,SAAS,EACN,OAAO,EACP;AAAA,MACC;AAAA,IACF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F,iBAAiBA,IACd,OAAO,EACP,SAAS,kEAAkE;AAAA,EAC9E,+BAA+BA,IAC5B,OAAO,EACP,SAAS,EACT,SAAS,8EAA8E;AAAA,EAC1F,4BAA4BA,IACzB,OAAO,EACP,SAAS,EACT;AAAA,IACC;AAAA,EACF;AACJ,CAAC;;;AC1BD,SAAS,KAAAC,WAAS;AAIX,IAAM,uBAAuBC,IAAE,OAAO;AAAA,EAC3C,OAAO;AAAA,EACP,QAAQA,IACL,OAAO,EACP,SAAS,EACT,IAAI,iBAAiB,EACrB,SAAS,EACT;AAAA,IACC;AAAA,EACF;AACJ,CAAC;AAIM,IAAM,4BAA4BA,IAAE,OAAO;AAAA,EAChD,OAAO,gCAAgC;AAAA,IACrC;AAAA,EACF;AACF,CAAC;;;ACtBD,SAAS,KAAAC,WAAS;AAGX,IAAM,qBAAqBC,IAAE,OAAO;AAAA,EACzC,kBAAkBA,IACf,MAAM,qBAAqB,EAC3B;AAAA,IACC;AAAA,EACF;AACJ,CAAC;","names":["z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z"]}
@@ -0,0 +1,188 @@
1
+ # Auth and accounts
2
+
3
+ Everything here needs a **session token** (a JWT, sent as
4
+ `Authorization: Bearer <token>`), not an API key — a separate credential
5
+ from the one used on `/v1/charges`/`/v1/webhooks`/`/v1/sandbox`. See
6
+ [`tokens-and-networks.md`](./tokens-and-networks.md) for `Token`/
7
+ `Network`, which are unrelated to this auth split despite the similar
8
+ name.
9
+
10
+ **A session token identifies only the signed-in user — never a single
11
+ organization or role.** A user can belong to any number of
12
+ organizations, each with its own role, so nothing below assumes "the"
13
+ organization; every organization-scoped endpoint takes its id as an
14
+ explicit `{id}` path segment, and `GET /v1/organizations` is how you
15
+ discover which id(s) you have.
16
+
17
+ ## Signup and login — `auth.ts`
18
+
19
+ `SignupSchema`/`SignupInput` and `LoginSchema`/`LoginInput` — both
20
+ `{ email, password }`, bodies of `POST /v1/auth/signup` and
21
+ `POST /v1/auth/login`. `email` is trimmed, lowercased, and
22
+ NFC-normalized before validation (internally, via a shared
23
+ `NormalizedEmailSchema` not exported on its own) — `"User@x.com"` and
24
+ `"user@x.com"` are treated as the same account, matching the API's own
25
+ case-insensitive uniqueness check. `signup` also creates a brand-new
26
+ organization, with the new user as its `owner`; `login` doesn't select
27
+ an organization at all.
28
+
29
+ `AuthResponseSchema`/`AuthResponse` is what `signup`, `login`, and
30
+ `POST /v1/invitations/accept` (below) all return: `{ token, user }`.
31
+ `token` is a session JWT valid 7 days — this authenticates a
32
+ human/dashboard session, not payment operations. `user` is pure identity
33
+ — `UserSchema` (see below) minus `createdAt` **and** `role`, since role
34
+ only means something once you've picked which organization. Call
35
+ `GET /v1/organizations` right after to find out which organization(s)
36
+ you belong to and your role in each, then create an API key
37
+ (`POST /v1/organizations/{id}/api-keys`, below) before you can create
38
+ charges.
39
+
40
+ ## Email verification and password reset — `auth.ts`
41
+
42
+ `VerifyEmailSchema`/`VerifyEmailInput` — `{ token }`, body of
43
+ `POST /v1/auth/verify-email`. The token comes from the email `POST
44
+ /v1/auth/signup` sends in the background (or a fresh one from
45
+ `POST /v1/auth/resend-verification`, session-authenticated, no body) —
46
+ single-use, expires 24h after issuance. Two things are gated on it:
47
+ creating a `live` API key (`POST /v1/organizations/{id}/api-keys`,
48
+ below) and changing `payoutAddress`
49
+ (`PATCH /v1/organizations/{id}`, below) both require a verified email,
50
+ returning `403 email_not_verified` otherwise — `test` API keys have no
51
+ such requirement. `User.emailVerifiedAt` (see `UserSchema` below)
52
+ reflects the current state.
53
+
54
+ `ForgotPasswordSchema`/`ForgotPasswordInput` — `{ email }`, body of
55
+ `POST /v1/auth/forgot-password`. Always get the same generic
56
+ `MessageResponse` back regardless of whether the email matches an
57
+ account — this is the one endpoint in the API that actually closes
58
+ account enumeration, rather than accepting it as a tradeoff (unlike
59
+ signup's `422 email_taken`).
60
+
61
+ `ResetPasswordSchema`/`ResetPasswordInput` — `{ token, newPassword }`,
62
+ body of `POST /v1/auth/reset-password`. The token expires 1 hour after a
63
+ `forgot-password` call. A successful reset invalidates every other
64
+ outstanding reset token for that account, **and every session token
65
+ issued before the reset** — the next request with an old session gets
66
+ `401 invalid_session`, even though the JWT itself hasn't reached its
67
+ 7-day expiry.
68
+
69
+ `MessageResponseSchema`/`MessageResponse` — `{ message }`, the shared
70
+ response shape for all four of the endpoints above (chosen over an
71
+ empty `204` since a human-readable confirmation is more useful to show
72
+ directly in a UI for these specifically).
73
+
74
+ ## Organizations — `organization.ts`
75
+
76
+ `ListOrganizationsSchema`/`PaginatedOrganizationsSchema` are the
77
+ query/response shapes for `GET /v1/organizations` — every organization
78
+ the caller belongs to, each entry an `OrganizationWithRoleSchema` (see
79
+ below). Same shared `{ limit, cursor }` → `{ data, nextCursor, hasMore }`
80
+ cursor pagination every list endpoint uses, see
81
+ [`charges.md`](./charges.md#the-shared-cursor-pagination-pattern). This
82
+ is the starting point for every other endpoint on this page — there's no
83
+ other way to learn which organization id(s) a session token can act on.
84
+
85
+ `UpdateOrganizationSchema`/`UpdateOrganizationInput` — `{ name?,
86
+ payoutAddress? }`, body of `PATCH /v1/organizations/{id}`.
87
+ `payoutAddress` is an EVM address, regex-validated
88
+ (`/^0x[a-fA-F0-9]{40}$/`); required before that organization can create
89
+ any charge, and requires a verified email when actually changing
90
+ (`403 email_not_verified` otherwise — see the email verification section
91
+ above). Changing it only affects charges created **after** the change —
92
+ an already-created charge's payout split is frozen at creation time and
93
+ is never retroactively affected. `name` has no such gate.
94
+
95
+ `OrganizationSchema`/`Organization` is the read shape returned by
96
+ `GET`/`PATCH /v1/organizations/{id}` — notably `currentFeePercent`, the
97
+ organization's platform fee based on trailing monthly volume, which is
98
+ likewise frozen onto each charge at creation (so it can change between
99
+ charges without affecting ones already made).
100
+ `OrganizationWithRoleSchema`/`OrganizationWithRole` extends it with
101
+ `role` — only present on the `GET /v1/organizations` list response,
102
+ where "your role in *this* one" is meaningful; the single-organization
103
+ `GET`/`PATCH` endpoints don't repeat it.
104
+
105
+ ## Members and roles — `users.ts`
106
+
107
+ `UserRoleSchema`/`UserRole` — `'owner' | 'admin' | 'member'`. An
108
+ organization must always keep at least one `owner`. An `admin` can
109
+ manage `member`s but not other `admin`s; you can only manage a user with
110
+ a strictly lower role than your own, unless you're an `owner` — this
111
+ applies identically to changing a role and to inviting one (see
112
+ "Invitations" below).
113
+
114
+ `UpdateUserRoleSchema`/`UpdateUserRoleInput` — `{ role }`, body of
115
+ `PATCH /v1/organizations/{id}/users/{userId}`, for changing an existing
116
+ member's role *within that organization*. `UserSchema`/`User` is the
117
+ read shape returned there and by `GET /v1/organizations/{id}/users` —
118
+ `role` is that member's role in the organization the request was scoped
119
+ to (a `User` has no single global role, since the same person can be a
120
+ `member` of one organization and an `owner` of another).
121
+ `emailVerifiedAt` (nullable timestamp) reflects whether the address was
122
+ confirmed via `POST /v1/auth/verify-email` — it gates two things
123
+ elsewhere in the API (creating a `live` API key, changing
124
+ `payoutAddress` — see above) but doesn't restrict a `member` based on
125
+ role by itself; it's there for your own integration's policy to read
126
+ too.
127
+
128
+ `ListUsersSchema`/`PaginatedUsersSchema` are the query/response shapes
129
+ for `GET /v1/organizations/{id}/users` — same shared cursor pagination
130
+ as `GET /v1/organizations` above.
131
+
132
+ ## Invitations — `invitations.ts`
133
+
134
+ `InviteUserSchema`/`InviteUserInput` — `{ email, role }` (`role` defaults
135
+ to `member`), body of `POST /v1/organizations/{id}/invitations`. Subject
136
+ to the identical role-hierarchy rule as `UpdateUserRoleSchema` above —
137
+ an `admin` inviter can't invite an `admin` or `owner`. Sends a
138
+ single-use, plain-text email code (via Resend, no clickable link — same
139
+ pattern as email verification/password reset), valid 7 days.
140
+ `InvitationSchema`/`Invitation` is the response shape — `{ id,
141
+ organizationId, email, role, invitedByUserId, expiresAt, createdAt }`,
142
+ no token (the raw code only ever reaches the invitee, via email). Keep
143
+ the returned `id` if you need to
144
+ `DELETE /v1/organizations/{id}/invitations/{invitationId}` later.
145
+
146
+ `AcceptInvitationSchema`/`AcceptInvitationInput` — `{ token,
147
+ password? }`, body of `POST /v1/invitations/accept`. **No session
148
+ token required** — the code itself is the proof, same model as
149
+ `VerifyEmailSchema` above. If the invited email already has a Klap
150
+ account, `password` is ignored and the membership is just added to it
151
+ (any other organizations that account already belongs to are
152
+ untouched); if it doesn't, `password` is required (same `8-128`-char
153
+ rule as `SignupSchema`) and a new account is created along with the
154
+ membership, in one step. Returns an `AuthResponse` either way.
155
+
156
+ ## API keys — `api-keys.ts`
157
+
158
+ `CreateApiKeySchema`/`CreateApiKeyInput` — `{ name, environment }`, the
159
+ body of `POST /v1/organizations/{id}/api-keys`. `environment`
160
+ (`live`/`test`, see [`charges.md`](./charges.md)'s `EnvironmentSchema`)
161
+ decides everything about the resulting key: `live` keys move real funds
162
+ on Base mainnet; `test` keys settle the same charge lifecycle on Base
163
+ Sepolia (a real testnet — real on-chain activity, never real money) and
164
+ additionally unlock `POST /v1/sandbox/*` (see [`sandbox.md`](./sandbox.md))
165
+ for simulating events with zero on-chain activity at all. Creating a
166
+ `live` key requires a verified email (`403 email_not_verified`
167
+ otherwise) — `test` keys have no such requirement.
168
+
169
+ `ApiKeySchema`/`ApiKey` is the response shape. `key` (the full secret,
170
+ `klap_live_.../klap_test_...`) is present **only** in the response to
171
+ creation — every later read/list returns `hint` instead (a
172
+ truncated, always-safe-to-display form like `klap_live_...ab12`). Store
173
+ `key` immediately; it cannot be retrieved again.
174
+
175
+ `ListApiKeysSchema`/`PaginatedApiKeysSchema` are the query/response
176
+ shapes for `GET /v1/organizations/{id}/api-keys` — same shared
177
+ `{ limit, cursor }` → `{ data, nextCursor, hasMore }` cursor pagination
178
+ every list endpoint uses, see
179
+ [`charges.md`](./charges.md#the-shared-cursor-pagination-pattern).
180
+
181
+ ## See also
182
+
183
+ - [`charges.md`](./charges.md) — `EnvironmentSchema` (`live`/`test`),
184
+ referenced by both API keys and charges.
185
+ - [`webhooks.md`](./webhooks.md) — the `account`/`security` category
186
+ events these resources emit (`payout_address.changed`,
187
+ `api_key.created`, `member.role_changed`, `member.invited`,
188
+ `auth.login`, ...).