@klappay/types 2.0.2 → 2.0.4
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.d.mts +617 -12
- package/dist/index.d.ts +617 -12
- package/dist/index.js +238 -207
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +234 -207
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -134,27 +134,50 @@ var TOKEN_ADDRESSES = {
|
|
|
134
134
|
};
|
|
135
135
|
|
|
136
136
|
// src/charges.ts
|
|
137
|
+
import { z as z8 } from "zod";
|
|
138
|
+
|
|
139
|
+
// src/checkout-metadata.ts
|
|
137
140
|
import { z as z7 } from "zod";
|
|
138
|
-
var
|
|
141
|
+
var CHECKOUT_PRODUCTS_MAX = 20;
|
|
142
|
+
var CheckoutProductSchema = z7.object({
|
|
143
|
+
name: z7.string().min(1).max(200).describe("What the payer is buying, shown as-is on the hosted checkout page."),
|
|
144
|
+
quantity: z7.number().int().positive().max(9999).optional().describe("How many of this item. Omit for a single, unquantified item."),
|
|
145
|
+
imageUrl: z7.string().url().max(2048).refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
|
|
146
|
+
"Product image, fetched only by the payer's own browser \u2014 Klappay never fetches it server-side. Must be `http(s)`."
|
|
147
|
+
)
|
|
148
|
+
});
|
|
149
|
+
var KlappayCheckoutMetadataSchema = z7.object({
|
|
150
|
+
products: z7.array(CheckoutProductSchema).max(CHECKOUT_PRODUCTS_MAX).optional().describe(
|
|
151
|
+
`What the payer is buying, shown on the hosted checkout page \u2014 up to ${CHECKOUT_PRODUCTS_MAX} items. Purely informational: never validated against \`amount\`, never used by any payment or distribution logic.`
|
|
152
|
+
)
|
|
153
|
+
}).describe(
|
|
154
|
+
"Reserved for Klappay \u2014 the one namespace inside `metadata` whose format is defined and enforced by Klappay, not by you. A `metadata.klappay` that does not match this shape is rejected outright (`400 validation_error`), unlike every other key in `metadata`, which accepts absolutely anything and never fails validation."
|
|
155
|
+
);
|
|
156
|
+
var MetadataWithKlappaySchema = z7.object({ klappay: KlappayCheckoutMetadataSchema.optional() }).catchall(z7.unknown()).describe(
|
|
157
|
+
"Arbitrary key/value data, returned as-is on every read. Put whatever you want in here \u2014 none of it is validated, except the `klappay` key, which is reserved for Klappay: if present, it must match `KlappayCheckoutMetadataSchema` exactly, or the whole request is rejected with `400 validation_error`."
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
// src/charges.ts
|
|
161
|
+
var ChargeStatusSchema = z8.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
|
|
139
162
|
"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."
|
|
140
163
|
);
|
|
141
|
-
var SettlementStatusSchema =
|
|
164
|
+
var SettlementStatusSchema = z8.enum(["pending", "completed", "failed"]).describe(
|
|
142
165
|
"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."
|
|
143
166
|
);
|
|
144
167
|
var CHARGE_EXPIRES_IN_MIN_SECONDS = 60;
|
|
145
168
|
var CHARGE_EXPIRES_IN_MAX_SECONDS = 3600;
|
|
146
169
|
var CHARGE_ACCEPTED_PAYMENTS_MAX = 14;
|
|
147
|
-
var AcceptedPaymentSchema =
|
|
170
|
+
var AcceptedPaymentSchema = z8.object({
|
|
148
171
|
token: TokenSchema,
|
|
149
172
|
network: NetworkSchema
|
|
150
173
|
});
|
|
151
|
-
var AcceptedPaymentsSchema =
|
|
174
|
+
var AcceptedPaymentsSchema = z8.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
|
|
152
175
|
const seen = /* @__PURE__ */ new Set();
|
|
153
176
|
pairs.forEach((pair, index) => {
|
|
154
177
|
const key = `${pair.token}:${pair.network}`;
|
|
155
178
|
if (seen.has(key)) {
|
|
156
179
|
ctx.addIssue({
|
|
157
|
-
code:
|
|
180
|
+
code: z8.ZodIssueCode.custom,
|
|
158
181
|
message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,
|
|
159
182
|
path: [index]
|
|
160
183
|
});
|
|
@@ -162,7 +185,7 @@ var AcceptedPaymentsSchema = z7.array(AcceptedPaymentSchema).min(1, "At least on
|
|
|
162
185
|
seen.add(key);
|
|
163
186
|
if (!OPERATIONAL_NETWORKS.includes(pair.network)) {
|
|
164
187
|
ctx.addIssue({
|
|
165
|
-
code:
|
|
188
|
+
code: z8.ZodIssueCode.custom,
|
|
166
189
|
message: `Network "${pair.network}" isn't live yet \u2014 only ${OPERATIONAL_NETWORKS.join(", ")} today.`,
|
|
167
190
|
path: [index, "network"]
|
|
168
191
|
});
|
|
@@ -172,22 +195,22 @@ var AcceptedPaymentsSchema = z7.array(AcceptedPaymentSchema).min(1, "At least on
|
|
|
172
195
|
`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\`.`
|
|
173
196
|
);
|
|
174
197
|
var CHARGE_SPLIT_RECIPIENTS_MAX = 5;
|
|
175
|
-
var SplitRecipientSchema =
|
|
176
|
-
address:
|
|
177
|
-
percent:
|
|
198
|
+
var SplitRecipientSchema = z8.object({
|
|
199
|
+
address: z8.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").describe("EVM address to send a slice of this charge to."),
|
|
200
|
+
percent: z8.number().positive().max(100).describe(
|
|
178
201
|
"Percent of *your own* net share (i.e. of `100 - feePercent`, not of the charge's gross `amount`) to route to this address instead of your own payout wallet. Klappay's fee is computed on the gross amount first and is never diluted by how you choose to split what's left \u2014 see `docs/payments.md`'s \"Settling the payout\" section for the exact math."
|
|
179
202
|
),
|
|
180
|
-
label:
|
|
203
|
+
label: z8.string().min(1).max(64).optional().describe(
|
|
181
204
|
'Free-form label for your own bookkeeping (e.g. `"supplier"`, `"sales rep"`) \u2014 echoed back unchanged, never interpreted by Klappay.'
|
|
182
205
|
)
|
|
183
206
|
});
|
|
184
|
-
var SplitRecipientsSchema =
|
|
207
|
+
var SplitRecipientsSchema = z8.array(SplitRecipientSchema).max(CHARGE_SPLIT_RECIPIENTS_MAX).superRefine((recipients, ctx) => {
|
|
185
208
|
const seen = /* @__PURE__ */ new Set();
|
|
186
209
|
recipients.forEach((recipient, index) => {
|
|
187
210
|
const key = recipient.address.toLowerCase();
|
|
188
211
|
if (seen.has(key)) {
|
|
189
212
|
ctx.addIssue({
|
|
190
|
-
code:
|
|
213
|
+
code: z8.ZodIssueCode.custom,
|
|
191
214
|
message: `Duplicate split recipient address: ${recipient.address}.`,
|
|
192
215
|
path: [index, "address"]
|
|
193
216
|
});
|
|
@@ -198,79 +221,79 @@ var SplitRecipientsSchema = z7.array(SplitRecipientSchema).max(CHARGE_SPLIT_RECI
|
|
|
198
221
|
`Optional extra recipients for this charge's split \u2014 e.g. a supplier or the sales rep who closed the deal \u2014 up to ${CHARGE_SPLIT_RECIPIENTS_MAX}. Frozen at creation exactly like everything else that shapes the split address; cannot be changed afterward. The sum of every \`percent\` here must fit within \`100 - feePercent\` (your own net share) \u2014 a request that doesn't is rejected with \`422 split_recipients_exceed_available_percent\`.`
|
|
199
222
|
);
|
|
200
223
|
var CHARGE_AMOUNT_MAX = 999999999999;
|
|
201
|
-
var CreateChargeSchema =
|
|
202
|
-
amount:
|
|
224
|
+
var CreateChargeSchema = z8.object({
|
|
225
|
+
amount: z8.number().positive().max(CHARGE_AMOUNT_MAX).describe(
|
|
203
226
|
"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."
|
|
204
227
|
),
|
|
205
|
-
currency:
|
|
228
|
+
currency: z8.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
|
|
206
229
|
acceptedPayments: AcceptedPaymentsSchema,
|
|
207
|
-
expiresIn:
|
|
230
|
+
expiresIn: z8.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
|
|
208
231
|
"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."
|
|
209
232
|
),
|
|
210
|
-
idempotencyKey:
|
|
233
|
+
idempotencyKey: z8.string().min(1).max(255).optional().describe(
|
|
211
234
|
"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."
|
|
212
235
|
),
|
|
213
|
-
externalRef:
|
|
236
|
+
externalRef: z8.string().min(1).max(255).optional().describe(
|
|
214
237
|
"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."
|
|
215
238
|
),
|
|
216
|
-
source:
|
|
239
|
+
source: z8.string().min(1).max(64).optional().describe(
|
|
217
240
|
'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.'
|
|
218
241
|
),
|
|
219
|
-
metadata:
|
|
220
|
-
redirectUrl:
|
|
242
|
+
metadata: MetadataWithKlappaySchema.optional(),
|
|
243
|
+
redirectUrl: z8.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
|
|
221
244
|
"Where to send the payer once this charge resolves, if you use Klappay's hosted checkout page (see `checkoutUrl` on the read shape) \u2014 ignored otherwise. Must be `http(s)` \u2014 a browser will navigate here, so `javascript:`/`data:` and other non-navigational schemes are rejected. Otherwise not validated beyond being well-formed; what happens at that destination is yours to build."
|
|
222
245
|
),
|
|
223
246
|
splitRecipients: SplitRecipientsSchema.optional()
|
|
224
247
|
});
|
|
225
|
-
var ChargeSchema =
|
|
226
|
-
id:
|
|
227
|
-
amount:
|
|
228
|
-
amountReceived:
|
|
248
|
+
var ChargeSchema = z8.object({
|
|
249
|
+
id: z8.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
|
|
250
|
+
amount: z8.number().describe("The amount originally requested, in `currency` units (up to 6 decimal places)."),
|
|
251
|
+
amountReceived: z8.number().nullable().describe(
|
|
229
252
|
"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`."
|
|
230
253
|
),
|
|
231
|
-
isOverpaid:
|
|
254
|
+
isOverpaid: z8.boolean().describe(
|
|
232
255
|
"`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically \u2014 see the docs for why."
|
|
233
256
|
),
|
|
234
|
-
currency:
|
|
235
|
-
acceptedPayments:
|
|
257
|
+
currency: z8.string().describe("Always `USD` today \u2014 the only supported currency."),
|
|
258
|
+
acceptedPayments: z8.array(AcceptedPaymentSchema).describe(
|
|
236
259
|
"Every `(token, network)` pair this charge was configured to accept, unchanged after creation."
|
|
237
260
|
),
|
|
238
|
-
paidWith:
|
|
261
|
+
paidWith: z8.array(AcceptedPaymentSchema).describe(
|
|
239
262
|
"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`."
|
|
240
263
|
),
|
|
241
|
-
address:
|
|
264
|
+
address: z8.string().describe(
|
|
242
265
|
"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."
|
|
243
266
|
),
|
|
244
267
|
status: ChargeStatusSchema,
|
|
245
268
|
settlementStatus: SettlementStatusSchema.nullable(),
|
|
246
269
|
environment: EnvironmentSchema,
|
|
247
|
-
apiKeyId:
|
|
270
|
+
apiKeyId: z8.string().nullable().describe(
|
|
248
271
|
"Which of your API keys created this charge. `null` for a charge created before this field existed."
|
|
249
272
|
),
|
|
250
|
-
txHash:
|
|
273
|
+
txHash: z8.string().nullable().describe(
|
|
251
274
|
"Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected."
|
|
252
275
|
),
|
|
253
|
-
externalRef:
|
|
254
|
-
source:
|
|
255
|
-
metadata:
|
|
256
|
-
redirectUrl:
|
|
257
|
-
checkoutUrl:
|
|
276
|
+
externalRef: z8.string().nullable(),
|
|
277
|
+
source: z8.string().nullable(),
|
|
278
|
+
metadata: MetadataWithKlappaySchema.nullable(),
|
|
279
|
+
redirectUrl: z8.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
|
|
280
|
+
checkoutUrl: z8.string().nullable().describe(
|
|
258
281
|
"Link to Klappay's hosted checkout page for this charge. `null` if this deployment has no hosted checkout configured \u2014 build your own payment UI from `address`/`acceptedPayments` instead."
|
|
259
282
|
),
|
|
260
|
-
splitRecipients:
|
|
261
|
-
createdAt:
|
|
262
|
-
expiresAt:
|
|
283
|
+
splitRecipients: z8.array(SplitRecipientSchema).describe("Echoes whatever extra split recipients were set at creation \u2014 empty array if none."),
|
|
284
|
+
createdAt: z8.string().datetime(),
|
|
285
|
+
expiresAt: z8.string().datetime().describe(
|
|
263
286
|
"When this charge stops accepting payment, if still `pending`/`partially_paid` by then."
|
|
264
287
|
),
|
|
265
|
-
confirmedAt:
|
|
266
|
-
settledAt:
|
|
288
|
+
confirmedAt: z8.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
|
|
289
|
+
settledAt: z8.string().datetime().nullable().describe(
|
|
267
290
|
"When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
|
|
268
291
|
),
|
|
269
|
-
lastActivityAt:
|
|
292
|
+
lastActivityAt: z8.string().datetime().describe(
|
|
270
293
|
"When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet."
|
|
271
294
|
)
|
|
272
295
|
});
|
|
273
|
-
var ListChargesSchema =
|
|
296
|
+
var ListChargesSchema = z8.object({
|
|
274
297
|
status: ChargeStatusSchema.optional(),
|
|
275
298
|
token: TokenSchema.optional().describe(
|
|
276
299
|
"Filters on `paidWith.token` \u2014 the pair actually paid, not accepted."
|
|
@@ -279,13 +302,13 @@ var ListChargesSchema = z7.object({
|
|
|
279
302
|
"Filters on `paidWith.network` \u2014 the pair actually paid, not accepted."
|
|
280
303
|
),
|
|
281
304
|
environment: EnvironmentSchema.optional(),
|
|
282
|
-
since:
|
|
305
|
+
since: z8.string().datetime().optional().describe(
|
|
283
306
|
"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."
|
|
284
307
|
),
|
|
285
|
-
isOverpaid:
|
|
308
|
+
isOverpaid: z8.enum(["true", "false"]).transform((v) => v === "true").optional()
|
|
286
309
|
}).extend(PaginationQuerySchema.shape);
|
|
287
310
|
var PaginatedChargesSchema = paginatedSchema(ChargeSchema);
|
|
288
|
-
var GetChargeQrCodeQuerySchema =
|
|
311
|
+
var GetChargeQrCodeQuerySchema = z8.object({
|
|
289
312
|
token: TokenSchema.optional().describe(
|
|
290
313
|
"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."
|
|
291
314
|
),
|
|
@@ -293,61 +316,61 @@ var GetChargeQrCodeQuerySchema = z7.object({
|
|
|
293
316
|
});
|
|
294
317
|
|
|
295
318
|
// src/distributions.ts
|
|
296
|
-
import { z as
|
|
297
|
-
var SplitDistributionStatusSchema =
|
|
319
|
+
import { z as z9 } from "zod";
|
|
320
|
+
var SplitDistributionStatusSchema = z9.enum(["pending", "processing", "completed", "failed"]).describe(
|
|
298
321
|
"Status of one payout attempt to the merchant, for a single `(token, network)` pair \u2014 a charge that settles across more than one pair has one of these per pair. `pending`: queued, not yet claimed by a distributor. `processing`: a distributor (Klappay's own worker, or anyone racing to call `distribute()` first, see `PendingDistributionSchema`) has claimed it and is submitting the on-chain transaction. `completed`: the merchant's wallet has the funds. `failed`: every automatic retry was exhausted."
|
|
299
322
|
);
|
|
300
|
-
var PendingDistributionRecipientSchema =
|
|
301
|
-
address:
|
|
302
|
-
percentAllocation:
|
|
323
|
+
var PendingDistributionRecipientSchema = z9.object({
|
|
324
|
+
address: z9.string().describe("On-chain recipient address."),
|
|
325
|
+
percentAllocation: z9.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
|
|
303
326
|
});
|
|
304
|
-
var PendingDistributionSchema =
|
|
305
|
-
splitAddress:
|
|
327
|
+
var PendingDistributionSchema = z9.object({
|
|
328
|
+
splitAddress: z9.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
|
|
306
329
|
network: NetworkSchema,
|
|
307
330
|
token: TokenSchema,
|
|
308
|
-
recipients:
|
|
331
|
+
recipients: z9.array(PendingDistributionRecipientSchema).describe(
|
|
309
332
|
"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."
|
|
310
333
|
),
|
|
311
|
-
distributorFeePercent:
|
|
334
|
+
distributorFeePercent: z9.number().describe(
|
|
312
335
|
"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."
|
|
313
336
|
),
|
|
314
|
-
estimatedRewardAmount:
|
|
337
|
+
estimatedRewardAmount: z9.number().describe(
|
|
315
338
|
"Estimate only, in the charge's `currency` units, based on the amount Klappay detected on-chain \u2014 not a live read of the split's current balance. Read the balance yourself before submitting a transaction; a stale estimate is harmless (see the docs), never a reason to skip that check."
|
|
316
339
|
),
|
|
317
|
-
availableSince:
|
|
318
|
-
graceEndsAt:
|
|
340
|
+
availableSince: z9.string().datetime().describe("When this distribution entered its grace period."),
|
|
341
|
+
graceEndsAt: z9.string().datetime().describe(
|
|
319
342
|
"When Klappay's own worker may claim this distribution. Racing to call `distribute()` after this timestamp is possible but increasingly likely to lose to the worker."
|
|
320
343
|
)
|
|
321
344
|
});
|
|
322
345
|
var PaginatedPendingDistributionsSchema = paginatedSchema(PendingDistributionSchema);
|
|
323
|
-
var ListenPendingDistributionsQuerySchema =
|
|
324
|
-
limit:
|
|
346
|
+
var ListenPendingDistributionsQuerySchema = z9.object({
|
|
347
|
+
limit: z9.coerce.number().int().min(0).max(PAGINATION_LIMIT_MAX).default(0).describe(
|
|
325
348
|
"How many currently-claimable distributions to emit as an initial snapshot right after connecting \u2014 each as a synthetic `distribution.available` event \u2014 before continuing with real-time deltas. `0` (the default, same as omitting it) sends no snapshot at all, matching this endpoint's original behavior: connect first, then call `GET /v1/distributions/pending` yourself to bootstrap. Not a page \u2014 there is no cursor for this snapshot, so if more than `limit` are claimable at connect time, the excess is simply not sent; call `GET /v1/distributions/pending` directly for a complete, paginated listing."
|
|
326
349
|
)
|
|
327
350
|
});
|
|
328
|
-
var PendingDistributionEventSchema =
|
|
329
|
-
|
|
330
|
-
type:
|
|
351
|
+
var PendingDistributionEventSchema = z9.discriminatedUnion("type", [
|
|
352
|
+
z9.object({
|
|
353
|
+
type: z9.literal("distribution.available"),
|
|
331
354
|
distribution: PendingDistributionSchema
|
|
332
355
|
}),
|
|
333
|
-
|
|
334
|
-
type:
|
|
335
|
-
splitAddress:
|
|
356
|
+
z9.object({
|
|
357
|
+
type: z9.literal("distribution.claimed"),
|
|
358
|
+
splitAddress: z9.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
|
|
336
359
|
})
|
|
337
360
|
]);
|
|
338
361
|
|
|
339
362
|
// src/metrics.ts
|
|
340
|
-
import { z as
|
|
341
|
-
var MetricsResourceSchema =
|
|
363
|
+
import { z as z10 } from "zod";
|
|
364
|
+
var MetricsResourceSchema = z10.enum(["charges", "transactions", "distributions"]).describe(
|
|
342
365
|
"Which underlying dataset to query. `charges`: one row per charge. `transactions`: one row per detected on-chain transfer \u2014 a charge paid in installments has more than one. `distributions`: one row per payout attempt to the merchant, one per `(token, network)` pair a charge settled across."
|
|
343
366
|
);
|
|
344
|
-
var MetricsAggregationSchema =
|
|
367
|
+
var MetricsAggregationSchema = z10.enum(["count", "sum", "avg", "min", "max"]).describe(
|
|
345
368
|
"`count` counts matching rows and never takes `field`. `sum`/`avg`/`min`/`max` require `field` to be set to one of the resource\u2019s numeric fields."
|
|
346
369
|
);
|
|
347
|
-
var MetricsFilterOperatorSchema =
|
|
370
|
+
var MetricsFilterOperatorSchema = z10.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
|
|
348
371
|
"`in` expects an array value (max 50 entries); every other operator expects a single scalar."
|
|
349
372
|
);
|
|
350
|
-
var MetricsDateGranularitySchema =
|
|
373
|
+
var MetricsDateGranularitySchema = z10.enum(["day", "week", "month", "year"]).describe(
|
|
351
374
|
"Bucket width for a `date_bucket` `groupBy` entry \u2014 Postgres `date_trunc` semantics (UTC)."
|
|
352
375
|
);
|
|
353
376
|
var metricsQueryEnvironmentSchema = EnvironmentSchema.describe(
|
|
@@ -360,151 +383,151 @@ var METRICS_QUERY_MAX_GROUP_BY = 3;
|
|
|
360
383
|
var METRICS_QUERY_MAX_FILTERS = 20;
|
|
361
384
|
var METRICS_QUERY_MAX_METRICS = 10;
|
|
362
385
|
var METRIC_ALIAS_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
363
|
-
var metricAliasSchema =
|
|
386
|
+
var metricAliasSchema = z10.string().min(1).max(64).regex(
|
|
364
387
|
METRIC_ALIAS_PATTERN,
|
|
365
388
|
"Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 this becomes a SQL column alias."
|
|
366
389
|
).optional();
|
|
367
|
-
var MetricsFilterValueSchema =
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
390
|
+
var MetricsFilterValueSchema = z10.union([
|
|
391
|
+
z10.string().max(255),
|
|
392
|
+
z10.number(),
|
|
393
|
+
z10.boolean(),
|
|
394
|
+
z10.array(z10.union([z10.string().max(255), z10.number()])).min(1).max(50)
|
|
372
395
|
]);
|
|
373
|
-
var orderBySchema =
|
|
374
|
-
key:
|
|
396
|
+
var orderBySchema = z10.object({
|
|
397
|
+
key: z10.string().min(1).max(64).regex(
|
|
375
398
|
METRIC_ALIAS_PATTERN,
|
|
376
399
|
"Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 every valid output column name already looks like this."
|
|
377
400
|
).describe(
|
|
378
401
|
"An output column name from this same query \u2014 either a `groupBy` field name, or a metric\u2019s `alias` (or its default name: `${aggregation}` for `count`, `${aggregation}_${field}` otherwise, e.g. `sum_amount`). Must match `^[a-zA-Z_][a-zA-Z0-9_]*$` \u2014 every real output column name already does, so this only ever rejects a value that could never have been one."
|
|
379
402
|
),
|
|
380
|
-
direction:
|
|
403
|
+
direction: z10.enum(["asc", "desc"])
|
|
381
404
|
}).describe(
|
|
382
405
|
"Sort the result rows by any output column \u2014 including the bucket field itself for a `date_bucket` query (e.g. `createdAt`). Omit to get ascending-by-bucket order for a date-bucketed query, or implementation-defined (not guaranteed stable) order otherwise."
|
|
383
406
|
);
|
|
384
|
-
var limitSchema =
|
|
407
|
+
var limitSchema = z10.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
|
|
385
408
|
`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.`
|
|
386
409
|
);
|
|
387
|
-
var ChargesQueryFieldSchema =
|
|
410
|
+
var ChargesQueryFieldSchema = z10.enum(["status", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
|
|
388
411
|
"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."
|
|
389
412
|
);
|
|
390
|
-
var ChargesMetricFieldSchema =
|
|
413
|
+
var ChargesMetricFieldSchema = z10.enum(["amount", "amountReceived", "feePercent"]).describe(
|
|
391
414
|
"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%."
|
|
392
415
|
);
|
|
393
|
-
var ChargesDateFieldSchema =
|
|
416
|
+
var ChargesDateFieldSchema = z10.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt"]).describe(
|
|
394
417
|
"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."
|
|
395
418
|
);
|
|
396
|
-
var ChargesFilterSchema =
|
|
419
|
+
var ChargesFilterSchema = z10.object({
|
|
397
420
|
field: ChargesQueryFieldSchema,
|
|
398
421
|
operator: MetricsFilterOperatorSchema,
|
|
399
422
|
value: MetricsFilterValueSchema
|
|
400
423
|
});
|
|
401
|
-
var ChargesGroupBySchema =
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
type:
|
|
424
|
+
var ChargesGroupBySchema = z10.union([
|
|
425
|
+
z10.object({ type: z10.literal("field"), field: ChargesQueryFieldSchema }),
|
|
426
|
+
z10.object({
|
|
427
|
+
type: z10.literal("date_bucket"),
|
|
405
428
|
field: ChargesDateFieldSchema,
|
|
406
429
|
granularity: MetricsDateGranularitySchema
|
|
407
430
|
})
|
|
408
431
|
]);
|
|
409
|
-
var ChargesMetricSchema =
|
|
432
|
+
var ChargesMetricSchema = z10.object({
|
|
410
433
|
aggregation: MetricsAggregationSchema,
|
|
411
434
|
field: ChargesMetricFieldSchema.optional(),
|
|
412
435
|
alias: metricAliasSchema
|
|
413
436
|
});
|
|
414
|
-
var ChargesMetricsQuerySchema =
|
|
415
|
-
resource:
|
|
437
|
+
var ChargesMetricsQuerySchema = z10.object({
|
|
438
|
+
resource: z10.literal("charges"),
|
|
416
439
|
environment: metricsQueryEnvironmentSchema,
|
|
417
|
-
dateRange:
|
|
440
|
+
dateRange: z10.object({
|
|
418
441
|
field: ChargesDateFieldSchema,
|
|
419
|
-
from:
|
|
420
|
-
to:
|
|
442
|
+
from: z10.string().max(64).datetime(),
|
|
443
|
+
to: z10.string().max(64).datetime()
|
|
421
444
|
}),
|
|
422
|
-
groupBy:
|
|
423
|
-
metrics:
|
|
424
|
-
filters:
|
|
445
|
+
groupBy: z10.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
|
|
446
|
+
metrics: z10.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
|
|
447
|
+
filters: z10.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
|
|
425
448
|
orderBy: orderBySchema.optional(),
|
|
426
449
|
limit: limitSchema
|
|
427
450
|
});
|
|
428
|
-
var TransactionsQueryFieldSchema =
|
|
451
|
+
var TransactionsQueryFieldSchema = z10.enum(["network", "token", "source", "causedTransition"]).describe(
|
|
429
452
|
"A `Transaction` field to filter or group by \u2014 see `NetworkSchema`/`TokenSchema`/`TransactionSourceSchema` for their possible values. `causedTransition` is `true` only for the transfer(s) that actually flipped the charge's `status` \u2014 a charge paid in installments can have more than one; filtering/grouping on it excludes no-op duplicate transfers (see `TimelineEvent.causedTransition` in charges.md for the full explanation)."
|
|
430
453
|
);
|
|
431
|
-
var TransactionsMetricFieldSchema =
|
|
432
|
-
var TransactionsDateFieldSchema =
|
|
433
|
-
var TransactionsFilterSchema =
|
|
454
|
+
var TransactionsMetricFieldSchema = z10.enum(["amount"]).describe("The transfer amount, in the charge's `currency` units.");
|
|
455
|
+
var TransactionsDateFieldSchema = z10.enum(["detectedAt"]).describe("When Klappay detected this transfer on-chain (not when it was mined).");
|
|
456
|
+
var TransactionsFilterSchema = z10.object({
|
|
434
457
|
field: TransactionsQueryFieldSchema,
|
|
435
458
|
operator: MetricsFilterOperatorSchema,
|
|
436
459
|
value: MetricsFilterValueSchema
|
|
437
460
|
});
|
|
438
|
-
var TransactionsGroupBySchema =
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
type:
|
|
461
|
+
var TransactionsGroupBySchema = z10.union([
|
|
462
|
+
z10.object({ type: z10.literal("field"), field: TransactionsQueryFieldSchema }),
|
|
463
|
+
z10.object({
|
|
464
|
+
type: z10.literal("date_bucket"),
|
|
442
465
|
field: TransactionsDateFieldSchema,
|
|
443
466
|
granularity: MetricsDateGranularitySchema
|
|
444
467
|
})
|
|
445
468
|
]);
|
|
446
|
-
var TransactionsMetricSchema =
|
|
469
|
+
var TransactionsMetricSchema = z10.object({
|
|
447
470
|
aggregation: MetricsAggregationSchema,
|
|
448
471
|
field: TransactionsMetricFieldSchema.optional(),
|
|
449
472
|
alias: metricAliasSchema
|
|
450
473
|
});
|
|
451
|
-
var TransactionsMetricsQuerySchema =
|
|
452
|
-
resource:
|
|
474
|
+
var TransactionsMetricsQuerySchema = z10.object({
|
|
475
|
+
resource: z10.literal("transactions"),
|
|
453
476
|
environment: metricsQueryEnvironmentSchema,
|
|
454
|
-
dateRange:
|
|
477
|
+
dateRange: z10.object({
|
|
455
478
|
field: TransactionsDateFieldSchema,
|
|
456
|
-
from:
|
|
457
|
-
to:
|
|
479
|
+
from: z10.string().max(64).datetime(),
|
|
480
|
+
to: z10.string().max(64).datetime()
|
|
458
481
|
}),
|
|
459
|
-
groupBy:
|
|
460
|
-
metrics:
|
|
461
|
-
filters:
|
|
482
|
+
groupBy: z10.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
|
|
483
|
+
metrics: z10.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
|
|
484
|
+
filters: z10.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
|
|
462
485
|
orderBy: orderBySchema.optional(),
|
|
463
486
|
limit: limitSchema
|
|
464
487
|
});
|
|
465
|
-
var DistributionsQueryFieldSchema =
|
|
488
|
+
var DistributionsQueryFieldSchema = z10.enum(["status", "network", "token", "distributorAddress"]).describe(
|
|
466
489
|
"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."
|
|
467
490
|
);
|
|
468
|
-
var DistributionsMetricFieldSchema =
|
|
491
|
+
var DistributionsMetricFieldSchema = z10.enum(["attempts"]).describe(
|
|
469
492
|
"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."
|
|
470
493
|
);
|
|
471
|
-
var DistributionsDateFieldSchema =
|
|
494
|
+
var DistributionsDateFieldSchema = z10.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
|
|
472
495
|
"`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."
|
|
473
496
|
);
|
|
474
|
-
var DistributionsFilterSchema =
|
|
497
|
+
var DistributionsFilterSchema = z10.object({
|
|
475
498
|
field: DistributionsQueryFieldSchema,
|
|
476
499
|
operator: MetricsFilterOperatorSchema,
|
|
477
500
|
value: MetricsFilterValueSchema
|
|
478
501
|
});
|
|
479
|
-
var DistributionsGroupBySchema =
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
type:
|
|
502
|
+
var DistributionsGroupBySchema = z10.union([
|
|
503
|
+
z10.object({ type: z10.literal("field"), field: DistributionsQueryFieldSchema }),
|
|
504
|
+
z10.object({
|
|
505
|
+
type: z10.literal("date_bucket"),
|
|
483
506
|
field: DistributionsDateFieldSchema,
|
|
484
507
|
granularity: MetricsDateGranularitySchema
|
|
485
508
|
})
|
|
486
509
|
]);
|
|
487
|
-
var DistributionsMetricSchema =
|
|
510
|
+
var DistributionsMetricSchema = z10.object({
|
|
488
511
|
aggregation: MetricsAggregationSchema,
|
|
489
512
|
field: DistributionsMetricFieldSchema.optional(),
|
|
490
513
|
alias: metricAliasSchema
|
|
491
514
|
});
|
|
492
|
-
var DistributionsMetricsQuerySchema =
|
|
493
|
-
resource:
|
|
515
|
+
var DistributionsMetricsQuerySchema = z10.object({
|
|
516
|
+
resource: z10.literal("distributions"),
|
|
494
517
|
environment: metricsQueryEnvironmentSchema,
|
|
495
|
-
dateRange:
|
|
518
|
+
dateRange: z10.object({
|
|
496
519
|
field: DistributionsDateFieldSchema,
|
|
497
|
-
from:
|
|
498
|
-
to:
|
|
520
|
+
from: z10.string().max(64).datetime(),
|
|
521
|
+
to: z10.string().max(64).datetime()
|
|
499
522
|
}),
|
|
500
|
-
groupBy:
|
|
501
|
-
metrics:
|
|
502
|
-
filters:
|
|
523
|
+
groupBy: z10.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
|
|
524
|
+
metrics: z10.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
|
|
525
|
+
filters: z10.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
|
|
503
526
|
orderBy: orderBySchema.optional(),
|
|
504
527
|
limit: limitSchema
|
|
505
528
|
});
|
|
506
529
|
var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
|
|
507
|
-
var MetricsQuerySchema =
|
|
530
|
+
var MetricsQuerySchema = z10.discriminatedUnion("resource", [
|
|
508
531
|
ChargesMetricsQuerySchema,
|
|
509
532
|
TransactionsMetricsQuerySchema,
|
|
510
533
|
DistributionsMetricsQuerySchema
|
|
@@ -513,7 +536,7 @@ var MetricsQuerySchema = z9.discriminatedUnion("resource", [
|
|
|
513
536
|
const to = new Date(input.dateRange.to);
|
|
514
537
|
if (from >= to) {
|
|
515
538
|
ctx.addIssue({
|
|
516
|
-
code:
|
|
539
|
+
code: z10.ZodIssueCode.custom,
|
|
517
540
|
message: "`dateRange.from` must be before `dateRange.to`.",
|
|
518
541
|
path: ["dateRange", "from"]
|
|
519
542
|
});
|
|
@@ -521,7 +544,7 @@ var MetricsQuerySchema = z9.discriminatedUnion("resource", [
|
|
|
521
544
|
const spanDays = (to.getTime() - from.getTime()) / ONE_DAY_MS;
|
|
522
545
|
if (spanDays > MAX_METRICS_QUERY_DATE_RANGE_DAYS) {
|
|
523
546
|
ctx.addIssue({
|
|
524
|
-
code:
|
|
547
|
+
code: z10.ZodIssueCode.custom,
|
|
525
548
|
message: `\`dateRange\` cannot span more than ${MAX_METRICS_QUERY_DATE_RANGE_DAYS} days.`,
|
|
526
549
|
path: ["dateRange", "to"]
|
|
527
550
|
});
|
|
@@ -529,7 +552,7 @@ var MetricsQuerySchema = z9.discriminatedUnion("resource", [
|
|
|
529
552
|
const dateBucketCount = input.groupBy.filter((entry) => entry.type === "date_bucket").length;
|
|
530
553
|
if (dateBucketCount > 1) {
|
|
531
554
|
ctx.addIssue({
|
|
532
|
-
code:
|
|
555
|
+
code: z10.ZodIssueCode.custom,
|
|
533
556
|
message: "At most one `date_bucket` entry is allowed in `groupBy`.",
|
|
534
557
|
path: ["groupBy"]
|
|
535
558
|
});
|
|
@@ -537,7 +560,7 @@ var MetricsQuerySchema = z9.discriminatedUnion("resource", [
|
|
|
537
560
|
input.metrics.forEach((metric, index) => {
|
|
538
561
|
if (metric.aggregation !== "count" && metric.field === void 0) {
|
|
539
562
|
ctx.addIssue({
|
|
540
|
-
code:
|
|
563
|
+
code: z10.ZodIssueCode.custom,
|
|
541
564
|
message: "`field` is required unless `aggregation` is `count`.",
|
|
542
565
|
path: ["metrics", index, "field"]
|
|
543
566
|
});
|
|
@@ -546,7 +569,7 @@ var MetricsQuerySchema = z9.discriminatedUnion("resource", [
|
|
|
546
569
|
const aliases = input.metrics.map((metric) => metric.alias).filter((alias) => alias !== void 0);
|
|
547
570
|
if (new Set(aliases).size !== aliases.length) {
|
|
548
571
|
ctx.addIssue({
|
|
549
|
-
code:
|
|
572
|
+
code: z10.ZodIssueCode.custom,
|
|
550
573
|
message: "Every `metrics[].alias` must be unique.",
|
|
551
574
|
path: ["metrics"]
|
|
552
575
|
});
|
|
@@ -555,32 +578,32 @@ var MetricsQuerySchema = z9.discriminatedUnion("resource", [
|
|
|
555
578
|
input.metrics.forEach((metric, index) => {
|
|
556
579
|
if (metric.alias !== void 0 && reservedNames.has(metric.alias)) {
|
|
557
580
|
ctx.addIssue({
|
|
558
|
-
code:
|
|
581
|
+
code: z10.ZodIssueCode.custom,
|
|
559
582
|
message: `\`alias\` "${metric.alias}" collides with a \`groupBy\` field name (or the reserved word "bucket") \u2014 choose a different alias.`,
|
|
560
583
|
path: ["metrics", index, "alias"]
|
|
561
584
|
});
|
|
562
585
|
}
|
|
563
586
|
});
|
|
564
587
|
});
|
|
565
|
-
var MetricsQueryResultRowSchema =
|
|
566
|
-
|
|
567
|
-
|
|
588
|
+
var MetricsQueryResultRowSchema = z10.record(
|
|
589
|
+
z10.string(),
|
|
590
|
+
z10.union([z10.string(), z10.number(), z10.boolean(), z10.null()])
|
|
568
591
|
);
|
|
569
|
-
var MetricsQueryResultSchema =
|
|
570
|
-
data:
|
|
571
|
-
meta:
|
|
592
|
+
var MetricsQueryResultSchema = z10.object({
|
|
593
|
+
data: z10.array(MetricsQueryResultRowSchema),
|
|
594
|
+
meta: z10.object({
|
|
572
595
|
resource: MetricsResourceSchema,
|
|
573
596
|
environment: EnvironmentSchema,
|
|
574
|
-
rowCount:
|
|
575
|
-
truncated:
|
|
597
|
+
rowCount: z10.number().int().describe("Number of rows in `data`."),
|
|
598
|
+
truncated: z10.boolean().describe(
|
|
576
599
|
"`true` if more rows matched than `limit` allowed \u2014 `data` holds only the first `limit`."
|
|
577
600
|
)
|
|
578
601
|
})
|
|
579
602
|
});
|
|
580
603
|
|
|
581
604
|
// src/webhook-events.ts
|
|
582
|
-
import { z as
|
|
583
|
-
var ChargeWebhookEventTypeSchema =
|
|
605
|
+
import { z as z11 } from "zod";
|
|
606
|
+
var ChargeWebhookEventTypeSchema = z11.enum([
|
|
584
607
|
"charge.created",
|
|
585
608
|
"charge.partially_paid",
|
|
586
609
|
"charge.confirmed",
|
|
@@ -592,14 +615,14 @@ var ChargeWebhookEventTypeSchema = z10.enum([
|
|
|
592
615
|
]).describe(
|
|
593
616
|
'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`.'
|
|
594
617
|
);
|
|
595
|
-
var WebhookDeliveryEventTypeSchema =
|
|
618
|
+
var WebhookDeliveryEventTypeSchema = z11.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
|
|
596
619
|
"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`)."
|
|
597
620
|
);
|
|
598
|
-
var WebhookEventTypeSchema =
|
|
621
|
+
var WebhookEventTypeSchema = z11.union([
|
|
599
622
|
ChargeWebhookEventTypeSchema,
|
|
600
623
|
WebhookDeliveryEventTypeSchema
|
|
601
624
|
]);
|
|
602
|
-
var WebhookCategorySchema =
|
|
625
|
+
var WebhookCategorySchema = z11.enum(["payments", "webhooks"]).describe(
|
|
603
626
|
"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."
|
|
604
627
|
);
|
|
605
628
|
function buildCategoryMap() {
|
|
@@ -627,78 +650,78 @@ var TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([
|
|
|
627
650
|
);
|
|
628
651
|
|
|
629
652
|
// src/webhooks.ts
|
|
630
|
-
import { z as
|
|
653
|
+
import { z as z12 } from "zod";
|
|
631
654
|
var WEBHOOK_EVENTS_WILDCARD = "*";
|
|
632
|
-
var CreateWebhookSchema =
|
|
633
|
-
url:
|
|
655
|
+
var CreateWebhookSchema = z12.object({
|
|
656
|
+
url: z12.string().max(2048).url().describe(
|
|
634
657
|
"Must be HTTPS and resolve to a public address \u2014 private/internal IPs are rejected."
|
|
635
658
|
),
|
|
636
|
-
events:
|
|
659
|
+
events: z12.array(z12.union([WebhookEventTypeSchema, z12.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
|
|
637
660
|
'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.'
|
|
638
661
|
),
|
|
639
|
-
eventCategories:
|
|
662
|
+
eventCategories: z12.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
|
|
640
663
|
"Subscribe to every event in these categories. At least one of `events` or `eventCategories` is required."
|
|
641
664
|
),
|
|
642
|
-
excludeEvents:
|
|
665
|
+
excludeEvents: z12.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
|
|
643
666
|
'Event types to exclude even if selected via `events: ["*"]` or `eventCategories`.'
|
|
644
667
|
)
|
|
645
668
|
}).refine((v) => v.events.length > 0 || v.eventCategories.length > 0, {
|
|
646
669
|
message: "must select at least one event via `events` or `eventCategories`",
|
|
647
670
|
path: ["events"]
|
|
648
671
|
});
|
|
649
|
-
var WebhookSchema =
|
|
650
|
-
id:
|
|
672
|
+
var WebhookSchema = z12.object({
|
|
673
|
+
id: z12.string(),
|
|
651
674
|
environment: EnvironmentSchema.nullable().describe(
|
|
652
675
|
"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)."
|
|
653
676
|
),
|
|
654
|
-
url:
|
|
655
|
-
events:
|
|
656
|
-
eventCategories:
|
|
657
|
-
excludeEvents:
|
|
658
|
-
isWildcard:
|
|
659
|
-
secret:
|
|
677
|
+
url: z12.string(),
|
|
678
|
+
events: z12.array(WebhookEventTypeSchema),
|
|
679
|
+
eventCategories: z12.array(WebhookCategorySchema),
|
|
680
|
+
excludeEvents: z12.array(WebhookEventTypeSchema),
|
|
681
|
+
isWildcard: z12.boolean(),
|
|
682
|
+
secret: z12.string().describe(
|
|
660
683
|
"The signing secret, used to verify the `X-Klappay-Signature` header on every delivery. Returned in full only this once \u2014 store it now, it is not recoverable afterward. Header format: `t=<unix-seconds>,v1=<hex-encoded HMAC-SHA256>`. Compute the expected signature as `HMAC-SHA256(secret, \"${t}.${raw request body}\")` (hex-encoded) and compare it to `v1` using a constant-time comparison; as a replay-protection measure, also reject if `t` is too far from the current time \u2014 Klappay does not enforce or check any particular tolerance server-side, so the exact threshold is entirely the receiver's own policy call. An official SDK's `constructEvent()`/`verifySignature()` do this for you, defaulting to a 300-second tolerance, overridable via `constructEvent`'s `toleranceSeconds` option \u2014 see github.com/klappay for available SDKs."
|
|
661
684
|
),
|
|
662
|
-
createdAt:
|
|
685
|
+
createdAt: z12.string().datetime()
|
|
663
686
|
});
|
|
664
687
|
var WebhookListItemSchema = WebhookSchema.omit({ secret: true }).extend({
|
|
665
|
-
hint:
|
|
688
|
+
hint: z12.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
|
|
666
689
|
});
|
|
667
|
-
var WebhookPayloadSchema =
|
|
668
|
-
id:
|
|
690
|
+
var WebhookPayloadSchema = z12.object({
|
|
691
|
+
id: z12.string().describe(
|
|
669
692
|
"Unique id for this specific delivery \u2014 also sent as the `X-Klappay-Delivery` header."
|
|
670
693
|
),
|
|
671
694
|
event: WebhookEventTypeSchema,
|
|
672
|
-
createdAt:
|
|
673
|
-
data:
|
|
695
|
+
createdAt: z12.string().datetime(),
|
|
696
|
+
data: z12.unknown().describe(
|
|
674
697
|
"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."
|
|
675
698
|
)
|
|
676
699
|
});
|
|
677
|
-
var WebhookDeliveryStatusSchema =
|
|
678
|
-
var WebhookDeliverySchema =
|
|
679
|
-
id:
|
|
680
|
-
webhookId:
|
|
700
|
+
var WebhookDeliveryStatusSchema = z12.enum(["pending", "delivered", "failed"]);
|
|
701
|
+
var WebhookDeliverySchema = z12.object({
|
|
702
|
+
id: z12.string(),
|
|
703
|
+
webhookId: z12.string(),
|
|
681
704
|
event: WebhookEventTypeSchema,
|
|
682
705
|
status: WebhookDeliveryStatusSchema.describe(
|
|
683
706
|
"`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."
|
|
684
707
|
),
|
|
685
|
-
attempts:
|
|
686
|
-
responseCode:
|
|
708
|
+
attempts: z12.number(),
|
|
709
|
+
responseCode: z12.number().nullable().describe(
|
|
687
710
|
"HTTP status your endpoint returned on the most recent attempt. `null` if every attempt failed to connect at all."
|
|
688
711
|
),
|
|
689
|
-
nextRetryAt:
|
|
690
|
-
deliveredAt:
|
|
691
|
-
createdAt:
|
|
712
|
+
nextRetryAt: z12.string().datetime().nullable(),
|
|
713
|
+
deliveredAt: z12.string().datetime().nullable(),
|
|
714
|
+
createdAt: z12.string().datetime()
|
|
692
715
|
});
|
|
693
716
|
var ListWebhookDeliveriesSchema = PaginationQuerySchema;
|
|
694
717
|
var PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema);
|
|
695
718
|
|
|
696
719
|
// src/timeline.ts
|
|
697
|
-
import { z as
|
|
698
|
-
var TransactionSourceSchema =
|
|
720
|
+
import { z as z13 } from "zod";
|
|
721
|
+
var TransactionSourceSchema = z13.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
|
|
699
722
|
"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)."
|
|
700
723
|
);
|
|
701
|
-
var TimelineEventTypeSchema =
|
|
724
|
+
var TimelineEventTypeSchema = z13.enum([
|
|
702
725
|
"charge.created",
|
|
703
726
|
"charge.expired",
|
|
704
727
|
"transaction.detected",
|
|
@@ -709,11 +732,11 @@ var TimelineEventTypeSchema = z12.enum([
|
|
|
709
732
|
]).describe(
|
|
710
733
|
"`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)."
|
|
711
734
|
);
|
|
712
|
-
var TimelineEventSchema =
|
|
735
|
+
var TimelineEventSchema = z13.object({
|
|
713
736
|
type: TimelineEventTypeSchema,
|
|
714
|
-
at:
|
|
715
|
-
txHash:
|
|
716
|
-
amount:
|
|
737
|
+
at: z13.string().datetime(),
|
|
738
|
+
txHash: z13.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
|
|
739
|
+
amount: z13.number().optional().describe(
|
|
717
740
|
"Present for `transaction.detected` events only \u2014 the amount that specific transfer carried."
|
|
718
741
|
),
|
|
719
742
|
source: TransactionSourceSchema.optional().describe(
|
|
@@ -725,49 +748,49 @@ var TimelineEventSchema = z12.object({
|
|
|
725
748
|
network: NetworkSchema.optional().describe(
|
|
726
749
|
"Present for `transaction.detected` and `split.distributed` events \u2014 which network this specific transfer, or settlement, used."
|
|
727
750
|
),
|
|
728
|
-
causedTransition:
|
|
751
|
+
causedTransition: z13.boolean().optional().describe(
|
|
729
752
|
"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."
|
|
730
753
|
),
|
|
731
754
|
event: WebhookEventTypeSchema.optional().describe(
|
|
732
755
|
"Present for `webhook.*` events only \u2014 which event type this delivery was for."
|
|
733
756
|
),
|
|
734
|
-
responseCode:
|
|
757
|
+
responseCode: z13.number().nullable().optional().describe(
|
|
735
758
|
"Present for `webhook.*` events only \u2014 HTTP status your endpoint returned, or `null` if the request never connected."
|
|
736
759
|
),
|
|
737
|
-
attempts:
|
|
760
|
+
attempts: z13.number().optional().describe(
|
|
738
761
|
"Present for `webhook.*` events only \u2014 how many delivery attempts have been made so far."
|
|
739
762
|
)
|
|
740
763
|
});
|
|
741
764
|
|
|
742
765
|
// src/health.ts
|
|
743
|
-
import { z as
|
|
744
|
-
var HealthSchema =
|
|
745
|
-
status:
|
|
766
|
+
import { z as z14 } from "zod";
|
|
767
|
+
var HealthSchema = z14.object({
|
|
768
|
+
status: z14.enum(["ok", "error"]).describe(
|
|
746
769
|
"`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."
|
|
747
770
|
),
|
|
748
|
-
version:
|
|
749
|
-
timestamp:
|
|
750
|
-
db:
|
|
751
|
-
pendingWebhooks:
|
|
752
|
-
oldestPendingChargeAgeSeconds:
|
|
753
|
-
lastMoralisEventAgeSeconds:
|
|
771
|
+
version: z14.string(),
|
|
772
|
+
timestamp: z14.string().datetime(),
|
|
773
|
+
db: z14.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
|
|
774
|
+
pendingWebhooks: z14.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
|
|
775
|
+
oldestPendingChargeAgeSeconds: z14.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
|
|
776
|
+
lastMoralisEventAgeSeconds: z14.number().nullable().describe(
|
|
754
777
|
"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."
|
|
755
778
|
)
|
|
756
779
|
});
|
|
757
780
|
|
|
758
781
|
// src/sandbox.ts
|
|
759
|
-
import { z as
|
|
760
|
-
var SandboxTriggerSchema =
|
|
782
|
+
import { z as z15 } from "zod";
|
|
783
|
+
var SandboxTriggerSchema = z15.object({
|
|
761
784
|
event: TriggerableChargeEventSchema,
|
|
762
|
-
amount:
|
|
785
|
+
amount: z15.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
|
|
763
786
|
"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."
|
|
764
787
|
)
|
|
765
788
|
});
|
|
766
789
|
|
|
767
790
|
// src/capabilities.ts
|
|
768
|
-
import { z as
|
|
769
|
-
var CapabilitiesSchema =
|
|
770
|
-
acceptedPayments:
|
|
791
|
+
import { z as z16 } from "zod";
|
|
792
|
+
var CapabilitiesSchema = z16.object({
|
|
793
|
+
acceptedPayments: z16.array(AcceptedPaymentSchema).describe(
|
|
771
794
|
"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."
|
|
772
795
|
)
|
|
773
796
|
});
|
|
@@ -780,6 +803,7 @@ export {
|
|
|
780
803
|
CHARGE_EXPIRES_IN_MAX_SECONDS,
|
|
781
804
|
CHARGE_EXPIRES_IN_MIN_SECONDS,
|
|
782
805
|
CHARGE_SPLIT_RECIPIENTS_MAX,
|
|
806
|
+
CHECKOUT_PRODUCTS_MAX,
|
|
783
807
|
CapabilitiesSchema,
|
|
784
808
|
ChargeSchema,
|
|
785
809
|
ChargeStatusSchema,
|
|
@@ -787,6 +811,7 @@ export {
|
|
|
787
811
|
ChargesDateFieldSchema,
|
|
788
812
|
ChargesMetricFieldSchema,
|
|
789
813
|
ChargesQueryFieldSchema,
|
|
814
|
+
CheckoutProductSchema,
|
|
790
815
|
CreateChargeSchema,
|
|
791
816
|
CreateWebhookSchema,
|
|
792
817
|
DistributionsDateFieldSchema,
|
|
@@ -798,6 +823,7 @@ export {
|
|
|
798
823
|
ErrorPayloadSchema,
|
|
799
824
|
GetChargeQrCodeQuerySchema,
|
|
800
825
|
HealthSchema,
|
|
826
|
+
KlappayCheckoutMetadataSchema,
|
|
801
827
|
ListChargesSchema,
|
|
802
828
|
ListWebhookDeliveriesSchema,
|
|
803
829
|
ListenPendingDistributionsQuerySchema,
|
|
@@ -807,6 +833,7 @@ export {
|
|
|
807
833
|
METRICS_QUERY_MAX_GROUP_BY,
|
|
808
834
|
METRICS_QUERY_MAX_METRICS,
|
|
809
835
|
METRICS_QUERY_MAX_ROW_LIMIT,
|
|
836
|
+
MetadataWithKlappaySchema,
|
|
810
837
|
MetricsAggregationSchema,
|
|
811
838
|
MetricsDateGranularitySchema,
|
|
812
839
|
MetricsFilterOperatorSchema,
|