@klappay/types 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  var ErrorPayloadSchema = z.object({
4
4
  error: z.object({
5
5
  code: z.string().describe(
6
- "A stable, machine-readable error identifier (e.g. `validation_error`, `invalid_credentials`)."
6
+ "A stable, machine-readable error identifier (e.g. `validation_error`, `charge_not_found`)."
7
7
  ),
8
8
  message: z.string().describe(
9
9
  "Human-readable explanation, safe to log or show a developer \u2014 not meant for end users."
@@ -18,9 +18,27 @@ var EnvironmentSchema = z2.enum(["live", "test"]).describe(
18
18
  "`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 \u2014 real on-chain activity, but never real money."
19
19
  );
20
20
 
21
- // src/networks.ts
21
+ // src/api-key-scopes.ts
22
22
  import { z as z3 } from "zod";
23
- var NetworkSchema = z3.enum(["base", "optimism", "polygon", "ethereum", "arbitrum", "avalanche", "bnb"]).describe("The blockchain a charge/payment is on.");
23
+ var ApiKeyScopeSchema = z3.enum([
24
+ "charges:read",
25
+ "charges:write",
26
+ "webhooks:read",
27
+ "webhooks:write",
28
+ "webhooks:manage_secret",
29
+ "metrics:read",
30
+ "metrics:charges:read",
31
+ "metrics:transactions:read",
32
+ "metrics:distributions:read",
33
+ "sandbox:trigger"
34
+ ]).describe(
35
+ "What an API key is allowed to do, independent of `tenantId`/`environment` (which scope *whose* data, not *what actions*). A key with none of these can still authenticate but every scoped route rejects it with `403 insufficient_scope`. `metrics:read` alone grants every metrics resource; `metrics:{resource}:read` grants only that one \u2014 a key can hold either or both."
36
+ );
37
+ var API_KEY_SCOPES = ApiKeyScopeSchema.options;
38
+
39
+ // src/networks.ts
40
+ import { z as z4 } from "zod";
41
+ var NetworkSchema = z4.enum(["base", "optimism", "polygon", "ethereum", "arbitrum", "avalanche", "bnb"]).describe("The blockchain a charge/payment is on.");
24
42
  var NETWORK_LABELS = {
25
43
  base: "Base",
26
44
  optimism: "Optimism",
@@ -59,29 +77,29 @@ var OPERATIONAL_NETWORKS = [
59
77
  ];
60
78
 
61
79
  // src/pagination.ts
62
- import { z as z4 } from "zod";
80
+ import { z as z5 } from "zod";
63
81
  var PAGINATION_LIMIT_MIN = 1;
64
82
  var PAGINATION_LIMIT_MAX = 100;
65
83
  var PAGINATION_LIMIT_DEFAULT = 20;
66
- var PaginationQuerySchema = z4.object({
67
- limit: z4.coerce.number().min(PAGINATION_LIMIT_MIN).max(PAGINATION_LIMIT_MAX).default(PAGINATION_LIMIT_DEFAULT).describe(
84
+ var PaginationQuerySchema = z5.object({
85
+ limit: z5.coerce.number().min(PAGINATION_LIMIT_MIN).max(PAGINATION_LIMIT_MAX).default(PAGINATION_LIMIT_DEFAULT).describe(
68
86
  `Max items to return per page (${PAGINATION_LIMIT_MIN}\u2013${PAGINATION_LIMIT_MAX}, default ${PAGINATION_LIMIT_DEFAULT}).`
69
87
  ),
70
- cursor: z4.string().max(500).optional().describe(
88
+ cursor: z5.string().max(500).optional().describe(
71
89
  "Opaque \u2014 pass the previous response's `nextCursor` verbatim to fetch the next page. Never construct or parse this value yourself; its shape is not part of the public contract and may change."
72
90
  )
73
91
  });
74
92
  function paginatedSchema(itemSchema) {
75
- return z4.object({
76
- data: z4.array(itemSchema),
77
- nextCursor: z4.string().nullable().describe("Pass as `cursor` to fetch the next page. `null` when there are no more results."),
78
- hasMore: z4.boolean()
93
+ return z5.object({
94
+ data: z5.array(itemSchema),
95
+ nextCursor: z5.string().nullable().describe("Pass as `cursor` to fetch the next page. `null` when there are no more results."),
96
+ hasMore: z5.boolean()
79
97
  });
80
98
  }
81
99
 
82
100
  // src/tokens.ts
83
- import { z as z5 } from "zod";
84
- var TokenSchema = z5.enum(["USDC", "USDT"]).describe(
101
+ import { z as z6 } from "zod";
102
+ var TokenSchema = z6.enum(["USDC", "USDT"]).describe(
85
103
  `Which stablecoin the payer will send. Support depends on both \`network\` and \`environment\` \u2014 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 \u2014 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** \u2014 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 \u2014 Klappay does not verify or guarantee Binance's collateral backing it. \`USDT\` on BNB Chain is Tether's own official issuance, same trust model as everywhere else. More tokens/networks are expected to be added over time \u2014 check \`TOKEN_ADDRESSES\` in \`@klappay/types\` (or a future \`GET /v1/networks\` capabilities endpoint) for the exact current matrix rather than assuming full coverage.`
86
104
  );
87
105
  var TOKEN_DECIMALS = 6;
@@ -116,30 +134,27 @@ var TOKEN_ADDRESSES = {
116
134
  };
117
135
 
118
136
  // src/charges.ts
119
- import { z as z6 } from "zod";
120
- var ChargeStatusSchema = z6.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid", "canceled"]).describe(
121
- "Payment progress, from the payer side. `pending`: created, nothing received yet. `partially_paid`: some funds received, less than `amount`. `confirmed`: full amount received (or more \u2014 see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. `canceled`: the merchant explicitly canceled it via `POST /v1/charges/{id}/cancel` before it resolved on its own \u2014 unlike every other terminal status, this one is never reached automatically. This never reflects whether funds actually reached the merchant \u2014 see `settlementStatus` for that."
137
+ import { z as z7 } from "zod";
138
+ var ChargeStatusSchema = z7.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
139
+ "Payment progress, from the payer side. `pending`: created, nothing received yet. `partially_paid`: some funds received, less than `amount`. `confirmed`: full amount received (or more \u2014 see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. Every status is reached automatically, on its own timeline \u2014 there is no merchant-initiated cancellation. This never reflects whether funds actually reached the merchant \u2014 see `settlementStatus` for that."
122
140
  );
123
- var SettlementStatusSchema = z6.enum(["pending", "completed", "failed"]).describe(
141
+ var SettlementStatusSchema = z7.enum(["pending", "completed", "failed"]).describe(
124
142
  "Progress of the payout to the merchant's wallet, a separate step from `status` \u2014 `status: confirmed` only means the payment was detected on-chain, not that the merchant has been paid yet. `pending`: payment detected, payout not yet attempted. `completed`: the merchant's wallet has the funds. `failed`: the payout attempt failed and retries were exhausted (rare; contact support). `null` on the parent `Charge` means no payout has been attempted yet \u2014 nothing has been received, or the charge is still in progress."
125
143
  );
126
- var ChargeModeSchema = z6.enum(["standard", "continuous"]).describe(
127
- "`standard` (default): the usual lifecycle \u2014 accumulates transfers toward one resolution (`confirmed`/`expired`/`underpaid`), settles once. `continuous`: never resolves \u2014 `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 \u2014 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 \u2014 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."
128
- );
129
144
  var CHARGE_EXPIRES_IN_MIN_SECONDS = 60;
130
- var CHARGE_EXPIRES_IN_MAX_SECONDS = 365 * 24 * 60 * 60;
145
+ var CHARGE_EXPIRES_IN_MAX_SECONDS = 3600;
131
146
  var CHARGE_ACCEPTED_PAYMENTS_MAX = 14;
132
- var AcceptedPaymentSchema = z6.object({
147
+ var AcceptedPaymentSchema = z7.object({
133
148
  token: TokenSchema,
134
149
  network: NetworkSchema
135
150
  });
136
- var AcceptedPaymentsSchema = z6.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
151
+ var AcceptedPaymentsSchema = z7.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
137
152
  const seen = /* @__PURE__ */ new Set();
138
153
  pairs.forEach((pair, index) => {
139
154
  const key = `${pair.token}:${pair.network}`;
140
155
  if (seen.has(key)) {
141
156
  ctx.addIssue({
142
- code: z6.ZodIssueCode.custom,
157
+ code: z7.ZodIssueCode.custom,
143
158
  message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,
144
159
  path: [index]
145
160
  });
@@ -147,7 +162,7 @@ var AcceptedPaymentsSchema = z6.array(AcceptedPaymentSchema).min(1, "At least on
147
162
  seen.add(key);
148
163
  if (!OPERATIONAL_NETWORKS.includes(pair.network)) {
149
164
  ctx.addIssue({
150
- code: z6.ZodIssueCode.custom,
165
+ code: z7.ZodIssueCode.custom,
151
166
  message: `Network "${pair.network}" isn't live yet \u2014 only ${OPERATIONAL_NETWORKS.join(", ")} today.`,
152
167
  path: [index, "network"]
153
168
  });
@@ -157,88 +172,70 @@ var AcceptedPaymentsSchema = z6.array(AcceptedPaymentSchema).min(1, "At least on
157
172
  `Every \`(token, network)\` pair the payer is allowed to pay with \u2014 at least one, up to ${CHARGE_ACCEPTED_PAYMENTS_MAX}. This list is also the only restriction knob: the payer can use any combination of the pairs listed here, and every transfer on one of them is credited and sums toward the charge total (see \`paidWith\`) \u2014 e.g. a charge accepting USDC and USDT can be confirmed by $9 in USDC plus $1 in USDT, or by USDC arriving on two different accepted networks. To require payment in one specific token on one specific network, list only that single pair \u2014 a transfer on any pair not in this list is still recorded (for audit) but never credited. Each network must be live (see \`GET /v1/networks\` for the current matrix) \u2014 an unconfigured \`(token, network)\` combination for your environment is rejected with \`422 token_not_supported\`.`
158
173
  );
159
174
  var CHARGE_AMOUNT_MAX = 999999999999;
160
- var CreateChargeSchema = z6.object({
161
- mode: ChargeModeSchema.default("standard"),
162
- amount: z6.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
163
- "Amount to charge, in `currency` units (e.g. `49.9` = $49.90) \u2014 up to 6 decimal places; anything more precise is silently truncated. Omit entirely for a charge that accepts any amount \u2014 the first credited transfer of any size confirms it, and `isOverpaid` never applies (there is no target to exceed)."
175
+ var CreateChargeSchema = z7.object({
176
+ amount: z7.number().positive().max(CHARGE_AMOUNT_MAX).describe(
177
+ "Amount to charge, in `currency` units (e.g. `49.9` = $49.90) \u2014 up to 6 decimal places; anything more precise is silently truncated. Required \u2014 every charge has a target amount, the first credited transfer that reaches it confirms the charge."
164
178
  ),
165
- currency: z6.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
179
+ currency: z7.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
166
180
  acceptedPayments: AcceptedPaymentsSchema,
167
- expiresIn: z6.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).optional().describe(
168
- "Seconds, not minutes or milliseconds \u2014 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`) \u2014 useful for donations, investments, or any charge with no natural deadline. Cannot be extended or shortened after creation either way."
181
+ expiresIn: z7.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
182
+ "Seconds, not minutes or milliseconds \u2014 how long the charge stays open before it expires. Required, min 60, max 3600 (60 minutes) \u2014 sized off the slowest chain Klappay supports today (Ethereum mainnet, where a safely-confirmed transfer takes up to ~15 minutes), leaving real margin for payer-side delay (gas spikes, wallet friction) on top of that. Cannot be extended or shortened after creation."
169
183
  ),
170
- idempotencyKey: z6.string().min(1).max(255).optional().describe(
171
- "Scoped to your organization. Replaying the same key returns the original charge unchanged instead of creating a duplicate \u2014 safe to retry a request after a timeout without double-charging."
184
+ idempotencyKey: z7.string().min(1).max(255).optional().describe(
185
+ "Scoped to your tenant. Replaying the same key returns the original charge unchanged instead of creating a duplicate \u2014 safe to retry a request after a timeout without double-charging."
172
186
  ),
173
- externalRef: z6.string().min(1).max(255).optional().describe(
187
+ externalRef: z7.string().min(1).max(255).optional().describe(
174
188
  "An opaque correlation id from your own system (e.g. an order id) \u2014 echoed back on the charge and in every webhook payload. Not interpreted or validated by Klappay."
175
189
  ),
176
- source: z6.string().min(1).max(64).optional().describe(
190
+ source: z7.string().min(1).max(64).optional().describe(
177
191
  'Free-form label for what created this charge (e.g. `"checkout"`, `"invoice"`) \u2014 useful if you create charges from more than one flow and want to tell them apart later. Not a fixed enum; use whatever values make sense to you.'
178
192
  ),
179
- metadata: z6.record(z6.string(), z6.unknown()).optional().describe("Arbitrary key/value data to attach to the charge, returned as-is on every read.")
180
- }).superRefine((input, ctx) => {
181
- if (input.mode === "continuous" && (input.amount !== void 0 || input.expiresIn !== void 0)) {
182
- ctx.addIssue({
183
- code: z6.ZodIssueCode.custom,
184
- message: 'mode: "continuous" requires both amount and expiresIn to be omitted.',
185
- path: ["mode"]
186
- });
187
- }
193
+ metadata: z7.record(z7.string(), z7.unknown()).optional().describe("Arbitrary key/value data to attach to the charge, returned as-is on every read.")
188
194
  });
189
- var ChargeSchema = z6.object({
190
- id: z6.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
191
- mode: ChargeModeSchema,
192
- amount: z6.number().nullable().describe(
193
- "The amount originally requested, in `currency` units (up to 6 decimal places). `null` if `amount` was omitted at creation \u2014 this charge accepts any amount, and the first credited transfer confirms it."
194
- ),
195
- amountReceived: z6.number().nullable().describe(
196
- "Cumulative amount actually received on-chain so far, in `currency` units (up to 6 decimal places). `null` until the first transfer arrives. Can exceed `amount` \u2014 see `isOverpaid` \u2014 unless `amount` itself is `null`, in which case `isOverpaid` never applies."
195
+ var ChargeSchema = z7.object({
196
+ id: z7.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
197
+ amount: z7.number().describe("The amount originally requested, in `currency` units (up to 6 decimal places)."),
198
+ amountReceived: z7.number().nullable().describe(
199
+ "Cumulative amount actually received on-chain so far, in `currency` units (up to 6 decimal places). `null` until the first transfer arrives. Can exceed `amount` \u2014 see `isOverpaid`."
197
200
  ),
198
- isOverpaid: z6.boolean().describe(
201
+ isOverpaid: z7.boolean().describe(
199
202
  "`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically \u2014 see the docs for why."
200
203
  ),
201
- currency: z6.string().describe("Always `USD` today \u2014 the only supported currency."),
202
- acceptedPayments: z6.array(AcceptedPaymentSchema).describe(
204
+ currency: z7.string().describe("Always `USD` today \u2014 the only supported currency."),
205
+ acceptedPayments: z7.array(AcceptedPaymentSchema).describe(
203
206
  "Every `(token, network)` pair this charge was configured to accept, unchanged after creation."
204
207
  ),
205
- paidWith: z6.array(AcceptedPaymentSchema).describe(
208
+ paidWith: z7.array(AcceptedPaymentSchema).describe(
206
209
  "Every distinct `(token, network)` pair that has actually contributed a credited transfer so far \u2014 empty until the first one arrives. Can hold more than one entry: a charge accepting several pairs can be paid across a combination of them, and every entry here sums toward `amountReceived`."
207
210
  ),
208
- address: z6.string().describe(
211
+ address: z7.string().describe(
209
212
  "The on-chain address the payer must send funds to \u2014 identical across every accepted network (0xSplits addresses are chain-agnostic). Unique per charge, predicted at creation time \u2014 funds sent here go directly to the merchant, Klappay never custodies them."
210
213
  ),
211
214
  status: ChargeStatusSchema,
212
215
  settlementStatus: SettlementStatusSchema.nullable(),
213
216
  environment: EnvironmentSchema,
214
- apiKeyId: z6.string().nullable().describe(
217
+ apiKeyId: z7.string().nullable().describe(
215
218
  "Which of your API keys created this charge. `null` for a charge created before this field existed."
216
219
  ),
217
- txHash: z6.string().nullable().describe(
220
+ txHash: z7.string().nullable().describe(
218
221
  "Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected."
219
222
  ),
220
- externalRef: z6.string().nullable(),
221
- source: z6.string().nullable(),
222
- metadata: z6.record(z6.string(), z6.unknown()).nullable(),
223
- createdAt: z6.string().datetime(),
224
- expiresAt: z6.string().datetime().nullable().describe(
225
- "When this charge stops accepting payment, if still `pending`/`partially_paid` by then. `null` if `expiresIn` was omitted at creation \u2014 the charge never expires on its own and must be dealt with manually (or left open indefinitely)."
223
+ externalRef: z7.string().nullable(),
224
+ source: z7.string().nullable(),
225
+ metadata: z7.record(z7.string(), z7.unknown()).nullable(),
226
+ createdAt: z7.string().datetime(),
227
+ expiresAt: z7.string().datetime().describe(
228
+ "When this charge stops accepting payment, if still `pending`/`partially_paid` by then."
226
229
  ),
227
- confirmedAt: z6.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
228
- settledAt: z6.string().datetime().nullable().describe(
230
+ confirmedAt: z7.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
231
+ settledAt: z7.string().datetime().nullable().describe(
229
232
  "When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
230
233
  ),
231
- lastActivityAt: z6.string().datetime().describe(
232
- "When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet. Only meaningful for a charge with no `expiresAt` \u2014 see `pausedAt`."
233
- ),
234
- pausedAt: z6.string().datetime().nullable().describe(
235
- "Only ever set for a charge with no `expiresAt`: `null` means Klappay 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 \u2014 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."
236
- ),
237
- canceledAt: z6.string().datetime().nullable().describe(
238
- "When `POST /v1/charges/{id}/cancel` was called. `null` unless `status` is `canceled`. Unlike `pausedAt`, this never clears automatically \u2014 real-time watching is stopped the same way, but a transfer landing afterward doesn't revert the charge to `pending`; it fires `charge.paid_after_cancel` instead, since resuming silently would contradict the merchant's explicit cancellation."
234
+ lastActivityAt: z7.string().datetime().describe(
235
+ "When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet."
239
236
  )
240
237
  });
241
- var ListChargesSchema = z6.object({
238
+ var ListChargesSchema = z7.object({
242
239
  status: ChargeStatusSchema.optional(),
243
240
  token: TokenSchema.optional().describe(
244
241
  "Filters on `paidWith.token` \u2014 the pair actually paid, not accepted."
@@ -247,55 +244,19 @@ var ListChargesSchema = z6.object({
247
244
  "Filters on `paidWith.network` \u2014 the pair actually paid, not accepted."
248
245
  ),
249
246
  environment: EnvironmentSchema.optional(),
250
- since: z6.string().datetime().optional().describe(
247
+ since: z7.string().datetime().optional().describe(
251
248
  "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."
252
249
  ),
253
- isOverpaid: z6.enum(["true", "false"]).transform((v) => v === "true").optional()
250
+ isOverpaid: z7.enum(["true", "false"]).transform((v) => v === "true").optional()
254
251
  }).extend(PaginationQuerySchema.shape);
255
252
  var PaginatedChargesSchema = paginatedSchema(ChargeSchema);
256
- var GetChargeQrCodeQuerySchema = z6.object({
253
+ var GetChargeQrCodeQuerySchema = z7.object({
257
254
  token: TokenSchema.optional().describe(
258
255
  "Which accepted `(token, network)` pair to encode in the QR \u2014 required if `acceptedPayments` has more than one pair, since there is no single unambiguous default to fall back to. Ignored (and unnecessary) when the charge accepts exactly one pair."
259
256
  ),
260
257
  network: NetworkSchema.optional()
261
258
  });
262
259
 
263
- // src/public-charges.ts
264
- import { z as z7 } from "zod";
265
- var PublicChargeSchema = z7.object({
266
- id: z7.string(),
267
- mode: ChargeModeSchema,
268
- status: ChargeStatusSchema,
269
- settlementStatus: SettlementStatusSchema.nullable(),
270
- amount: z7.number().nullable(),
271
- amountReceived: z7.number().nullable(),
272
- isOverpaid: z7.boolean(),
273
- currency: z7.string(),
274
- acceptedPayments: z7.array(AcceptedPaymentSchema),
275
- paidWith: z7.array(AcceptedPaymentSchema),
276
- address: z7.string(),
277
- environment: EnvironmentSchema,
278
- txHash: z7.string().nullable(),
279
- metadata: z7.record(z7.unknown()).nullable().describe(
280
- "Redacted \u2014 everything the merchant put in `Charge.metadata` is stripped except the reserved `klappay` key (for Klappay-internal product integrations, e.g. this endpoint's own checkout consumer), if present. `null` if there's no `klappay` key, even when the merchant's own metadata is otherwise non-empty."
281
- ),
282
- createdAt: z7.string().datetime(),
283
- expiresAt: z7.string().datetime().nullable(),
284
- confirmedAt: z7.string().datetime().nullable(),
285
- settledAt: z7.string().datetime().nullable(),
286
- lastActivityAt: z7.string().datetime(),
287
- pausedAt: z7.string().datetime().nullable(),
288
- canceledAt: z7.string().datetime().nullable()
289
- });
290
- var GetPublicChargeQuerySchema = z7.object({
291
- environment: EnvironmentSchema.describe(
292
- "Which environment this charge is expected to be in. Required, not inferred \u2014 there's no API key here to derive it from, and stating it explicitly catches an integration bug (e.g. a `test` chargeId reaching a `live` checkout flow) instead of silently trusting whatever environment the id happens to belong to. A mismatch is indistinguishable from the charge not existing at all (`404`), same anti-enumeration posture as every other case below."
293
- )
294
- });
295
- var GetPublicChargeQrCodeQuerySchema = GetPublicChargeQuerySchema.extend(
296
- GetChargeQrCodeQuerySchema.shape
297
- );
298
-
299
260
  // src/distributions.ts
300
261
  import { z as z8 } from "zod";
301
262
  var SplitDistributionStatusSchema = z8.enum(["pending", "processing", "completed", "failed"]).describe(
@@ -351,11 +312,11 @@ var MetricsAggregationSchema = z9.enum(["count", "sum", "avg", "min", "max"]).de
351
312
  var MetricsFilterOperatorSchema = z9.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
352
313
  "`in` expects an array value (max 50 entries); every other operator expects a single scalar."
353
314
  );
354
- var MetricsDateGranularitySchema = z9.enum(["day", "week", "month"]).describe(
315
+ var MetricsDateGranularitySchema = z9.enum(["day", "week", "month", "year"]).describe(
355
316
  "Bucket width for a `date_bucket` `groupBy` entry \u2014 Postgres `date_trunc` semantics (UTC)."
356
317
  );
357
318
  var metricsQueryEnvironmentSchema = EnvironmentSchema.describe(
358
- "Which environment's data to query \u2014 `live` or `test`. Independent of your session (a dashboard user isn't scoped to one environment the way an API key is) \u2014 scopes the query to charges/transactions/distributions created under a `live` or `test` API key respectively."
319
+ "Which environment's data to query \u2014 `live` or `test`. Must match the environment of the API key used to authenticate \u2014 scopes the query to charges/transactions/distributions created under a `live` or `test` API key respectively."
359
320
  );
360
321
  var MAX_METRICS_QUERY_DATE_RANGE_DAYS = 366;
361
322
  var METRICS_QUERY_MAX_ROW_LIMIT = 1e3;
@@ -388,14 +349,14 @@ var orderBySchema = z9.object({
388
349
  var limitSchema = z9.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
389
350
  `Max rows to return, ${1}\u2013${METRICS_QUERY_MAX_ROW_LIMIT}, default ${METRICS_QUERY_DEFAULT_ROW_LIMIT}. If more rows matched, \`meta.truncated\` is \`true\` on the response \u2014 narrow the query instead of just raising this.`
390
351
  );
391
- var ChargesQueryFieldSchema = z9.enum(["status", "mode", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
392
- "A `Charge` field to filter or group by \u2014 see `ChargeStatusSchema`/`ChargeModeSchema` for `status`/`mode`'s own possible values (charges.md). `source`/`externalRef` are free-form strings your own integration set at creation, not a fixed enum."
352
+ var ChargesQueryFieldSchema = z9.enum(["status", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
353
+ "A `Charge` field to filter or group by \u2014 see `ChargeStatusSchema` for `status`'s own possible values (charges.md). `source`/`externalRef` are free-form strings your own integration set at creation, not a fixed enum."
393
354
  );
394
355
  var ChargesMetricFieldSchema = z9.enum(["amount", "amountReceived", "feePercent"]).describe(
395
356
  "A `Charge` numeric field to aggregate. `amount`/`amountReceived` are decimal currency amounts (requested vs. actually received \u2014 see `charges.md`). `feePercent` is the platform fee frozen on the charge at creation, e.g. `1.5` means 1.5%."
396
357
  );
397
- var ChargesDateFieldSchema = z9.enum(["createdAt", "confirmedAt", "lastActivityAt"]).describe(
398
- "A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` \u2014 a `dateRange`/`date_bucket` on it implicitly excludes every charge that never confirmed."
358
+ var ChargesDateFieldSchema = z9.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt"]).describe(
359
+ "A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` \u2014 a `dateRange`/`date_bucket` on it implicitly excludes every charge that never confirmed. `expiresAt` is always present (set at creation), useful for e.g. finding charges expiring soon or measuring how close to expiry charges typically resolve."
399
360
  );
400
361
  var ChargesFilterSchema = z9.object({
401
362
  field: ChargesQueryFieldSchema,
@@ -466,14 +427,14 @@ var TransactionsMetricsQuerySchema = z9.object({
466
427
  orderBy: orderBySchema.optional(),
467
428
  limit: limitSchema
468
429
  });
469
- var DistributionsQueryFieldSchema = z9.enum(["status", "network", "token"]).describe(
470
- "A `SplitDistribution` field to filter or group by \u2014 see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values."
430
+ var DistributionsQueryFieldSchema = z9.enum(["status", "network", "token", "distributorAddress"]).describe(
431
+ "A `SplitDistribution` field to filter or group by \u2014 see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values. `distributorAddress` is the public on-chain address that actually called `distribute()` for a `completed` distribution \u2014 Klappay's own operator address if settled by Klappay's own worker, a community keeper's address if settled externally (or `null` on the rare case that lookup failed), `null` for every non-`completed` status."
471
432
  );
472
433
  var DistributionsMetricFieldSchema = z9.enum(["attempts"]).describe(
473
434
  "How many times a payout was attempted for this settlement so far \u2014 incremented on every attempt, whether it succeeded or is being retried after failing. A high `attempts` alongside `status: 'failed'` means every automatic retry was exhausted."
474
435
  );
475
- var DistributionsDateFieldSchema = z9.enum(["createdAt", "completedAt"]).describe(
476
- "`createdAt`: when this settlement was queued. `completedAt`: when it actually paid out \u2014 `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed."
436
+ var DistributionsDateFieldSchema = z9.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
437
+ "`createdAt`: when this settlement was queued. `processingStartedAt`: when a worker began its most recent attempt at the payout \u2014 `null` until the first attempt, then overwritten on every subsequent retry, so it reflects the *latest* attempt's start, not the first. `completedAt`: when it actually paid out \u2014 `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed."
477
438
  );
478
439
  var DistributionsFilterSchema = z9.object({
479
440
  field: DistributionsQueryFieldSchema,
@@ -570,15 +531,11 @@ var MetricsQueryResultRowSchema = z9.record(
570
531
  z9.string(),
571
532
  z9.union([z9.string(), z9.number(), z9.boolean(), z9.null()])
572
533
  );
573
- var MetricsQueryScopeSchema = z9.enum(["owner_admin", "member"]).describe(
574
- "`member`: results were automatically restricted to data tied to API keys you personally created \u2014 rows with no resolvable creator were excluded, not counted, and not surfaced any other way. `owner_admin`: the full organization\u2019s data was queried, no restriction applied."
575
- );
576
534
  var MetricsQueryResultSchema = z9.object({
577
535
  data: z9.array(MetricsQueryResultRowSchema),
578
536
  meta: z9.object({
579
537
  resource: MetricsResourceSchema,
580
538
  environment: EnvironmentSchema,
581
- scope: MetricsQueryScopeSchema,
582
539
  rowCount: z9.number().int().describe("Number of rows in `data`."),
583
540
  truncated: z9.boolean().describe(
584
541
  "`true` if more rows matched than `limit` allowed \u2014 `data` holds only the first `limit`."
@@ -596,86 +553,43 @@ var ChargeWebhookEventTypeSchema = z10.enum([
596
553
  "charge.underpaid",
597
554
  "charge.settled",
598
555
  "charge.settlement_failed",
599
- "charge.overpaid",
600
- "charge.paused",
601
- "charge.reactivated",
602
- "charge.contribution_received",
603
- "charge.contribution_settled",
604
- "charge.canceled",
605
- "charge.paid_after_cancel"
606
- ]).describe(
607
- 'Note the distinction between `charge.confirmed` and `charge.settled`: `confirmed` means the payment was detected on-chain; `settled` means the merchant\'s wallet actually received the funds \u2014 a separate, later step. Subscribe to `confirmed` if you only need "will I get paid," or `settled` if you need "has the money actually arrived." `charge.overpaid` fires alongside `charge.confirmed`/`charge.partially_paid` whenever the cumulative amount received ends up above `amount` (see `Charge.isOverpaid`). Every event in this category carries the full `Charge` object as `data`, except `charge.paused`/`charge.reactivated`/`charge.contribution_received`/`charge.contribution_settled`/`charge.paid_after_cancel` (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) \u2014 Klappay 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 \u2014 pausing trades that away deliberately, see `docs/payments.md`). `charge.contribution_received`/`charge.contribution_settled` are exclusive to `mode: continuous` charges (see `Charge.mode`) \u2014 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. `charge.canceled` fires when a merchant explicitly cancels a `pending`/`partially_paid` charge via `POST /v1/charges/{id}/cancel` \u2014 unlike every other terminal status, this one is never reached automatically. `charge.paid_after_cancel` is an anomaly signal: a transfer still landed on a canceled charge\'s address (nothing on-chain can prevent that) \u2014 `status` stays `canceled`, it is never silently resumed, and this event is your cue to manually refund the payer or honor the charge anyway. `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 }`; for `charge.paid_after_cancel`: `{ chargeId, token, network, amount, txHash, payerAddress }`.'
608
- );
609
- var AccountWebhookEventTypeSchema = z10.enum([
610
- "payout_address.changed",
611
- "api_key.created",
612
- "api_key.revoked",
613
- "webhook.created",
614
- "webhook.deleted",
615
- "webhook.secret_rotated",
616
- "fee_tier.updated",
617
- "member.removed",
618
- "member.role_changed",
619
- "member.invited"
556
+ "charge.overpaid"
620
557
  ]).describe(
621
- "Account and configuration changes \u2014 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 }`."
558
+ 'Note the distinction between `charge.confirmed` and `charge.settled`: `confirmed` means the payment was detected on-chain; `settled` means the merchant\'s wallet actually received the funds \u2014 a separate, later step. Subscribe to `confirmed` if you only need "will I get paid," or `settled` if you need "has the money actually arrived." `charge.overpaid` fires alongside `charge.confirmed`/`charge.partially_paid` whenever the cumulative amount received ends up above `amount` (see `Charge.isOverpaid`). Every event in this category carries the full `Charge` object as `data`.'
622
559
  );
623
560
  var WebhookDeliveryEventTypeSchema = z10.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
624
561
  "Meta-events about the health of your own webhook endpoints \u2014 useful for monitoring without polling `GET /v1/webhooks/{id}/deliveries`. `webhook.endpoint_unhealthy` fires once when a webhook's failure rate over the trailing 24h crosses 20%, and `webhook.delivery_recovered` fires once when a delivery to that webhook next succeeds. `data` for every event in this category: `{ webhookId, url, failureRatio? }` (`failureRatio` only present on `webhook.endpoint_unhealthy`)."
625
562
  );
626
- var SecurityWebhookEventTypeSchema = z10.enum([
627
- "auth.login",
628
- "auth.login_failed",
629
- "auth.suspicious_activity",
630
- "auth.email_verified",
631
- "auth.password_reset_requested",
632
- "auth.password_reset_completed",
633
- "auth.password_changed",
634
- "auth.email_change_requested",
635
- "auth.email_changed"
636
- ]).describe(
637
- "Account security signals. `auth.suspicious_activity` is a soft heuristic (login from an IP not seen on this account before), not a block \u2014 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) \u2014 `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. `auth.password_changed` is the self-service counterpart to `auth.password_reset_completed` \u2014 fires from `POST /v1/auth/change-password` (requires the current password) instead of the unauthenticated forgot-password flow. `auth.email_change_requested`/`auth.email_changed` are the request/complete pair for `POST /v1/auth/change-email` \u2192 `POST /v1/auth/confirm-email-change` \u2014 the change only takes effect, and `email_changed` only fires, once the confirmation link sent to the *current* address is used. `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`/`auth.password_changed`: `{ userId, email }`; `auth.email_change_requested`: `{ userId, email, newEmail }`; `auth.email_changed`: `{ userId, previousEmail, newEmail }`."
638
- );
639
563
  var WebhookEventTypeSchema = z10.union([
640
564
  ChargeWebhookEventTypeSchema,
641
- AccountWebhookEventTypeSchema,
642
- WebhookDeliveryEventTypeSchema,
643
- SecurityWebhookEventTypeSchema
565
+ WebhookDeliveryEventTypeSchema
644
566
  ]);
645
- var WebhookCategorySchema = z10.enum(["payments", "account", "webhooks", "security"]).describe(
567
+ var WebhookCategorySchema = z10.enum(["payments", "webhooks"]).describe(
646
568
  "Subscribe to every event in a category via `eventCategories` instead of listing events one by one \u2014 new events added to a category later arrive automatically, no subscription update needed."
647
569
  );
648
570
  function buildCategoryMap() {
649
571
  const map = {};
650
572
  for (const event of ChargeWebhookEventTypeSchema.options) map[event] = "payments";
651
- for (const event of AccountWebhookEventTypeSchema.options) map[event] = "account";
652
573
  for (const event of WebhookDeliveryEventTypeSchema.options) map[event] = "webhooks";
653
- for (const event of SecurityWebhookEventTypeSchema.options) map[event] = "security";
574
+ for (const event of WebhookEventTypeSchema.options.flatMap((schema) => schema.options)) {
575
+ if (!(event in map)) {
576
+ throw new Error(
577
+ `buildCategoryMap: "${event}" has no category \u2014 a new event sub-schema was unioned into WebhookEventTypeSchema without a matching loop added here.`
578
+ );
579
+ }
580
+ }
654
581
  return map;
655
582
  }
656
583
  var EVENT_CATEGORY_MAP = buildCategoryMap();
657
584
  var WEBHOOK_EVENT_CATEGORIES = {
658
585
  payments: ChargeWebhookEventTypeSchema.options,
659
- account: AccountWebhookEventTypeSchema.options,
660
- webhooks: WebhookDeliveryEventTypeSchema.options,
661
- security: SecurityWebhookEventTypeSchema.options
586
+ webhooks: WebhookDeliveryEventTypeSchema.options
662
587
  };
663
588
  var TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([
664
- "charge.created",
665
- "charge.paused",
666
- "charge.reactivated",
667
- "charge.contribution_received",
668
- "charge.contribution_settled",
669
- "charge.canceled",
670
- "charge.paid_after_cancel"
589
+ "charge.created"
671
590
  ]).describe(
672
- "Every charge event that represents a payment-progress state transition a sandbox charge can be pushed into \u2014 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 \u2014 nothing meaningful to simulate or wait for on a fresh sandbox charge), `charge.contribution_received`/`charge.contribution_settled` (exclusive to `mode: continuous` charges, which this trigger endpoint does not support simulating today \u2014 see `POST /v1/charges/{id}/trigger`'s own description), and `charge.canceled` (already a real, immediate action in `test` mode via `POST /v1/charges/{id}/cancel` itself \u2014 nothing to simulate) along with `charge.paid_after_cancel` (not simulatable without a real transfer to an already-canceled charge)."
591
+ "Every charge event that represents a payment-progress state transition a sandbox charge can be pushed into \u2014 everything except `charge.created` (a charge already exists by the time you have an id to trigger against)."
673
592
  );
674
- var NonChargeTriggerableEventSchema = z10.union([
675
- AccountWebhookEventTypeSchema,
676
- WebhookDeliveryEventTypeSchema,
677
- SecurityWebhookEventTypeSchema
678
- ]);
679
593
 
680
594
  // src/webhooks.ts
681
595
  import { z as z11 } from "zod";
@@ -700,7 +614,7 @@ var CreateWebhookSchema = z11.object({
700
614
  var WebhookSchema = z11.object({
701
615
  id: z11.string(),
702
616
  environment: EnvironmentSchema.nullable().describe(
703
- "Which environment's API key created this webhook \u2014 `live` or `test`. Charge/webhook-delivery-health events are only ever delivered to a webhook whose `environment` matches the event's own (or to a webhook with `environment: null`, which receives every environment \u2014 the case for every webhook created before this field existed). Account/security events (`payout_address.changed`, `member.*`, `auth.*`, `fee_tier.updated`) have no environment concept and are delivered regardless."
617
+ "Which environment's API key created this webhook \u2014 `live` or `test`. Every event is only ever delivered to a webhook whose `environment` matches the event's own (or to a webhook with `environment: null`, which receives every environment \u2014 the case for every webhook created before this field existed)."
704
618
  ),
705
619
  url: z11.string(),
706
620
  events: z11.array(WebhookEventTypeSchema),
@@ -722,7 +636,7 @@ var WebhookPayloadSchema = z11.object({
722
636
  event: WebhookEventTypeSchema,
723
637
  createdAt: z11.string().datetime(),
724
638
  data: z11.unknown().describe(
725
- "Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; account/security/webhook-delivery events carry a smaller, event-specific object \u2014 see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md."
639
+ "Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; webhook-delivery events carry a smaller, event-specific object \u2014 see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md."
726
640
  )
727
641
  });
728
642
  var WebhookDeliveryStatusSchema = z11.enum(["pending", "delivered", "failed"]);
@@ -744,178 +658,27 @@ var WebhookDeliverySchema = z11.object({
744
658
  var ListWebhookDeliveriesSchema = PaginationQuerySchema;
745
659
  var PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema);
746
660
 
747
- // src/api-keys.ts
748
- import { z as z12 } from "zod";
749
- var CreateApiKeySchema = z12.object({
750
- name: z12.string().min(1).max(64).describe(
751
- 'A label to help you tell keys apart (e.g. `"production backend"`). Not used for anything functional.'
752
- ),
753
- environment: EnvironmentSchema.describe(
754
- "`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."
755
- )
756
- });
757
- var ApiKeySchema = z12.object({
758
- id: z12.string(),
759
- name: z12.string(),
760
- environment: EnvironmentSchema.describe(
761
- "`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."
762
- ),
763
- key: z12.string().optional().describe(
764
- "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` \u2014 never returned again afterward, so store it immediately."
765
- ),
766
- hint: z12.string().describe(
767
- "A truncated, always-safe-to-display form of the key (e.g. `klap_live_...ab12`), returned everywhere the full key isn't."
768
- ),
769
- createdAt: z12.string().datetime(),
770
- lastUsedAt: z12.string().datetime().nullable().describe("Updated on every successful authenticated request. `null` if never used."),
771
- createdByUserId: z12.string().nullable().describe(
772
- "Which member of the organization created this key. `null` for a key created before this field existed."
773
- )
774
- });
775
- var ListApiKeysSchema = PaginationQuerySchema;
776
- var PaginatedApiKeysSchema = paginatedSchema(ApiKeySchema);
777
-
778
- // src/users.ts
779
- import { z as z13 } from "zod";
780
- var UserRoleSchema = z13.enum(["owner", "admin", "member"]).describe(
781
- "`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`."
782
- );
783
- var UpdateUserRoleSchema = z13.object({
784
- role: UserRoleSchema
785
- });
786
- var UserSchema = z13.object({
787
- id: z13.string(),
788
- email: z13.string(),
789
- name: z13.string().nullable(),
790
- role: UserRoleSchema.describe("Your role within the organization this user was fetched from."),
791
- emailVerifiedAt: z13.string().datetime().nullable().describe(
792
- "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`) \u2014 everything else works regardless of verification status."
793
- ),
794
- createdAt: z13.string().datetime()
795
- });
796
- var ListUsersSchema = PaginationQuerySchema;
797
- var PaginatedUsersSchema = paginatedSchema(UserSchema);
798
-
799
- // src/auth.ts
800
- import { z as z14 } from "zod";
801
- var NormalizedEmailSchema = z14.string().trim().max(255).toLowerCase().email().transform((email) => email.normalize("NFC")).describe(
802
- "Trimmed, lowercased, and NFC-normalized server-side before use \u2014 case/whitespace don't matter."
803
- );
804
- var SignupSchema = z14.object({
805
- email: NormalizedEmailSchema,
806
- password: z14.string().min(8).max(128).describe("8-128 characters. No other complexity rule.")
807
- });
808
- var LoginSchema = z14.object({
809
- email: NormalizedEmailSchema,
810
- password: z14.string().min(1).max(128)
811
- });
812
- var VerifyEmailSchema = z14.object({
813
- token: z14.string().min(1).describe("The token from the verification email \u2014 passed as-is, not the account email.")
814
- });
815
- var ForgotPasswordSchema = z14.object({
816
- email: NormalizedEmailSchema
817
- });
818
- var ResetPasswordSchema = z14.object({
819
- token: z14.string().min(1).describe("The token from the password reset email."),
820
- newPassword: z14.string().min(8).max(128)
821
- });
822
- var MessageResponseSchema = z14.object({
823
- message: z14.string().describe("Human-readable confirmation, safe to show a user directly.")
824
- });
825
- var SelfUserSchema = UserSchema.omit({ createdAt: true, role: true });
826
- var AuthResponseSchema = z14.object({
827
- token: z14.string().describe(
828
- "Session JWT, valid 7 days \u2014 use as `Authorization: Bearer <token>` on every `/v1/organizations/*` request (which nests API keys, members, and invitations \u2014 see `GET /v1/organizations`). This token identifies only you; it carries no organization or role \u2014 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."
829
- ),
830
- user: SelfUserSchema
831
- });
832
- var ChangeNameSchema = z14.object({
833
- name: z14.string().min(1).max(255).describe("Your display name.")
834
- });
835
- var ChangePasswordSchema = z14.object({
836
- currentPassword: z14.string().min(1).max(128),
837
- newPassword: z14.string().min(8).max(128)
838
- });
839
- var ChangeEmailSchema = z14.object({
840
- currentPassword: z14.string().min(1).max(128),
841
- newEmail: NormalizedEmailSchema
842
- });
843
- var ConfirmEmailChangeSchema = z14.object({
844
- token: z14.string().min(1).describe("The token from the confirmation email sent to your current address.")
845
- });
846
-
847
- // src/organization.ts
848
- import { z as z15 } from "zod";
849
- var UpdateOrganizationSchema = z15.object({
850
- name: z15.string().min(1).max(255).optional().describe("The organization's display name."),
851
- payoutAddress: z15.string().regex(/^0x[a-fA-F0-9]{40}$/, "must be a valid EVM address").optional().describe(
852
- "The wallet that receives the merchant's share of every future charge. Changing this only affects charges created after the change \u2014 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 \u2014 EIP-55 checksum casing is not required or verified."
853
- )
854
- });
855
- var OrganizationSchema = z15.object({
856
- id: z15.string(),
857
- name: z15.string(),
858
- payoutAddress: z15.string().nullable().describe("`null` until configured \u2014 `POST /v1/charges` fails until this is set."),
859
- currentFeePercent: z15.number().describe(
860
- "Your current platform fee percentage \u2014 `1.5` means 1.5%, not a 0\u20131 fraction. Funds the infrastructure Klappay runs on your behalf (on-chain monitoring, settlement, webhook delivery, support) the same way any payment processor's fee does; this is not optional or removable. Dynamic, not fixed: it's based on your trailing monthly volume, with lower volume paying a higher percentage \u2014 higher-volume organizations, or ones with a specific negotiated arrangement, can be assigned a different rate at Klappay's discretion. Frozen onto each charge at creation, so a rate change never retroactively affects a charge already created; see `feeUpdatedAt` for when it last changed. Contact Klappay if you'd like your rate reviewed."
861
- ),
862
- feeUpdatedAt: z15.string().datetime().nullable().describe(
863
- "When `currentFeePercent` last changed. `null` if it has never changed since this organization signed up."
864
- ),
865
- createdAt: z15.string().datetime()
866
- });
867
- var OrganizationWithRoleSchema = OrganizationSchema.extend({
868
- role: UserRoleSchema.describe("Your own role within this specific organization.")
869
- });
870
- var PaginatedOrganizationsSchema = paginatedSchema(OrganizationWithRoleSchema);
871
- var ListOrganizationsSchema = PaginationQuerySchema;
872
-
873
- // src/invitations.ts
874
- import { z as z16 } from "zod";
875
- var InviteUserSchema = z16.object({
876
- email: NormalizedEmailSchema,
877
- role: UserRoleSchema.default("member").describe(
878
- "The role the invitee will hold once they accept \u2014 subject to the same management-hierarchy rule as `PATCH /v1/organizations/{id}/users/{userId}`: an `admin` inviter cannot invite an `admin` or `owner`."
879
- )
880
- });
881
- var AcceptInvitationSchema = z16.object({
882
- token: z16.string().min(1).describe("The token from the invitation email."),
883
- password: z16.string().min(8).max(128).optional().describe(
884
- "Required only if the invited email has no existing Klappay account \u2014 a new account is created along with the membership. Ignored if the account already exists."
885
- )
886
- });
887
- var InvitationSchema = z16.object({
888
- id: z16.string(),
889
- organizationId: z16.string(),
890
- email: z16.string(),
891
- role: UserRoleSchema,
892
- invitedByUserId: z16.string().describe("Which member of the organization sent this invitation."),
893
- expiresAt: z16.string().datetime(),
894
- createdAt: z16.string().datetime()
895
- });
896
-
897
661
  // src/timeline.ts
898
- import { z as z17 } from "zod";
899
- var TransactionSourceSchema = z17.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
662
+ import { z as z12 } from "zod";
663
+ var TransactionSourceSchema = z12.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
900
664
  "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)."
901
665
  );
902
- var TimelineEventTypeSchema = z17.enum([
666
+ var TimelineEventTypeSchema = z12.enum([
903
667
  "charge.created",
904
668
  "charge.expired",
905
- "charge.canceled",
906
669
  "transaction.detected",
907
670
  "split.distributed",
908
671
  "webhook.dispatched",
909
672
  "webhook.delivered",
910
673
  "webhook.failed"
911
674
  ]).describe(
912
- "`charge.created`: the charge was created. `charge.expired`: `expiresAt` passed with no full payment. `charge.canceled`: the merchant explicitly canceled it via `POST /v1/charges/{id}/cancel`. `transaction.detected`: a raw on-chain transfer was seen (see the `event`-shaped fields below for details \u2014 a charge can have more than one, e.g. a partial payment followed by the rest). `split.distributed`: a payout to the merchant completed on-chain, for one contributing `(token, network)` pair \u2014 a charge settled across more than one pair emits one of these per pair (see the `token`/`network` fields below). `webhook.dispatched`/`webhook.delivered`/`webhook.failed`: one specific delivery *attempt* for one webhook subscription \u2014 `failed` here means this single attempt failed, not that all retries were exhausted (see `WebhookDeliveryStatusSchema` for the exhausted-all-retries state)."
675
+ "`charge.created`: the charge was created. `charge.expired`: `expiresAt` passed with no full payment. `transaction.detected`: a raw on-chain transfer was seen (see the `event`-shaped fields below for details \u2014 a charge can have more than one, e.g. a partial payment followed by the rest). `split.distributed`: a payout to the merchant completed on-chain, for one contributing `(token, network)` pair \u2014 a charge settled across more than one pair emits one of these per pair (see the `token`/`network` fields below). `webhook.dispatched`/`webhook.delivered`/`webhook.failed`: one specific delivery *attempt* for one webhook subscription \u2014 `failed` here means this single attempt failed, not that all retries were exhausted (see `WebhookDeliveryStatusSchema` for the exhausted-all-retries state)."
913
676
  );
914
- var TimelineEventSchema = z17.object({
677
+ var TimelineEventSchema = z12.object({
915
678
  type: TimelineEventTypeSchema,
916
- at: z17.string().datetime(),
917
- txHash: z17.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
918
- amount: z17.number().optional().describe(
679
+ at: z12.string().datetime(),
680
+ txHash: z12.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
681
+ amount: z12.number().optional().describe(
919
682
  "Present for `transaction.detected` events only \u2014 the amount that specific transfer carried."
920
683
  ),
921
684
  source: TransactionSourceSchema.optional().describe(
@@ -927,80 +690,67 @@ var TimelineEventSchema = z17.object({
927
690
  network: NetworkSchema.optional().describe(
928
691
  "Present for `transaction.detected` and `split.distributed` events \u2014 which network this specific transfer, or settlement, used."
929
692
  ),
930
- causedTransition: z17.boolean().optional().describe(
693
+ causedTransition: z12.boolean().optional().describe(
931
694
  "Present for `transaction.detected` events only. `true` if this specific transfer changed the charge's status (e.g. PENDING\u2192CONFIRMED) \u2014 a charge paid in installments can have more than one such event."
932
695
  ),
933
696
  event: WebhookEventTypeSchema.optional().describe(
934
697
  "Present for `webhook.*` events only \u2014 which event type this delivery was for."
935
698
  ),
936
- responseCode: z17.number().nullable().optional().describe(
699
+ responseCode: z12.number().nullable().optional().describe(
937
700
  "Present for `webhook.*` events only \u2014 HTTP status your endpoint returned, or `null` if the request never connected."
938
701
  ),
939
- attempts: z17.number().optional().describe(
702
+ attempts: z12.number().optional().describe(
940
703
  "Present for `webhook.*` events only \u2014 how many delivery attempts have been made so far."
941
704
  )
942
705
  });
943
706
 
944
707
  // src/health.ts
945
- import { z as z18 } from "zod";
946
- var HealthSchema = z18.object({
947
- status: z18.enum(["ok", "error"]).describe(
708
+ import { z as z13 } from "zod";
709
+ var HealthSchema = z13.object({
710
+ status: z13.enum(["ok", "error"]).describe(
948
711
  "`error` when the database connectivity check fails \u2014 the HTTP status code mirrors this (503 instead of 200), so a plain uptime check (not just a JSON-aware one) still catches a DB outage."
949
712
  ),
950
- version: z18.string(),
951
- timestamp: z18.string().datetime(),
952
- db: z18.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
953
- pendingWebhooks: z18.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
954
- oldestPendingChargeAgeSeconds: z18.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
955
- lastMoralisEventAgeSeconds: z18.number().nullable().describe(
713
+ version: z13.string(),
714
+ timestamp: z13.string().datetime(),
715
+ db: z13.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
716
+ pendingWebhooks: z13.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
717
+ oldestPendingChargeAgeSeconds: z13.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
718
+ lastMoralisEventAgeSeconds: z13.number().nullable().describe(
956
719
  "Seconds since the last on-chain payment notification was received \u2014 a cheap signal for whether payment detection is currently working. `null` if none have ever been received."
957
720
  )
958
721
  });
959
722
 
960
723
  // src/sandbox.ts
961
- import { z as z19 } from "zod";
962
- var SandboxTriggerSchema = z19.object({
724
+ import { z as z14 } from "zod";
725
+ var SandboxTriggerSchema = z14.object({
963
726
  event: TriggerableChargeEventSchema,
964
- amount: z19.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
727
+ amount: z14.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
965
728
  "Used with `charge.partially_paid` (amount to simulate as received so far \u2014 must be less than the charge amount, defaults to half of it if omitted) and with `charge.overpaid` (amount received \u2014 must be greater than the charge amount, defaults to 1.5x it if omitted). Ignored for every other event."
966
729
  )
967
730
  });
968
- var SandboxEventTriggerSchema = z19.object({
969
- event: NonChargeTriggerableEventSchema.describe(
970
- "Any account, security, or webhook-delivery event \u2014 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)."
971
- )
972
- });
973
731
 
974
732
  // src/capabilities.ts
975
- import { z as z20 } from "zod";
976
- var CapabilitiesSchema = z20.object({
977
- acceptedPayments: z20.array(AcceptedPaymentSchema).describe(
733
+ import { z as z15 } from "zod";
734
+ var CapabilitiesSchema = z15.object({
735
+ acceptedPayments: z15.array(AcceptedPaymentSchema).describe(
978
736
  "Every `(token, network)` pair actually configured for your environment right now \u2014 read straight from the same lookup `POST /v1/charges` validates `acceptedPayments` against, so it can never list a pair that charge creation would then reject. Use this to build a picker UI instead of hardcoding the matrix client-side."
979
737
  )
980
738
  });
981
739
  export {
982
- AcceptInvitationSchema,
740
+ API_KEY_SCOPES,
983
741
  AcceptedPaymentSchema,
984
- AccountWebhookEventTypeSchema,
985
- ApiKeySchema,
986
- AuthResponseSchema,
742
+ ApiKeyScopeSchema,
987
743
  CHARGE_ACCEPTED_PAYMENTS_MAX,
988
744
  CHARGE_AMOUNT_MAX,
989
745
  CHARGE_EXPIRES_IN_MAX_SECONDS,
990
746
  CHARGE_EXPIRES_IN_MIN_SECONDS,
991
747
  CapabilitiesSchema,
992
- ChangeEmailSchema,
993
- ChangeNameSchema,
994
- ChangePasswordSchema,
995
- ChargeModeSchema,
996
748
  ChargeSchema,
997
749
  ChargeStatusSchema,
998
750
  ChargeWebhookEventTypeSchema,
999
751
  ChargesDateFieldSchema,
1000
752
  ChargesMetricFieldSchema,
1001
753
  ChargesQueryFieldSchema,
1002
- ConfirmEmailChangeSchema,
1003
- CreateApiKeySchema,
1004
754
  CreateChargeSchema,
1005
755
  CreateWebhookSchema,
1006
756
  DistributionsDateFieldSchema,
@@ -1010,64 +760,40 @@ export {
1010
760
  EVM_NETWORKS,
1011
761
  EnvironmentSchema,
1012
762
  ErrorPayloadSchema,
1013
- ForgotPasswordSchema,
1014
763
  GetChargeQrCodeQuerySchema,
1015
- GetPublicChargeQrCodeQuerySchema,
1016
- GetPublicChargeQuerySchema,
1017
764
  HealthSchema,
1018
- InvitationSchema,
1019
- InviteUserSchema,
1020
- ListApiKeysSchema,
1021
765
  ListChargesSchema,
1022
- ListOrganizationsSchema,
1023
- ListUsersSchema,
1024
766
  ListWebhookDeliveriesSchema,
1025
767
  ListenPendingDistributionsQuerySchema,
1026
- LoginSchema,
1027
768
  MAX_METRICS_QUERY_DATE_RANGE_DAYS,
1028
769
  METRICS_QUERY_DEFAULT_ROW_LIMIT,
1029
770
  METRICS_QUERY_MAX_FILTERS,
1030
771
  METRICS_QUERY_MAX_GROUP_BY,
1031
772
  METRICS_QUERY_MAX_METRICS,
1032
773
  METRICS_QUERY_MAX_ROW_LIMIT,
1033
- MessageResponseSchema,
1034
774
  MetricsAggregationSchema,
1035
775
  MetricsDateGranularitySchema,
1036
776
  MetricsFilterOperatorSchema,
1037
777
  MetricsQueryResultRowSchema,
1038
778
  MetricsQueryResultSchema,
1039
779
  MetricsQuerySchema,
1040
- MetricsQueryScopeSchema,
1041
780
  MetricsResourceSchema,
1042
781
  NETWORK_EXPLORERS,
1043
782
  NETWORK_LABELS,
1044
783
  NetworkSchema,
1045
- NonChargeTriggerableEventSchema,
1046
- NormalizedEmailSchema,
1047
784
  OPERATIONAL_NETWORKS,
1048
- OrganizationSchema,
1049
- OrganizationWithRoleSchema,
1050
785
  PAGINATION_LIMIT_DEFAULT,
1051
786
  PAGINATION_LIMIT_MAX,
1052
787
  PAGINATION_LIMIT_MIN,
1053
- PaginatedApiKeysSchema,
1054
788
  PaginatedChargesSchema,
1055
- PaginatedOrganizationsSchema,
1056
789
  PaginatedPendingDistributionsSchema,
1057
- PaginatedUsersSchema,
1058
790
  PaginatedWebhookDeliveriesSchema,
1059
791
  PaginationQuerySchema,
1060
792
  PendingDistributionEventSchema,
1061
793
  PendingDistributionRecipientSchema,
1062
794
  PendingDistributionSchema,
1063
- PublicChargeSchema,
1064
- ResetPasswordSchema,
1065
- SandboxEventTriggerSchema,
1066
795
  SandboxTriggerSchema,
1067
- SecurityWebhookEventTypeSchema,
1068
- SelfUserSchema,
1069
796
  SettlementStatusSchema,
1070
- SignupSchema,
1071
797
  SplitDistributionStatusSchema,
1072
798
  TOKEN_ADDRESSES,
1073
799
  TOKEN_DECIMALS,
@@ -1079,11 +805,6 @@ export {
1079
805
  TransactionsMetricFieldSchema,
1080
806
  TransactionsQueryFieldSchema,
1081
807
  TriggerableChargeEventSchema,
1082
- UpdateOrganizationSchema,
1083
- UpdateUserRoleSchema,
1084
- UserRoleSchema,
1085
- UserSchema,
1086
- VerifyEmailSchema,
1087
808
  WEBHOOK_EVENTS_WILDCARD,
1088
809
  WEBHOOK_EVENT_CATEGORIES,
1089
810
  WebhookCategorySchema,