@klappay/types 1.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.js ADDED
@@ -0,0 +1,905 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AcceptInvitationSchema: () => AcceptInvitationSchema,
24
+ AcceptedPaymentSchema: () => AcceptedPaymentSchema,
25
+ AccountWebhookEventTypeSchema: () => AccountWebhookEventTypeSchema,
26
+ ApiKeySchema: () => ApiKeySchema,
27
+ AuthResponseSchema: () => AuthResponseSchema,
28
+ CHARGE_ACCEPTED_PAYMENTS_MAX: () => CHARGE_ACCEPTED_PAYMENTS_MAX,
29
+ CHARGE_AMOUNT_MAX: () => CHARGE_AMOUNT_MAX,
30
+ CHARGE_EXPIRES_IN_MAX_SECONDS: () => CHARGE_EXPIRES_IN_MAX_SECONDS,
31
+ CHARGE_EXPIRES_IN_MIN_SECONDS: () => CHARGE_EXPIRES_IN_MIN_SECONDS,
32
+ CapabilitiesSchema: () => CapabilitiesSchema,
33
+ ChargeModeSchema: () => ChargeModeSchema,
34
+ ChargeSchema: () => ChargeSchema,
35
+ ChargeStatusEventSchema: () => ChargeStatusEventSchema,
36
+ ChargeStatusSchema: () => ChargeStatusSchema,
37
+ ChargeWebhookEventTypeSchema: () => ChargeWebhookEventTypeSchema,
38
+ CreateApiKeySchema: () => CreateApiKeySchema,
39
+ CreateChargeSchema: () => CreateChargeSchema,
40
+ CreateWebhookSchema: () => CreateWebhookSchema,
41
+ EVENT_CATEGORY_MAP: () => EVENT_CATEGORY_MAP,
42
+ EVM_NETWORKS: () => EVM_NETWORKS,
43
+ EnvironmentSchema: () => EnvironmentSchema,
44
+ ErrorPayloadSchema: () => ErrorPayloadSchema,
45
+ ForgotPasswordSchema: () => ForgotPasswordSchema,
46
+ HealthSchema: () => HealthSchema,
47
+ InvitationSchema: () => InvitationSchema,
48
+ InviteUserSchema: () => InviteUserSchema,
49
+ ListApiKeysSchema: () => ListApiKeysSchema,
50
+ ListChargesSchema: () => ListChargesSchema,
51
+ ListOrganizationsSchema: () => ListOrganizationsSchema,
52
+ ListUsersSchema: () => ListUsersSchema,
53
+ ListWebhookDeliveriesSchema: () => ListWebhookDeliveriesSchema,
54
+ LoginSchema: () => LoginSchema,
55
+ MessageResponseSchema: () => MessageResponseSchema,
56
+ NETWORK_EXPLORERS: () => NETWORK_EXPLORERS,
57
+ NETWORK_LABELS: () => NETWORK_LABELS,
58
+ NetworkSchema: () => NetworkSchema,
59
+ NonChargeTriggerableEventSchema: () => NonChargeTriggerableEventSchema,
60
+ NormalizedEmailSchema: () => NormalizedEmailSchema,
61
+ OPERATIONAL_NETWORKS: () => OPERATIONAL_NETWORKS,
62
+ OrganizationSchema: () => OrganizationSchema,
63
+ OrganizationWithRoleSchema: () => OrganizationWithRoleSchema,
64
+ PAGINATION_LIMIT_DEFAULT: () => PAGINATION_LIMIT_DEFAULT,
65
+ PAGINATION_LIMIT_MAX: () => PAGINATION_LIMIT_MAX,
66
+ PAGINATION_LIMIT_MIN: () => PAGINATION_LIMIT_MIN,
67
+ PaginatedApiKeysSchema: () => PaginatedApiKeysSchema,
68
+ PaginatedChargesSchema: () => PaginatedChargesSchema,
69
+ PaginatedOrganizationsSchema: () => PaginatedOrganizationsSchema,
70
+ PaginatedUsersSchema: () => PaginatedUsersSchema,
71
+ PaginatedWebhookDeliveriesSchema: () => PaginatedWebhookDeliveriesSchema,
72
+ PaginationQuerySchema: () => PaginationQuerySchema,
73
+ PendingDistributionEventSchema: () => PendingDistributionEventSchema,
74
+ PendingDistributionRecipientSchema: () => PendingDistributionRecipientSchema,
75
+ PendingDistributionSchema: () => PendingDistributionSchema,
76
+ ResetPasswordSchema: () => ResetPasswordSchema,
77
+ SandboxEventTriggerSchema: () => SandboxEventTriggerSchema,
78
+ SandboxTriggerSchema: () => SandboxTriggerSchema,
79
+ SecurityWebhookEventTypeSchema: () => SecurityWebhookEventTypeSchema,
80
+ SettlementStatusSchema: () => SettlementStatusSchema,
81
+ SignupSchema: () => SignupSchema,
82
+ SplitRecipientRoleSchema: () => SplitRecipientRoleSchema,
83
+ TOKEN_ADDRESSES: () => TOKEN_ADDRESSES,
84
+ TOKEN_DECIMALS: () => TOKEN_DECIMALS,
85
+ TimelineEventSchema: () => TimelineEventSchema,
86
+ TimelineEventTypeSchema: () => TimelineEventTypeSchema,
87
+ TokenSchema: () => TokenSchema,
88
+ TransactionSourceSchema: () => TransactionSourceSchema,
89
+ TriggerableChargeEventSchema: () => TriggerableChargeEventSchema,
90
+ UpdateOrganizationSchema: () => UpdateOrganizationSchema,
91
+ UpdateUserRoleSchema: () => UpdateUserRoleSchema,
92
+ UserRoleSchema: () => UserRoleSchema,
93
+ UserSchema: () => UserSchema,
94
+ VerifyChargeSchema: () => VerifyChargeSchema,
95
+ VerifyEmailSchema: () => VerifyEmailSchema,
96
+ VerifyPaymentSchema: () => VerifyPaymentSchema,
97
+ VerifySplitEntrySchema: () => VerifySplitEntrySchema,
98
+ WEBHOOK_EVENTS_WILDCARD: () => WEBHOOK_EVENTS_WILDCARD,
99
+ WEBHOOK_EVENT_CATEGORIES: () => WEBHOOK_EVENT_CATEGORIES,
100
+ WebhookCategorySchema: () => WebhookCategorySchema,
101
+ WebhookDeliveryEventTypeSchema: () => WebhookDeliveryEventTypeSchema,
102
+ WebhookDeliverySchema: () => WebhookDeliverySchema,
103
+ WebhookDeliveryStatusSchema: () => WebhookDeliveryStatusSchema,
104
+ WebhookEventTypeSchema: () => WebhookEventTypeSchema,
105
+ WebhookListItemSchema: () => WebhookListItemSchema,
106
+ WebhookPayloadSchema: () => WebhookPayloadSchema,
107
+ WebhookSchema: () => WebhookSchema,
108
+ paginatedSchema: () => paginatedSchema
109
+ });
110
+ module.exports = __toCommonJS(index_exports);
111
+
112
+ // src/errors.ts
113
+ var import_zod = require("zod");
114
+ var ErrorPayloadSchema = import_zod.z.object({
115
+ error: import_zod.z.object({
116
+ code: import_zod.z.string().describe(
117
+ "A stable, machine-readable error identifier (e.g. `validation_error`, `invalid_credentials`)."
118
+ ),
119
+ message: import_zod.z.string().describe(
120
+ "Human-readable explanation, safe to log or show a developer \u2014 not meant for end users."
121
+ ),
122
+ param: import_zod.z.string().optional().describe("Which request field the error refers to, when applicable.")
123
+ })
124
+ });
125
+
126
+ // src/environment.ts
127
+ var import_zod2 = require("zod");
128
+ var EnvironmentSchema = import_zod2.z.enum(["live", "test"]).describe(
129
+ "`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."
130
+ );
131
+
132
+ // src/networks.ts
133
+ var import_zod3 = require("zod");
134
+ var NetworkSchema = import_zod3.z.enum(["base", "optimism", "polygon", "ethereum", "arbitrum", "avalanche", "bnb"]).describe("The blockchain a charge/payment is on.");
135
+ var NETWORK_LABELS = {
136
+ base: "Base",
137
+ optimism: "Optimism",
138
+ polygon: "Polygon",
139
+ ethereum: "Ethereum",
140
+ arbitrum: "Arbitrum",
141
+ avalanche: "Avalanche",
142
+ bnb: "BNB Chain"
143
+ };
144
+ var NETWORK_EXPLORERS = {
145
+ base: "https://basescan.org",
146
+ optimism: "https://optimistic.etherscan.io",
147
+ polygon: "https://polygonscan.com",
148
+ ethereum: "https://etherscan.io",
149
+ arbitrum: "https://arbiscan.io",
150
+ avalanche: "https://snowtrace.io",
151
+ bnb: "https://bscscan.com"
152
+ };
153
+ var EVM_NETWORKS = [
154
+ "base",
155
+ "optimism",
156
+ "polygon",
157
+ "ethereum",
158
+ "arbitrum",
159
+ "avalanche",
160
+ "bnb"
161
+ ];
162
+ var OPERATIONAL_NETWORKS = [
163
+ "base",
164
+ "arbitrum",
165
+ "optimism",
166
+ "polygon",
167
+ "ethereum",
168
+ "avalanche",
169
+ "bnb"
170
+ ];
171
+
172
+ // src/pagination.ts
173
+ var import_zod4 = require("zod");
174
+ var PAGINATION_LIMIT_MIN = 1;
175
+ var PAGINATION_LIMIT_MAX = 100;
176
+ var PAGINATION_LIMIT_DEFAULT = 20;
177
+ var PaginationQuerySchema = import_zod4.z.object({
178
+ limit: import_zod4.z.coerce.number().min(PAGINATION_LIMIT_MIN).max(PAGINATION_LIMIT_MAX).default(PAGINATION_LIMIT_DEFAULT).describe(
179
+ `Max items to return per page (${PAGINATION_LIMIT_MIN}\u2013${PAGINATION_LIMIT_MAX}, default ${PAGINATION_LIMIT_DEFAULT}).`
180
+ ),
181
+ cursor: import_zod4.z.string().max(500).optional().describe(
182
+ "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."
183
+ )
184
+ });
185
+ function paginatedSchema(itemSchema) {
186
+ return import_zod4.z.object({
187
+ data: import_zod4.z.array(itemSchema),
188
+ nextCursor: import_zod4.z.string().nullable().describe("Pass as `cursor` to fetch the next page. `null` when there are no more results."),
189
+ hasMore: import_zod4.z.boolean()
190
+ });
191
+ }
192
+
193
+ // src/tokens.ts
194
+ var import_zod5 = require("zod");
195
+ var TokenSchema = import_zod5.z.enum(["USDC", "USDT"]).describe(
196
+ `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 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 \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.`
197
+ );
198
+ var TOKEN_DECIMALS = 6;
199
+ var TOKEN_ADDRESSES = {
200
+ USDC: {
201
+ base: {
202
+ live: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
203
+ test: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
204
+ },
205
+ optimism: {
206
+ live: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
207
+ test: "0x5fd84259d66Cd46123540766Be93DFE6D43130D7"
208
+ },
209
+ polygon: { live: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359" },
210
+ ethereum: {
211
+ live: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
212
+ test: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
213
+ },
214
+ arbitrum: { live: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831" },
215
+ avalanche: { live: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" },
216
+ bnb: { live: "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d" }
217
+ },
218
+ USDT: {
219
+ base: { live: "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2" },
220
+ optimism: { live: "0x94b008aA00579c1307B0EF2c499aD98a8ce58e58" },
221
+ polygon: { live: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F" },
222
+ ethereum: { live: "0xdAC17F958D2ee523a2206206994597C13D831ec7" },
223
+ arbitrum: { live: "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9" },
224
+ avalanche: { live: "0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7" },
225
+ bnb: { live: "0x55d398326f99059fF775485246999027B3197955" }
226
+ }
227
+ };
228
+
229
+ // src/charges.ts
230
+ var import_zod6 = require("zod");
231
+ var ChargeStatusSchema = import_zod6.z.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
232
+ "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`. This never reflects whether funds actually reached the merchant \u2014 see `settlementStatus` for that."
233
+ );
234
+ var SettlementStatusSchema = import_zod6.z.enum(["pending", "completed", "failed"]).describe(
235
+ "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."
236
+ );
237
+ var ChargeModeSchema = import_zod6.z.enum(["standard", "continuous"]).describe(
238
+ "`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."
239
+ );
240
+ var CHARGE_EXPIRES_IN_MIN_SECONDS = 60;
241
+ var CHARGE_EXPIRES_IN_MAX_SECONDS = 365 * 24 * 60 * 60;
242
+ var CHARGE_ACCEPTED_PAYMENTS_MAX = 14;
243
+ var AcceptedPaymentSchema = import_zod6.z.object({
244
+ token: TokenSchema,
245
+ network: NetworkSchema
246
+ });
247
+ var AcceptedPaymentsSchema = import_zod6.z.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
248
+ const seen = /* @__PURE__ */ new Set();
249
+ pairs.forEach((pair, index) => {
250
+ const key = `${pair.token}:${pair.network}`;
251
+ if (seen.has(key)) {
252
+ ctx.addIssue({
253
+ code: import_zod6.z.ZodIssueCode.custom,
254
+ message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,
255
+ path: [index]
256
+ });
257
+ }
258
+ seen.add(key);
259
+ if (!OPERATIONAL_NETWORKS.includes(pair.network)) {
260
+ ctx.addIssue({
261
+ code: import_zod6.z.ZodIssueCode.custom,
262
+ message: `Network "${pair.network}" isn't live yet \u2014 only ${OPERATIONAL_NETWORKS.join(", ")} today.`,
263
+ path: [index, "network"]
264
+ });
265
+ }
266
+ });
267
+ }).describe(
268
+ `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\`.`
269
+ );
270
+ var CHARGE_AMOUNT_MAX = 999999999999;
271
+ var CreateChargeSchema = import_zod6.z.object({
272
+ mode: ChargeModeSchema.default("standard"),
273
+ amount: import_zod6.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
274
+ "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)."
275
+ ),
276
+ currency: import_zod6.z.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
277
+ acceptedPayments: AcceptedPaymentsSchema,
278
+ expiresIn: import_zod6.z.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).optional().describe(
279
+ "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."
280
+ ),
281
+ idempotencyKey: import_zod6.z.string().min(1).max(255).optional().describe(
282
+ "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."
283
+ ),
284
+ externalRef: import_zod6.z.string().min(1).max(255).optional().describe(
285
+ "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 Klap."
286
+ ),
287
+ source: import_zod6.z.string().min(1).max(64).optional().describe(
288
+ '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.'
289
+ ),
290
+ metadata: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.unknown()).optional().describe("Arbitrary key/value data to attach to the charge, returned as-is on every read.")
291
+ }).superRefine((input, ctx) => {
292
+ if (input.mode === "continuous" && (input.amount !== void 0 || input.expiresIn !== void 0)) {
293
+ ctx.addIssue({
294
+ code: import_zod6.z.ZodIssueCode.custom,
295
+ message: 'mode: "continuous" requires both amount and expiresIn to be omitted.',
296
+ path: ["mode"]
297
+ });
298
+ }
299
+ });
300
+ var ChargeSchema = import_zod6.z.object({
301
+ id: import_zod6.z.string().describe("Klap-generated id, e.g. `ch_...`. Use this to look up the charge later."),
302
+ mode: ChargeModeSchema,
303
+ amount: import_zod6.z.number().nullable().describe(
304
+ "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."
305
+ ),
306
+ amountReceived: import_zod6.z.number().nullable().describe(
307
+ "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."
308
+ ),
309
+ isOverpaid: import_zod6.z.boolean().describe(
310
+ "`true` if `amountReceived` ended up greater than `amount`. Klap never refunds the difference automatically \u2014 see the docs for why."
311
+ ),
312
+ currency: import_zod6.z.string().describe("Always `USD` today \u2014 the only supported currency."),
313
+ acceptedPayments: import_zod6.z.array(AcceptedPaymentSchema).describe(
314
+ "Every `(token, network)` pair this charge was configured to accept, unchanged after creation."
315
+ ),
316
+ paidWith: import_zod6.z.array(AcceptedPaymentSchema).describe(
317
+ "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`."
318
+ ),
319
+ address: import_zod6.z.string().describe(
320
+ "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, Klap never custodies them."
321
+ ),
322
+ status: ChargeStatusSchema,
323
+ settlementStatus: SettlementStatusSchema.nullable(),
324
+ environment: EnvironmentSchema,
325
+ apiKeyId: import_zod6.z.string().nullable().describe(
326
+ "Which of your API keys created this charge. `null` for a charge created before this field existed."
327
+ ),
328
+ txHash: import_zod6.z.string().nullable().describe(
329
+ "Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected."
330
+ ),
331
+ externalRef: import_zod6.z.string().nullable(),
332
+ source: import_zod6.z.string().nullable(),
333
+ metadata: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.unknown()).nullable(),
334
+ createdAt: import_zod6.z.string().datetime(),
335
+ expiresAt: import_zod6.z.string().datetime().nullable().describe(
336
+ "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)."
337
+ ),
338
+ confirmedAt: import_zod6.z.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
339
+ settledAt: import_zod6.z.string().datetime().nullable().describe(
340
+ "When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
341
+ ),
342
+ lastActivityAt: import_zod6.z.string().datetime().describe(
343
+ "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`."
344
+ ),
345
+ pausedAt: import_zod6.z.string().datetime().nullable().describe(
346
+ "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 \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."
347
+ )
348
+ });
349
+ var ListChargesSchema = import_zod6.z.object({
350
+ status: ChargeStatusSchema.optional(),
351
+ token: TokenSchema.optional().describe(
352
+ "Filters on `paidWith.token` \u2014 the pair actually paid, not accepted."
353
+ ),
354
+ network: NetworkSchema.optional().describe(
355
+ "Filters on `paidWith.network` \u2014 the pair actually paid, not accepted."
356
+ ),
357
+ environment: EnvironmentSchema.optional(),
358
+ since: import_zod6.z.string().datetime().optional().describe(
359
+ "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."
360
+ ),
361
+ isOverpaid: import_zod6.z.enum(["true", "false"]).transform((v) => v === "true").optional()
362
+ }).extend(PaginationQuerySchema.shape);
363
+ var PaginatedChargesSchema = paginatedSchema(ChargeSchema);
364
+ var ChargeStatusEventSchema = import_zod6.z.object({
365
+ id: import_zod6.z.string(),
366
+ status: ChargeStatusSchema,
367
+ settlementStatus: SettlementStatusSchema.nullable(),
368
+ amount: import_zod6.z.number().nullable(),
369
+ amountReceived: import_zod6.z.number().nullable(),
370
+ paidWith: import_zod6.z.array(AcceptedPaymentSchema)
371
+ });
372
+
373
+ // src/distributions.ts
374
+ var import_zod7 = require("zod");
375
+ var PendingDistributionRecipientSchema = import_zod7.z.object({
376
+ address: import_zod7.z.string().describe("On-chain recipient address."),
377
+ percentAllocation: import_zod7.z.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
378
+ });
379
+ var PendingDistributionSchema = import_zod7.z.object({
380
+ splitAddress: import_zod7.z.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
381
+ network: NetworkSchema,
382
+ token: TokenSchema,
383
+ recipients: import_zod7.z.array(PendingDistributionRecipientSchema).describe(
384
+ "The exact recipient list to pass to `distribute()` \u2014 the split contract only stores a hash of this config, so the caller must supply the identical array to prove it matches. Always present, never reconstructed from partial data."
385
+ ),
386
+ distributorFeePercent: import_zod7.z.number().describe(
387
+ "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."
388
+ ),
389
+ estimatedRewardAmount: import_zod7.z.number().describe(
390
+ "Estimate only, in the charge's `currency` units, based on the amount Klap detected on-chain \u2014 not a live read of the split's current balance. Read the balance yourself before submitting a transaction; a stale estimate is harmless (see the docs), never a reason to skip that check."
391
+ ),
392
+ availableSince: import_zod7.z.string().datetime().describe("When this distribution entered its grace period."),
393
+ graceEndsAt: import_zod7.z.string().datetime().describe(
394
+ "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."
395
+ )
396
+ });
397
+ var PendingDistributionEventSchema = import_zod7.z.discriminatedUnion("type", [
398
+ import_zod7.z.object({
399
+ type: import_zod7.z.literal("distribution.available"),
400
+ distribution: PendingDistributionSchema
401
+ }),
402
+ import_zod7.z.object({
403
+ type: import_zod7.z.literal("distribution.claimed"),
404
+ splitAddress: import_zod7.z.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
405
+ })
406
+ ]);
407
+
408
+ // src/webhook-events.ts
409
+ var import_zod8 = require("zod");
410
+ var ChargeWebhookEventTypeSchema = import_zod8.z.enum([
411
+ "charge.created",
412
+ "charge.partially_paid",
413
+ "charge.confirmed",
414
+ "charge.expired",
415
+ "charge.underpaid",
416
+ "charge.settled",
417
+ "charge.settlement_failed",
418
+ "charge.overpaid",
419
+ "charge.paused",
420
+ "charge.reactivated",
421
+ "charge.contribution_received",
422
+ "charge.contribution_settled"
423
+ ]).describe(
424
+ '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` (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 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 \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. `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 }`.'
425
+ );
426
+ var AccountWebhookEventTypeSchema = import_zod8.z.enum([
427
+ "payout_address.changed",
428
+ "api_key.created",
429
+ "api_key.revoked",
430
+ "webhook.created",
431
+ "webhook.deleted",
432
+ "webhook.secret_rotated",
433
+ "fee_tier.updated",
434
+ "member.removed",
435
+ "member.role_changed",
436
+ "member.invited"
437
+ ]).describe(
438
+ "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 }`."
439
+ );
440
+ var WebhookDeliveryEventTypeSchema = import_zod8.z.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
441
+ "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`)."
442
+ );
443
+ var SecurityWebhookEventTypeSchema = import_zod8.z.enum([
444
+ "auth.login",
445
+ "auth.login_failed",
446
+ "auth.suspicious_activity",
447
+ "auth.email_verified",
448
+ "auth.password_reset_requested",
449
+ "auth.password_reset_completed"
450
+ ]).describe(
451
+ "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. `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 }`."
452
+ );
453
+ var WebhookEventTypeSchema = import_zod8.z.union([
454
+ ChargeWebhookEventTypeSchema,
455
+ AccountWebhookEventTypeSchema,
456
+ WebhookDeliveryEventTypeSchema,
457
+ SecurityWebhookEventTypeSchema
458
+ ]);
459
+ var WebhookCategorySchema = import_zod8.z.enum(["payments", "account", "webhooks", "security"]).describe(
460
+ "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."
461
+ );
462
+ function buildCategoryMap() {
463
+ const map = {};
464
+ for (const event of ChargeWebhookEventTypeSchema.options) map[event] = "payments";
465
+ for (const event of AccountWebhookEventTypeSchema.options) map[event] = "account";
466
+ for (const event of WebhookDeliveryEventTypeSchema.options) map[event] = "webhooks";
467
+ for (const event of SecurityWebhookEventTypeSchema.options) map[event] = "security";
468
+ return map;
469
+ }
470
+ var EVENT_CATEGORY_MAP = buildCategoryMap();
471
+ var WEBHOOK_EVENT_CATEGORIES = {
472
+ payments: ChargeWebhookEventTypeSchema.options,
473
+ account: AccountWebhookEventTypeSchema.options,
474
+ webhooks: WebhookDeliveryEventTypeSchema.options,
475
+ security: SecurityWebhookEventTypeSchema.options
476
+ };
477
+ var TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([
478
+ "charge.created",
479
+ "charge.paused",
480
+ "charge.reactivated",
481
+ "charge.contribution_received",
482
+ "charge.contribution_settled"
483
+ ]).describe(
484
+ "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), and `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)."
485
+ );
486
+ var NonChargeTriggerableEventSchema = import_zod8.z.union([
487
+ AccountWebhookEventTypeSchema,
488
+ WebhookDeliveryEventTypeSchema,
489
+ SecurityWebhookEventTypeSchema
490
+ ]);
491
+
492
+ // src/webhooks.ts
493
+ var import_zod9 = require("zod");
494
+ var WEBHOOK_EVENTS_WILDCARD = "*";
495
+ var CreateWebhookSchema = import_zod9.z.object({
496
+ url: import_zod9.z.string().max(2048).url().describe(
497
+ "Must be HTTPS and resolve to a public address \u2014 private/internal IPs are rejected."
498
+ ),
499
+ events: import_zod9.z.array(import_zod9.z.union([WebhookEventTypeSchema, import_zod9.z.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
500
+ '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.'
501
+ ),
502
+ eventCategories: import_zod9.z.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
503
+ "Subscribe to every event in these categories. At least one of `events` or `eventCategories` is required."
504
+ ),
505
+ excludeEvents: import_zod9.z.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
506
+ 'Event types to exclude even if selected via `events: ["*"]` or `eventCategories`.'
507
+ )
508
+ }).refine((v) => v.events.length > 0 || v.eventCategories.length > 0, {
509
+ message: "must select at least one event via `events` or `eventCategories`",
510
+ path: ["events"]
511
+ });
512
+ var WebhookSchema = import_zod9.z.object({
513
+ id: import_zod9.z.string(),
514
+ url: import_zod9.z.string(),
515
+ events: import_zod9.z.array(WebhookEventTypeSchema),
516
+ eventCategories: import_zod9.z.array(WebhookCategorySchema),
517
+ excludeEvents: import_zod9.z.array(WebhookEventTypeSchema),
518
+ isWildcard: import_zod9.z.boolean(),
519
+ secret: import_zod9.z.string().describe(
520
+ "The signing secret, used to verify the `X-Klap-Signature` header on every delivery. Returned in full only this once \u2014 store it now, it is not recoverable afterward. Header format: `t=<unix-seconds>,v1=<hex-encoded HMAC-SHA256>`. Compute the expected signature as `HMAC-SHA256(secret, \"${t}.${raw request body}\")` (hex-encoded) and compare it to `v1` using a constant-time comparison; as a replay-protection measure, also reject if `t` is too far from the current time \u2014 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."
521
+ ),
522
+ createdAt: import_zod9.z.string().datetime()
523
+ });
524
+ var WebhookListItemSchema = WebhookSchema.omit({ secret: true }).extend({
525
+ hint: import_zod9.z.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
526
+ });
527
+ var WebhookPayloadSchema = import_zod9.z.object({
528
+ id: import_zod9.z.string().describe("Unique id for this specific delivery \u2014 also sent as the `X-Klap-Delivery` header."),
529
+ event: WebhookEventTypeSchema,
530
+ createdAt: import_zod9.z.string().datetime(),
531
+ data: import_zod9.z.unknown().describe(
532
+ "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."
533
+ )
534
+ });
535
+ var WebhookDeliveryStatusSchema = import_zod9.z.enum(["pending", "delivered", "failed"]);
536
+ var WebhookDeliverySchema = import_zod9.z.object({
537
+ id: import_zod9.z.string(),
538
+ webhookId: import_zod9.z.string(),
539
+ event: WebhookEventTypeSchema,
540
+ status: WebhookDeliveryStatusSchema.describe(
541
+ "`pending`: still retrying. `delivered`: got a 2xx response. `failed`: retries exhausted (5 attempts over ~24h) \u2014 use `POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry` to try again manually."
542
+ ),
543
+ attempts: import_zod9.z.number(),
544
+ responseCode: import_zod9.z.number().nullable().describe(
545
+ "HTTP status your endpoint returned on the most recent attempt. `null` if every attempt failed to connect at all."
546
+ ),
547
+ nextRetryAt: import_zod9.z.string().datetime().nullable(),
548
+ deliveredAt: import_zod9.z.string().datetime().nullable(),
549
+ createdAt: import_zod9.z.string().datetime()
550
+ });
551
+ var ListWebhookDeliveriesSchema = PaginationQuerySchema;
552
+ var PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema);
553
+
554
+ // src/api-keys.ts
555
+ var import_zod10 = require("zod");
556
+ var CreateApiKeySchema = import_zod10.z.object({
557
+ name: import_zod10.z.string().min(1).max(64).describe(
558
+ 'A label to help you tell keys apart (e.g. `"production backend"`). Not used for anything functional.'
559
+ ),
560
+ environment: EnvironmentSchema.describe(
561
+ "`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."
562
+ )
563
+ });
564
+ var ApiKeySchema = import_zod10.z.object({
565
+ id: import_zod10.z.string(),
566
+ name: import_zod10.z.string(),
567
+ environment: EnvironmentSchema.describe(
568
+ "`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."
569
+ ),
570
+ key: import_zod10.z.string().optional().describe(
571
+ "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."
572
+ ),
573
+ hint: import_zod10.z.string().describe(
574
+ "A truncated, always-safe-to-display form of the key (e.g. `klap_live_...ab12`), returned everywhere the full key isn't."
575
+ ),
576
+ createdAt: import_zod10.z.string().datetime(),
577
+ lastUsedAt: import_zod10.z.string().datetime().nullable().describe("Updated on every successful authenticated request. `null` if never used."),
578
+ createdByUserId: import_zod10.z.string().nullable().describe(
579
+ "Which member of the organization created this key. `null` for a key created before this field existed."
580
+ )
581
+ });
582
+ var ListApiKeysSchema = PaginationQuerySchema;
583
+ var PaginatedApiKeysSchema = paginatedSchema(ApiKeySchema);
584
+
585
+ // src/users.ts
586
+ var import_zod11 = require("zod");
587
+ var UserRoleSchema = import_zod11.z.enum(["owner", "admin", "member"]).describe(
588
+ "`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`."
589
+ );
590
+ var UpdateUserRoleSchema = import_zod11.z.object({
591
+ role: UserRoleSchema
592
+ });
593
+ var UserSchema = import_zod11.z.object({
594
+ id: import_zod11.z.string(),
595
+ email: import_zod11.z.string(),
596
+ name: import_zod11.z.string().nullable(),
597
+ role: UserRoleSchema.describe("Your role within the organization this user was fetched from."),
598
+ emailVerifiedAt: import_zod11.z.string().datetime().nullable().describe(
599
+ "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."
600
+ ),
601
+ createdAt: import_zod11.z.string().datetime()
602
+ });
603
+ var ListUsersSchema = PaginationQuerySchema;
604
+ var PaginatedUsersSchema = paginatedSchema(UserSchema);
605
+
606
+ // src/auth.ts
607
+ var import_zod12 = require("zod");
608
+ var NormalizedEmailSchema = import_zod12.z.string().trim().max(255).toLowerCase().email().transform((email) => email.normalize("NFC")).describe(
609
+ "Trimmed, lowercased, and NFC-normalized server-side before use \u2014 case/whitespace don't matter."
610
+ );
611
+ var SignupSchema = import_zod12.z.object({
612
+ email: NormalizedEmailSchema,
613
+ password: import_zod12.z.string().min(8).max(128).describe("8-128 characters. No other complexity rule.")
614
+ });
615
+ var LoginSchema = import_zod12.z.object({
616
+ email: NormalizedEmailSchema,
617
+ password: import_zod12.z.string().min(1).max(128)
618
+ });
619
+ var VerifyEmailSchema = import_zod12.z.object({
620
+ token: import_zod12.z.string().min(1).describe("The token from the verification email \u2014 passed as-is, not the account email.")
621
+ });
622
+ var ForgotPasswordSchema = import_zod12.z.object({
623
+ email: NormalizedEmailSchema
624
+ });
625
+ var ResetPasswordSchema = import_zod12.z.object({
626
+ token: import_zod12.z.string().min(1).describe("The token from the password reset email."),
627
+ newPassword: import_zod12.z.string().min(8).max(128)
628
+ });
629
+ var MessageResponseSchema = import_zod12.z.object({
630
+ message: import_zod12.z.string().describe("Human-readable confirmation, safe to show a user directly.")
631
+ });
632
+ var AuthResponseSchema = import_zod12.z.object({
633
+ token: import_zod12.z.string().describe(
634
+ "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."
635
+ ),
636
+ user: UserSchema.omit({ createdAt: true, role: true })
637
+ });
638
+
639
+ // src/organization.ts
640
+ var import_zod13 = require("zod");
641
+ var UpdateOrganizationSchema = import_zod13.z.object({
642
+ name: import_zod13.z.string().min(1).max(255).optional().describe("The organization's display name."),
643
+ payoutAddress: import_zod13.z.string().regex(/^0x[a-fA-F0-9]{40}$/, "must be a valid EVM address").optional().describe(
644
+ "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."
645
+ )
646
+ });
647
+ var OrganizationSchema = import_zod13.z.object({
648
+ id: import_zod13.z.string(),
649
+ name: import_zod13.z.string(),
650
+ payoutAddress: import_zod13.z.string().nullable().describe("`null` until configured \u2014 `POST /v1/charges` fails until this is set."),
651
+ currentFeePercent: import_zod13.z.number().describe(
652
+ "Your current platform fee percentage, based on trailing monthly volume \u2014 lower volume tiers pay a higher percentage. `1.5` means 1.5%, not a 0\u20131 fraction. Frozen onto each charge at creation, so this can change between charges without affecting ones already created."
653
+ ),
654
+ feeUpdatedAt: import_zod13.z.string().datetime().nullable(),
655
+ createdAt: import_zod13.z.string().datetime()
656
+ });
657
+ var OrganizationWithRoleSchema = OrganizationSchema.extend({
658
+ role: UserRoleSchema.describe("Your own role within this specific organization.")
659
+ });
660
+ var PaginatedOrganizationsSchema = paginatedSchema(OrganizationWithRoleSchema);
661
+ var ListOrganizationsSchema = PaginationQuerySchema;
662
+
663
+ // src/invitations.ts
664
+ var import_zod14 = require("zod");
665
+ var InviteUserSchema = import_zod14.z.object({
666
+ email: NormalizedEmailSchema,
667
+ role: UserRoleSchema.default("member").describe(
668
+ "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`."
669
+ )
670
+ });
671
+ var AcceptInvitationSchema = import_zod14.z.object({
672
+ token: import_zod14.z.string().min(1).describe("The token from the invitation email."),
673
+ password: import_zod14.z.string().min(8).max(128).optional().describe(
674
+ "Required only if the invited email has no existing Klap account \u2014 a new account is created along with the membership. Ignored if the account already exists."
675
+ )
676
+ });
677
+ var InvitationSchema = import_zod14.z.object({
678
+ id: import_zod14.z.string(),
679
+ organizationId: import_zod14.z.string(),
680
+ email: import_zod14.z.string(),
681
+ role: UserRoleSchema,
682
+ invitedByUserId: import_zod14.z.string().describe("Which member of the organization sent this invitation."),
683
+ expiresAt: import_zod14.z.string().datetime(),
684
+ createdAt: import_zod14.z.string().datetime()
685
+ });
686
+
687
+ // src/timeline.ts
688
+ var import_zod15 = require("zod");
689
+ var TransactionSourceSchema = import_zod15.z.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
690
+ "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)."
691
+ );
692
+ var TimelineEventTypeSchema = import_zod15.z.enum([
693
+ "charge.created",
694
+ "charge.expired",
695
+ "transaction.detected",
696
+ "split.distributed",
697
+ "webhook.dispatched",
698
+ "webhook.delivered",
699
+ "webhook.failed"
700
+ ]).describe(
701
+ "`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)."
702
+ );
703
+ var TimelineEventSchema = import_zod15.z.object({
704
+ type: TimelineEventTypeSchema,
705
+ at: import_zod15.z.string().datetime(),
706
+ txHash: import_zod15.z.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
707
+ amount: import_zod15.z.number().optional().describe(
708
+ "Present for `transaction.detected` events only \u2014 the amount that specific transfer carried."
709
+ ),
710
+ source: TransactionSourceSchema.optional().describe(
711
+ "Present for `transaction.detected` events only."
712
+ ),
713
+ token: TokenSchema.optional().describe(
714
+ "Present for `transaction.detected` and `split.distributed` events \u2014 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."
715
+ ),
716
+ network: NetworkSchema.optional().describe(
717
+ "Present for `transaction.detected` and `split.distributed` events \u2014 which network this specific transfer, or settlement, used."
718
+ ),
719
+ causedTransition: import_zod15.z.boolean().optional().describe(
720
+ "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."
721
+ ),
722
+ event: WebhookEventTypeSchema.optional().describe(
723
+ "Present for `webhook.*` events only \u2014 which event type this delivery was for."
724
+ ),
725
+ responseCode: import_zod15.z.number().nullable().optional().describe(
726
+ "Present for `webhook.*` events only \u2014 HTTP status your endpoint returned, or `null` if the request never connected."
727
+ ),
728
+ attempts: import_zod15.z.number().optional().describe(
729
+ "Present for `webhook.*` events only \u2014 how many delivery attempts have been made so far."
730
+ )
731
+ });
732
+
733
+ // src/verify.ts
734
+ var import_zod16 = require("zod");
735
+ var SplitRecipientRoleSchema = import_zod16.z.enum(["merchant", "klap_fee", "distributor_incentive"]).describe(
736
+ "`merchant`: the payout recipient. `klap_fee`: the platform fee. `distributor_incentive`: the (usually small) reward paid to whoever triggered the on-chain settlement \u2014 may be Klap or a third party, see `address`."
737
+ );
738
+ var VerifySplitEntrySchema = import_zod16.z.object({
739
+ role: SplitRecipientRoleSchema,
740
+ address: import_zod16.z.string().nullable().describe(
741
+ "On-chain recipient address for this share. For `distributor_incentive`, this is `null` until settlement actually happens \u2014 there is no fixed address, it goes to whoever calls the settlement transaction."
742
+ ),
743
+ percentAllocation: import_zod16.z.number().describe("This entry's share of `amountReceived`, as a percentage (e.g. `99` = 99%)."),
744
+ amountUSD: import_zod16.z.number()
745
+ });
746
+ var VerifyPaymentSchema = import_zod16.z.object({
747
+ token: TokenSchema,
748
+ network: NetworkSchema,
749
+ amountReceived: import_zod16.z.number().describe("Cumulative amount received on this specific `(token, network)` pair."),
750
+ txHash: import_zod16.z.string().describe("The on-chain transaction hash of the most recent transfer on this pair."),
751
+ explorerTxUrl: import_zod16.z.string().describe("Direct link to `txHash` on the relevant block explorer."),
752
+ split: import_zod16.z.array(VerifySplitEntrySchema).describe(
753
+ "The exact breakdown of where this pair's payment went \u2014 merchant's share, Klap's fee, and (once settled) the settlement incentive."
754
+ ),
755
+ splitTxHash: import_zod16.z.string().nullable().describe(
756
+ "Transaction hash of the payout to the merchant for this pair, once settlement has happened. `null` until then."
757
+ ),
758
+ settledAt: import_zod16.z.string().datetime().nullable().describe(
759
+ "When settlement completed for this pair \u2014 the merchant's wallet actually has the funds. `null` until then."
760
+ )
761
+ });
762
+ var VerifyChargeSchema = import_zod16.z.object({
763
+ id: import_zod16.z.string(),
764
+ amount: import_zod16.z.number().nullable().describe("The amount originally requested. `null` if the charge accepted any amount."),
765
+ amountReceived: import_zod16.z.number().describe(
766
+ "The actual cumulative amount received across every contributing pair \u2014 can exceed `amount` on an overpayment."
767
+ ),
768
+ confirmedAt: import_zod16.z.string().datetime().nullable().describe(
769
+ "When the charge reached `confirmed`. `null` for a `mode: continuous` charge \u2014 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."
770
+ ),
771
+ splitAddress: import_zod16.z.string().describe(
772
+ "The on-chain address the payment was sent to \u2014 identical across every accepted network."
773
+ ),
774
+ payments: import_zod16.z.array(VerifyPaymentSchema).describe(
775
+ "One entry per `(token, network)` pair that actually contributed funds \u2014 a charge accepting several pairs can be confirmed by a combination of them, each proven and settled independently."
776
+ )
777
+ });
778
+
779
+ // src/health.ts
780
+ var import_zod17 = require("zod");
781
+ var HealthSchema = import_zod17.z.object({
782
+ status: import_zod17.z.enum(["ok", "error"]).describe(
783
+ "`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."
784
+ ),
785
+ version: import_zod17.z.string(),
786
+ timestamp: import_zod17.z.string().datetime(),
787
+ db: import_zod17.z.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
788
+ pendingWebhooks: import_zod17.z.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
789
+ oldestPendingChargeAgeSeconds: import_zod17.z.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
790
+ lastMoralisEventAgeSeconds: import_zod17.z.number().nullable().describe(
791
+ "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."
792
+ )
793
+ });
794
+
795
+ // src/sandbox.ts
796
+ var import_zod18 = require("zod");
797
+ var SandboxTriggerSchema = import_zod18.z.object({
798
+ event: TriggerableChargeEventSchema,
799
+ amount: import_zod18.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
800
+ "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."
801
+ )
802
+ });
803
+ var SandboxEventTriggerSchema = import_zod18.z.object({
804
+ event: NonChargeTriggerableEventSchema.describe(
805
+ "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)."
806
+ )
807
+ });
808
+
809
+ // src/capabilities.ts
810
+ var import_zod19 = require("zod");
811
+ var CapabilitiesSchema = import_zod19.z.object({
812
+ acceptedPayments: import_zod19.z.array(AcceptedPaymentSchema).describe(
813
+ "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."
814
+ )
815
+ });
816
+ // Annotate the CommonJS export names for ESM import in node:
817
+ 0 && (module.exports = {
818
+ AcceptInvitationSchema,
819
+ AcceptedPaymentSchema,
820
+ AccountWebhookEventTypeSchema,
821
+ ApiKeySchema,
822
+ AuthResponseSchema,
823
+ CHARGE_ACCEPTED_PAYMENTS_MAX,
824
+ CHARGE_AMOUNT_MAX,
825
+ CHARGE_EXPIRES_IN_MAX_SECONDS,
826
+ CHARGE_EXPIRES_IN_MIN_SECONDS,
827
+ CapabilitiesSchema,
828
+ ChargeModeSchema,
829
+ ChargeSchema,
830
+ ChargeStatusEventSchema,
831
+ ChargeStatusSchema,
832
+ ChargeWebhookEventTypeSchema,
833
+ CreateApiKeySchema,
834
+ CreateChargeSchema,
835
+ CreateWebhookSchema,
836
+ EVENT_CATEGORY_MAP,
837
+ EVM_NETWORKS,
838
+ EnvironmentSchema,
839
+ ErrorPayloadSchema,
840
+ ForgotPasswordSchema,
841
+ HealthSchema,
842
+ InvitationSchema,
843
+ InviteUserSchema,
844
+ ListApiKeysSchema,
845
+ ListChargesSchema,
846
+ ListOrganizationsSchema,
847
+ ListUsersSchema,
848
+ ListWebhookDeliveriesSchema,
849
+ LoginSchema,
850
+ MessageResponseSchema,
851
+ NETWORK_EXPLORERS,
852
+ NETWORK_LABELS,
853
+ NetworkSchema,
854
+ NonChargeTriggerableEventSchema,
855
+ NormalizedEmailSchema,
856
+ OPERATIONAL_NETWORKS,
857
+ OrganizationSchema,
858
+ OrganizationWithRoleSchema,
859
+ PAGINATION_LIMIT_DEFAULT,
860
+ PAGINATION_LIMIT_MAX,
861
+ PAGINATION_LIMIT_MIN,
862
+ PaginatedApiKeysSchema,
863
+ PaginatedChargesSchema,
864
+ PaginatedOrganizationsSchema,
865
+ PaginatedUsersSchema,
866
+ PaginatedWebhookDeliveriesSchema,
867
+ PaginationQuerySchema,
868
+ PendingDistributionEventSchema,
869
+ PendingDistributionRecipientSchema,
870
+ PendingDistributionSchema,
871
+ ResetPasswordSchema,
872
+ SandboxEventTriggerSchema,
873
+ SandboxTriggerSchema,
874
+ SecurityWebhookEventTypeSchema,
875
+ SettlementStatusSchema,
876
+ SignupSchema,
877
+ SplitRecipientRoleSchema,
878
+ TOKEN_ADDRESSES,
879
+ TOKEN_DECIMALS,
880
+ TimelineEventSchema,
881
+ TimelineEventTypeSchema,
882
+ TokenSchema,
883
+ TransactionSourceSchema,
884
+ TriggerableChargeEventSchema,
885
+ UpdateOrganizationSchema,
886
+ UpdateUserRoleSchema,
887
+ UserRoleSchema,
888
+ UserSchema,
889
+ VerifyChargeSchema,
890
+ VerifyEmailSchema,
891
+ VerifyPaymentSchema,
892
+ VerifySplitEntrySchema,
893
+ WEBHOOK_EVENTS_WILDCARD,
894
+ WEBHOOK_EVENT_CATEGORIES,
895
+ WebhookCategorySchema,
896
+ WebhookDeliveryEventTypeSchema,
897
+ WebhookDeliverySchema,
898
+ WebhookDeliveryStatusSchema,
899
+ WebhookEventTypeSchema,
900
+ WebhookListItemSchema,
901
+ WebhookPayloadSchema,
902
+ WebhookSchema,
903
+ paginatedSchema
904
+ });
905
+ //# sourceMappingURL=index.js.map