@blazium/sdk 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/LICENSE +22 -0
- package/README.md +306 -0
- package/dist/index.d.mts +333 -0
- package/dist/index.d.ts +333 -0
- package/dist/index.js +530 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +503 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +67 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import axios from 'axios';
|
|
3
|
+
import { createHmac, timingSafeEqual } from 'crypto';
|
|
4
|
+
|
|
5
|
+
// src/types.ts
|
|
6
|
+
var BlaziumChain = /* @__PURE__ */ ((BlaziumChain3) => {
|
|
7
|
+
BlaziumChain3["SOL"] = "SOL";
|
|
8
|
+
BlaziumChain3["TON"] = "TON";
|
|
9
|
+
BlaziumChain3["BTC"] = "BTC";
|
|
10
|
+
return BlaziumChain3;
|
|
11
|
+
})(BlaziumChain || {});
|
|
12
|
+
var BlaziumFiat = /* @__PURE__ */ ((BlaziumFiat2) => {
|
|
13
|
+
BlaziumFiat2["USD"] = "USD";
|
|
14
|
+
BlaziumFiat2["EUR"] = "EUR";
|
|
15
|
+
BlaziumFiat2["TRY"] = "TRY";
|
|
16
|
+
return BlaziumFiat2;
|
|
17
|
+
})(BlaziumFiat || {});
|
|
18
|
+
var PaymentStatus = /* @__PURE__ */ ((PaymentStatus2) => {
|
|
19
|
+
PaymentStatus2["CREATED"] = "CREATED";
|
|
20
|
+
PaymentStatus2["PENDING"] = "PENDING";
|
|
21
|
+
PaymentStatus2["PARTIALLY_PAID"] = "PARTIALLY_PAID";
|
|
22
|
+
PaymentStatus2["CONFIRMED"] = "CONFIRMED";
|
|
23
|
+
PaymentStatus2["FAILED"] = "FAILED";
|
|
24
|
+
PaymentStatus2["EXPIRED"] = "EXPIRED";
|
|
25
|
+
PaymentStatus2["CANCELLED"] = "CANCELLED";
|
|
26
|
+
return PaymentStatus2;
|
|
27
|
+
})(PaymentStatus || {});
|
|
28
|
+
var BlaziumEnvironment = /* @__PURE__ */ ((BlaziumEnvironment2) => {
|
|
29
|
+
BlaziumEnvironment2["PRODUCTION"] = "production";
|
|
30
|
+
BlaziumEnvironment2["SANDBOX"] = "sandbox";
|
|
31
|
+
return BlaziumEnvironment2;
|
|
32
|
+
})(BlaziumEnvironment || {});
|
|
33
|
+
var WithdrawalStatus = /* @__PURE__ */ ((WithdrawalStatus2) => {
|
|
34
|
+
WithdrawalStatus2["PENDING"] = "PENDING";
|
|
35
|
+
WithdrawalStatus2["PROCESSING"] = "PROCESSING";
|
|
36
|
+
WithdrawalStatus2["COMPLETED"] = "COMPLETED";
|
|
37
|
+
WithdrawalStatus2["FAILED"] = "FAILED";
|
|
38
|
+
WithdrawalStatus2["CANCELLED"] = "CANCELLED";
|
|
39
|
+
return WithdrawalStatus2;
|
|
40
|
+
})(WithdrawalStatus || {});
|
|
41
|
+
var BlaziumConfigSchema = z.object({
|
|
42
|
+
apiKey: z.string().min(1, "API Key is required"),
|
|
43
|
+
baseUrl: z.string().url().optional().default("https://api.blaziumpay.com/api/v1"),
|
|
44
|
+
timeout: z.number().min(0).optional().default(15e3),
|
|
45
|
+
environment: z.nativeEnum(BlaziumEnvironment).optional().default("production" /* PRODUCTION */),
|
|
46
|
+
webhookSecret: z.string().optional()
|
|
47
|
+
});
|
|
48
|
+
var CreatePaymentSchema = z.object({
|
|
49
|
+
amount: z.number().positive("Amount must be positive"),
|
|
50
|
+
currency: z.string().min(2).max(5).toUpperCase(),
|
|
51
|
+
description: z.string().max(500).optional(),
|
|
52
|
+
metadata: z.record(z.unknown()).optional(),
|
|
53
|
+
redirectUrl: z.string().url().optional(),
|
|
54
|
+
cancelUrl: z.string().url().optional(),
|
|
55
|
+
expiresIn: z.number().min(60).max(86400).optional(),
|
|
56
|
+
// Reward metadata (optional - for developer reference only)
|
|
57
|
+
// Note: BlaziumPay does NOT automatically grant rewards.
|
|
58
|
+
rewardAmount: z.number().optional(),
|
|
59
|
+
rewardCurrency: z.string().optional(),
|
|
60
|
+
rewardData: z.record(z.unknown()).optional()
|
|
61
|
+
});
|
|
62
|
+
var WebhookEventType = /* @__PURE__ */ ((WebhookEventType3) => {
|
|
63
|
+
WebhookEventType3["PAYMENT_CREATED"] = "payment.created";
|
|
64
|
+
WebhookEventType3["PAYMENT_PENDING"] = "payment.pending";
|
|
65
|
+
WebhookEventType3["PAYMENT_CONFIRMED"] = "payment.confirmed";
|
|
66
|
+
WebhookEventType3["PAYMENT_FAILED"] = "payment.failed";
|
|
67
|
+
WebhookEventType3["PAYMENT_EXPIRED"] = "payment.expired";
|
|
68
|
+
WebhookEventType3["PAYMENT_PARTIALLY_PAID"] = "payment.partially_paid";
|
|
69
|
+
return WebhookEventType3;
|
|
70
|
+
})(WebhookEventType || {});
|
|
71
|
+
|
|
72
|
+
// src/errors.ts
|
|
73
|
+
var BlaziumError = class extends Error {
|
|
74
|
+
constructor(message, code = "UNKNOWN_ERROR", details) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.name = this.constructor.name;
|
|
77
|
+
this.code = code;
|
|
78
|
+
this.details = details;
|
|
79
|
+
if (Error.captureStackTrace) {
|
|
80
|
+
Error.captureStackTrace(this, this.constructor);
|
|
81
|
+
}
|
|
82
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Convert error to JSON format
|
|
86
|
+
*/
|
|
87
|
+
toJSON() {
|
|
88
|
+
return {
|
|
89
|
+
name: this.name,
|
|
90
|
+
message: this.message,
|
|
91
|
+
code: this.code,
|
|
92
|
+
details: this.details,
|
|
93
|
+
stack: this.stack
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
var AuthenticationError = class extends BlaziumError {
|
|
98
|
+
constructor(message = "Invalid API Key provided") {
|
|
99
|
+
super(message, "AUTHENTICATION_ERROR");
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
var ValidationError = class extends BlaziumError {
|
|
103
|
+
constructor(message, errors) {
|
|
104
|
+
super(message, "VALIDATION_ERROR", errors);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
var NetworkError = class extends BlaziumError {
|
|
108
|
+
constructor(message = "Network request failed") {
|
|
109
|
+
super(message, "NETWORK_ERROR");
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
var RateLimitError = class extends BlaziumError {
|
|
113
|
+
constructor(message = "Too many requests", retryAfter) {
|
|
114
|
+
super(message, "RATE_LIMIT_ERROR");
|
|
115
|
+
this.retryAfter = retryAfter;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var TimeoutError = class extends BlaziumError {
|
|
119
|
+
constructor(message = "Operation timed out", code = "TIMEOUT_ERROR") {
|
|
120
|
+
super(message, code);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
var APIError = class extends BlaziumError {
|
|
124
|
+
constructor(message, statusCode, code = "API_ERROR") {
|
|
125
|
+
super(message, code);
|
|
126
|
+
this.statusCode = statusCode;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
var PaymentError = class extends BlaziumError {
|
|
130
|
+
constructor(message, code = "PAYMENT_ERROR", details) {
|
|
131
|
+
super(message, code, details);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
var PaymentNotFoundError = class extends PaymentError {
|
|
135
|
+
constructor(paymentId) {
|
|
136
|
+
super(`Payment with ID ${paymentId} not found`, "PAYMENT_NOT_FOUND", { paymentId });
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
var PaymentExpiredError = class extends PaymentError {
|
|
140
|
+
constructor(paymentId) {
|
|
141
|
+
super(`Payment ${paymentId} has expired`, "PAYMENT_EXPIRED", { paymentId });
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
var InsufficientPaymentError = class extends PaymentError {
|
|
145
|
+
constructor(received, expected) {
|
|
146
|
+
super(
|
|
147
|
+
`Insufficient payment: received ${received}, expected ${expected}`,
|
|
148
|
+
"INSUFFICIENT_PAYMENT",
|
|
149
|
+
{ received, expected }
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
var WebhookError = class extends BlaziumError {
|
|
154
|
+
constructor(message, code = "WEBHOOK_ERROR", details) {
|
|
155
|
+
super(message, code, details);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
var InvalidSignatureError = class extends WebhookError {
|
|
159
|
+
constructor() {
|
|
160
|
+
super("Webhook signature verification failed", "INVALID_SIGNATURE");
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
var BlaziumPayClient = class {
|
|
164
|
+
constructor(config) {
|
|
165
|
+
const validation = BlaziumConfigSchema.safeParse(config);
|
|
166
|
+
if (!validation.success) {
|
|
167
|
+
throw new ValidationError("Invalid configuration", validation.error.errors);
|
|
168
|
+
}
|
|
169
|
+
this.config = validation.data;
|
|
170
|
+
this.client = axios.create({
|
|
171
|
+
baseURL: this.config.baseUrl,
|
|
172
|
+
timeout: this.config.timeout,
|
|
173
|
+
headers: {
|
|
174
|
+
"Authorization": `Bearer ${this.config.apiKey}`,
|
|
175
|
+
"Content-Type": "application/json",
|
|
176
|
+
"User-Agent": `BlaziumPay-SDK/1.0.0 (${this.config.environment})`,
|
|
177
|
+
"X-SDK-Version": "1.0.0"
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
this.client.interceptors.request.use((config2) => {
|
|
181
|
+
config2._retryCount = config2._retryCount || 0;
|
|
182
|
+
return config2;
|
|
183
|
+
});
|
|
184
|
+
this.client.interceptors.response.use(
|
|
185
|
+
(response) => response,
|
|
186
|
+
async (error) => {
|
|
187
|
+
const config2 = error.config;
|
|
188
|
+
const retryCount = config2?._retryCount || 0;
|
|
189
|
+
const maxRetries = 3;
|
|
190
|
+
const retryableStatuses = [429, 500, 502, 503, 504];
|
|
191
|
+
const retryableCodes = ["ECONNABORTED", "ETIMEDOUT", "ENOTFOUND", "ECONNRESET"];
|
|
192
|
+
if (config2 && retryCount < maxRetries && (error.response && retryableStatuses.includes(error.response.status) || error.code && retryableCodes.includes(error.code) || !error.response && error.request)) {
|
|
193
|
+
config2._retryCount = retryCount + 1;
|
|
194
|
+
const delay = 300 * Math.pow(2, retryCount);
|
|
195
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
196
|
+
return this.client.request(config2);
|
|
197
|
+
}
|
|
198
|
+
if (error.response) {
|
|
199
|
+
const status = error.response.status;
|
|
200
|
+
const data = error.response.data;
|
|
201
|
+
const message = data?.error || error.message;
|
|
202
|
+
if (status === 401 || status === 403) {
|
|
203
|
+
throw new AuthenticationError(message);
|
|
204
|
+
}
|
|
205
|
+
if (status === 400 || status === 422) {
|
|
206
|
+
throw new ValidationError(message, data?.details);
|
|
207
|
+
}
|
|
208
|
+
if (status === 404) {
|
|
209
|
+
throw new APIError(message, 404, "NOT_FOUND");
|
|
210
|
+
}
|
|
211
|
+
if (status === 429) {
|
|
212
|
+
throw new RateLimitError(message);
|
|
213
|
+
}
|
|
214
|
+
if (status >= 500) {
|
|
215
|
+
throw new APIError(message, status, "SERVER_ERROR");
|
|
216
|
+
}
|
|
217
|
+
throw new APIError(message, status);
|
|
218
|
+
} else if (error.code === "ECONNABORTED") {
|
|
219
|
+
throw new TimeoutError("Request timeout");
|
|
220
|
+
} else if (error.request) {
|
|
221
|
+
throw new NetworkError(error.message);
|
|
222
|
+
} else {
|
|
223
|
+
throw new BlaziumError(error.message);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Create a new payment with idempotency support.
|
|
230
|
+
*
|
|
231
|
+
* Note: rewardAmount and rewardCurrency are optional metadata fields for developer reference.
|
|
232
|
+
* BlaziumPay does NOT automatically grant rewards - developers must implement their own
|
|
233
|
+
* logic in webhook handlers to grant premium features, add currency, or perform other actions.
|
|
234
|
+
*/
|
|
235
|
+
async createPayment(params, options) {
|
|
236
|
+
const validation = CreatePaymentSchema.safeParse(params);
|
|
237
|
+
if (!validation.success) {
|
|
238
|
+
throw new ValidationError("Invalid payment parameters", validation.error.errors);
|
|
239
|
+
}
|
|
240
|
+
const headers = {};
|
|
241
|
+
if (options?.idempotencyKey) {
|
|
242
|
+
headers["Idempotency-Key"] = options.idempotencyKey;
|
|
243
|
+
}
|
|
244
|
+
const response = await this.client.post("/payments", validation.data, { headers });
|
|
245
|
+
return this.normalizePayment(response.data);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Get payment details
|
|
249
|
+
*/
|
|
250
|
+
async getPayment(paymentId) {
|
|
251
|
+
if (!paymentId) throw new ValidationError("Payment ID is required");
|
|
252
|
+
const response = await this.client.get(`/payments/${paymentId}`);
|
|
253
|
+
return this.normalizePayment(response.data);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* List payments with filters
|
|
257
|
+
*/
|
|
258
|
+
async listPayments(params) {
|
|
259
|
+
const response = await this.client.get("/payments", {
|
|
260
|
+
params
|
|
261
|
+
});
|
|
262
|
+
return {
|
|
263
|
+
...response.data,
|
|
264
|
+
data: response.data.data.map((p) => this.normalizePayment(p))
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Cancel a payment
|
|
269
|
+
*/
|
|
270
|
+
async cancelPayment(paymentId) {
|
|
271
|
+
if (!paymentId) throw new ValidationError("Payment ID is required");
|
|
272
|
+
const response = await this.client.post(`/payments/${paymentId}/cancel`);
|
|
273
|
+
return this.normalizePayment(response.data);
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Get payment statistics
|
|
277
|
+
*/
|
|
278
|
+
async getStats() {
|
|
279
|
+
const response = await this.client.get("/payments/stats");
|
|
280
|
+
return response.data;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Get merchant balance for a specific chain
|
|
284
|
+
*/
|
|
285
|
+
async getBalance(chain) {
|
|
286
|
+
if (!chain) throw new ValidationError("Chain is required");
|
|
287
|
+
const response = await this.client.get(`/balance`, {
|
|
288
|
+
params: { chain: chain.toUpperCase() }
|
|
289
|
+
});
|
|
290
|
+
return response.data;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Request withdrawal
|
|
294
|
+
*/
|
|
295
|
+
async requestWithdrawal(request) {
|
|
296
|
+
if (!request.chain) throw new ValidationError("Chain is required");
|
|
297
|
+
if (!request.amount || request.amount <= 0) throw new ValidationError("Amount must be positive");
|
|
298
|
+
if (!request.destinationAddress) throw new ValidationError("Destination address is required");
|
|
299
|
+
const response = await this.client.post("/withdrawals", {
|
|
300
|
+
chain: request.chain.toUpperCase(),
|
|
301
|
+
amount: request.amount,
|
|
302
|
+
destinationAddress: request.destinationAddress
|
|
303
|
+
});
|
|
304
|
+
return response.data;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* List withdrawal history
|
|
308
|
+
*/
|
|
309
|
+
async listWithdrawals() {
|
|
310
|
+
const response = await this.client.get("/withdrawals");
|
|
311
|
+
return response.data.data;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Get specific withdrawal status
|
|
315
|
+
*/
|
|
316
|
+
async getWithdrawal(withdrawalId) {
|
|
317
|
+
if (!withdrawalId) throw new ValidationError("Withdrawal ID is required");
|
|
318
|
+
const response = await this.client.get(`/withdrawals/${withdrawalId}`);
|
|
319
|
+
return response.data;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Wait for a payment to be confirmed (Long Polling helper)
|
|
323
|
+
*/
|
|
324
|
+
async waitForPayment(paymentId, timeoutMs = 3e5, pollIntervalMs = 3e3) {
|
|
325
|
+
const start = Date.now();
|
|
326
|
+
while (Date.now() - start < timeoutMs) {
|
|
327
|
+
try {
|
|
328
|
+
const payment = await this.getPayment(paymentId);
|
|
329
|
+
if (payment.status === "CONFIRMED" /* CONFIRMED */) {
|
|
330
|
+
return payment;
|
|
331
|
+
}
|
|
332
|
+
const finalStatuses = [
|
|
333
|
+
"FAILED" /* FAILED */,
|
|
334
|
+
"EXPIRED" /* EXPIRED */,
|
|
335
|
+
"CANCELLED" /* CANCELLED */
|
|
336
|
+
];
|
|
337
|
+
if (finalStatuses.includes(payment.status)) {
|
|
338
|
+
throw new BlaziumError(
|
|
339
|
+
`Payment ended with status: ${payment.status}`,
|
|
340
|
+
"PAYMENT_NOT_CONFIRMED"
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
await this.sleep(pollIntervalMs);
|
|
344
|
+
} catch (e) {
|
|
345
|
+
if (e instanceof BlaziumError && e.code === "PAYMENT_NOT_CONFIRMED") {
|
|
346
|
+
throw e;
|
|
347
|
+
}
|
|
348
|
+
if (!(e instanceof NetworkError || e instanceof TimeoutError)) {
|
|
349
|
+
throw e;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
throw new TimeoutError(
|
|
354
|
+
`Payment confirmation timed out after ${timeoutMs}ms`,
|
|
355
|
+
"PAYMENT_TIMEOUT"
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Verify webhook signature
|
|
360
|
+
*
|
|
361
|
+
* Note: Only verified webhooks receive events. Unverified webhooks will not receive
|
|
362
|
+
* any webhook events from BlaziumPay. You must verify your webhook endpoint in the
|
|
363
|
+
* dashboard before it will receive events and require signature verification.
|
|
364
|
+
*/
|
|
365
|
+
verifyWebhookSignature(payload, signature) {
|
|
366
|
+
if (!this.config.webhookSecret) {
|
|
367
|
+
throw new ValidationError(
|
|
368
|
+
"Webhook secret not configured. Set webhookSecret in config. Note: Webhooks must be verified in the dashboard before they receive events. Only verified webhooks are sent events by BlaziumPay.",
|
|
369
|
+
"WEBHOOK_SECRET_MISSING"
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
const expectedSignature = createHmac("sha256", this.config.webhookSecret).update(payload).digest("hex");
|
|
374
|
+
const expectedBuffer = Buffer.from(expectedSignature, "hex");
|
|
375
|
+
const actualBuffer = Buffer.from(signature.replace("sha256=", ""), "hex");
|
|
376
|
+
return expectedBuffer.length === actualBuffer.length && timingSafeEqual(expectedBuffer, actualBuffer);
|
|
377
|
+
} catch {
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Parse and verify webhook payload
|
|
383
|
+
*
|
|
384
|
+
* @param rawPayload - Raw JSON string of webhook payload
|
|
385
|
+
* @param signature - Signature from HTTP header 'X-Blazium-Signature'
|
|
386
|
+
* @returns Parsed and verified webhook payload
|
|
387
|
+
*
|
|
388
|
+
* Note: Signature is verified from HTTP header, not from payload.
|
|
389
|
+
* Only verified webhooks receive events. Unverified webhooks will not receive
|
|
390
|
+
* any webhook events from BlaziumPay.
|
|
391
|
+
*/
|
|
392
|
+
parseWebhook(rawPayload, signature) {
|
|
393
|
+
if (!this.verifyWebhookSignature(rawPayload, signature)) {
|
|
394
|
+
throw new ValidationError(
|
|
395
|
+
"Invalid webhook signature. This webhook may be from an unverified endpoint. Only verified webhooks receive events from BlaziumPay.",
|
|
396
|
+
"INVALID_SIGNATURE"
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
try {
|
|
400
|
+
const payload = JSON.parse(rawPayload);
|
|
401
|
+
return {
|
|
402
|
+
id: payload.id,
|
|
403
|
+
webhook_id: payload.webhook_id,
|
|
404
|
+
event: payload.event,
|
|
405
|
+
payment_id: payload.payment_id,
|
|
406
|
+
payment: this.normalizePayment(payload.payment),
|
|
407
|
+
timestamp: payload.timestamp,
|
|
408
|
+
createdAt: payload.createdAt
|
|
409
|
+
};
|
|
410
|
+
} catch {
|
|
411
|
+
throw new ValidationError(
|
|
412
|
+
"Invalid webhook payload format",
|
|
413
|
+
"INVALID_PAYLOAD"
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
// --- HELPERS ---
|
|
418
|
+
normalizePayment(payment) {
|
|
419
|
+
const metadata = payment.metadata || {};
|
|
420
|
+
const partialPayment = metadata.partial_payment;
|
|
421
|
+
return {
|
|
422
|
+
id: payment.id,
|
|
423
|
+
status: payment.status,
|
|
424
|
+
amount: typeof payment.amount === "string" ? Number(payment.amount) : payment.amount,
|
|
425
|
+
currency: payment.currency,
|
|
426
|
+
checkoutUrl: payment.checkoutUrl,
|
|
427
|
+
createdAt: payment.createdAt,
|
|
428
|
+
expiresAt: payment.expiresAt,
|
|
429
|
+
description: payment.description,
|
|
430
|
+
metadata: payment.metadata,
|
|
431
|
+
updatedAt: payment.updatedAt,
|
|
432
|
+
payCurrency: payment.payCurrency,
|
|
433
|
+
payAmount: payment.payAmount ? Number(payment.payAmount) : void 0,
|
|
434
|
+
payAddress: payment.payAddress,
|
|
435
|
+
txHash: payment.txHash,
|
|
436
|
+
networkFee: payment.networkFee ? Number(payment.networkFee) : void 0,
|
|
437
|
+
blockHeight: payment.blockHeight,
|
|
438
|
+
confirmedAt: payment.confirmedAt,
|
|
439
|
+
addressIndex: payment.addressIndex,
|
|
440
|
+
quotedRate: payment.quotedRate ? Number(payment.quotedRate) : void 0,
|
|
441
|
+
quoteExpiresAt: payment.quoteExpiresAt,
|
|
442
|
+
rewardAmount: payment.rewardAmount ? Number(payment.rewardAmount) : void 0,
|
|
443
|
+
rewardCurrency: payment.rewardCurrency,
|
|
444
|
+
rewardData: payment.rewardData,
|
|
445
|
+
rewardDelivered: payment.rewardDelivered,
|
|
446
|
+
partialPayment: partialPayment ? {
|
|
447
|
+
amount: Number(partialPayment.amount),
|
|
448
|
+
txHash: partialPayment.txHash,
|
|
449
|
+
detectedAt: partialPayment.detectedAt,
|
|
450
|
+
expectedAmount: Number(partialPayment.expectedAmount ?? payment.payAmount ?? 0)
|
|
451
|
+
} : void 0
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
sleep(ms) {
|
|
455
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
456
|
+
}
|
|
457
|
+
isFinalStatus(status) {
|
|
458
|
+
return [
|
|
459
|
+
"CONFIRMED" /* CONFIRMED */,
|
|
460
|
+
"FAILED" /* FAILED */,
|
|
461
|
+
"EXPIRED" /* EXPIRED */,
|
|
462
|
+
"CANCELLED" /* CANCELLED */
|
|
463
|
+
].includes(status);
|
|
464
|
+
}
|
|
465
|
+
isFinal(payment) {
|
|
466
|
+
return this.isFinalStatus(payment.status);
|
|
467
|
+
}
|
|
468
|
+
isPaid(payment) {
|
|
469
|
+
return payment.status === "CONFIRMED" /* CONFIRMED */;
|
|
470
|
+
}
|
|
471
|
+
isPartiallyPaid(payment) {
|
|
472
|
+
return payment.status === "PARTIALLY_PAID" /* PARTIALLY_PAID */;
|
|
473
|
+
}
|
|
474
|
+
isExpired(payment) {
|
|
475
|
+
return payment.status === "EXPIRED" /* EXPIRED */;
|
|
476
|
+
}
|
|
477
|
+
getPaymentProgress(payment) {
|
|
478
|
+
if (!payment.payAmount || payment.amount <= 0) {
|
|
479
|
+
return 0;
|
|
480
|
+
}
|
|
481
|
+
if (payment.partialPayment) {
|
|
482
|
+
const progress = payment.partialPayment.amount / payment.payAmount * 100;
|
|
483
|
+
return Math.min(100, Math.max(0, progress));
|
|
484
|
+
}
|
|
485
|
+
if (payment.status === "CONFIRMED" /* CONFIRMED */) {
|
|
486
|
+
return 100;
|
|
487
|
+
}
|
|
488
|
+
return 0;
|
|
489
|
+
}
|
|
490
|
+
formatAmount(amount, currency) {
|
|
491
|
+
const decimals = {
|
|
492
|
+
"TON": 4,
|
|
493
|
+
"SOL": 4,
|
|
494
|
+
"BTC": 8
|
|
495
|
+
};
|
|
496
|
+
const decimalPlaces = decimals[currency.toUpperCase()] || 4;
|
|
497
|
+
return `${amount.toFixed(decimalPlaces)} ${currency.toUpperCase()}`;
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
export { APIError, AuthenticationError, BlaziumChain, BlaziumConfigSchema, BlaziumEnvironment, BlaziumError, BlaziumFiat, BlaziumPayClient, CreatePaymentSchema, InsufficientPaymentError, InvalidSignatureError, NetworkError, PaymentError, PaymentExpiredError, PaymentNotFoundError, PaymentStatus, RateLimitError, TimeoutError, ValidationError, WebhookError, WebhookEventType, WithdrawalStatus };
|
|
502
|
+
//# sourceMappingURL=index.mjs.map
|
|
503
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/errors.ts","../src/client.ts"],"names":["BlaziumChain","BlaziumFiat","PaymentStatus","BlaziumEnvironment","WithdrawalStatus","WebhookEventType","config"],"mappings":";;;;;AAKO,IAAK,YAAA,qBAAAA,aAAAA,KAAL;AACL,EAAAA,cAAA,KAAA,CAAA,GAAM,KAAA;AACN,EAAAA,cAAA,KAAA,CAAA,GAAM,KAAA;AACN,EAAAA,cAAA,KAAA,CAAA,GAAM,KAAA;AAHI,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAML,IAAK,WAAA,qBAAAC,YAAAA,KAAL;AACL,EAAAA,aAAA,KAAA,CAAA,GAAM,KAAA;AACN,EAAAA,aAAA,KAAA,CAAA,GAAM,KAAA;AACN,EAAAA,aAAA,KAAA,CAAA,GAAM,KAAA;AAHI,EAAA,OAAAA,YAAAA;AAAA,CAAA,EAAA,WAAA,IAAA,EAAA;AAML,IAAK,aAAA,qBAAAC,cAAAA,KAAL;AACL,EAAAA,eAAA,SAAA,CAAA,GAAU,SAAA;AACV,EAAAA,eAAA,SAAA,CAAA,GAAU,SAAA;AACV,EAAAA,eAAA,gBAAA,CAAA,GAAiB,gBAAA;AACjB,EAAAA,eAAA,WAAA,CAAA,GAAY,WAAA;AACZ,EAAAA,eAAA,QAAA,CAAA,GAAS,QAAA;AACT,EAAAA,eAAA,SAAA,CAAA,GAAU,SAAA;AACV,EAAAA,eAAA,WAAA,CAAA,GAAY,WAAA;AAPF,EAAA,OAAAA,cAAAA;AAA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,GAAA,EAAK,KAAK,GAAA,CAAI,CAAA,EAAG,QAAQ,CAAC,CAAA;AAAA,IAC5C;AAGA,IAAA,IAAI,QAAQ,MAAA,KAAA,WAAA,kBAAoC;AAC9C,MAAA,OAAO,GAAA;AAAA,IACT;AAIA,IAAA,OAAO,CAAA;AAAA,EACT;AAAA,EAEA,YAAA,CAAa,QAAgB,QAAA,EAA0B;AAErD,IAAA,MAAM,QAAA,GAAmC;AAAA,MACvC,KAAA,EAAO,CAAA;AAAA,MACP,KAAA,EAAO,CAAA;AAAA,MACP,KAAA,EAAO;AAAA,KACT;AAEA,IAAA,MAAM,aAAA,GAAgB,QAAA,CAAS,QAAA,CAAS,WAAA,EAAa,CAAA,IAAK,CAAA;AAC1D,IAAA,OAAO,CAAA,EAAG,OAAO,OAAA,CAAQ,aAAa,CAAC,CAAA,CAAA,EAAI,QAAA,CAAS,aAAa,CAAA,CAAA;AAAA,EACnE;AACF","file":"index.mjs","sourcesContent":["// sdk > src > types.ts\n\nimport { z } from 'zod';\n\n// Enums\nexport enum BlaziumChain {\n SOL = 'SOL',\n TON = 'TON',\n BTC = 'BTC',\n}\n\nexport enum BlaziumFiat {\n USD = 'USD',\n EUR = 'EUR',\n TRY = 'TRY',\n}\n\nexport enum PaymentStatus {\n CREATED = 'CREATED',\n PENDING = 'PENDING',\n PARTIALLY_PAID = 'PARTIALLY_PAID',\n CONFIRMED = 'CONFIRMED',\n FAILED = 'FAILED',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n}\n\nexport enum BlaziumEnvironment {\n PRODUCTION = 'production',\n SANDBOX = 'sandbox',\n}\n\nexport enum WithdrawalStatus {\n PENDING = 'PENDING',\n PROCESSING = 'PROCESSING',\n COMPLETED = 'COMPLETED',\n FAILED = 'FAILED',\n CANCELLED = 'CANCELLED',\n}\n\n// Configuration\nexport const BlaziumConfigSchema = z.object({\n apiKey: z.string().min(1, \"API Key is required\"),\n baseUrl: z.string().url().optional().default(\"https://api.blaziumpay.com/api/v1\"),\n timeout: z.number().min(0).optional().default(15000),\n environment: z.nativeEnum(BlaziumEnvironment).optional().default(BlaziumEnvironment.PRODUCTION),\n webhookSecret: z.string().optional(),\n});\n\nexport type BlaziumConfig = z.input<typeof BlaziumConfigSchema>;\nexport type BlaziumConfigInternal = z.output<typeof BlaziumConfigSchema>;\n\nexport interface Payment {\n id: string;\n status: PaymentStatus;\n amount: number;\n currency: string;\n checkoutUrl: string;\n createdAt: string;\n expiresAt: string;\n \n description?: string;\n metadata?: Record<string, unknown>;\n updatedAt?: string;\n \n payCurrency?: BlaziumChain;\n payAmount?: number;\n payAddress?: string;\n txHash?: string;\n networkFee?: number;\n blockHeight?: string;\n confirmedAt?: string;\n addressIndex?: number;\n \n // Locked exchange rate\n quotedRate?: number;\n quoteExpiresAt?: string;\n \n // Reward metadata (optional - for developer reference only)\n // Note: BlaziumPay does NOT automatically grant rewards.\n // Developers must implement their own logic in webhook handlers.\n rewardAmount?: number;\n rewardCurrency?: string;\n rewardData?: Record<string, unknown>;\n rewardDelivered?: boolean; // Flag from API indicating if developer has marked reward as delivered\n \n partialPayment?: {\n amount: number;\n txHash: string;\n detectedAt: string;\n expectedAmount: number;\n };\n}\n\nexport const CreatePaymentSchema = z.object({\n amount: z.number().positive(\"Amount must be positive\"),\n currency: z.string().min(2).max(5).toUpperCase(),\n description: z.string().max(500).optional(),\n metadata: z.record(z.unknown()).optional(),\n redirectUrl: z.string().url().optional(),\n cancelUrl: z.string().url().optional(),\n expiresIn: z.number().min(60).max(86400).optional(),\n // Reward metadata (optional - for developer reference only)\n // Note: BlaziumPay does NOT automatically grant rewards.\n rewardAmount: z.number().optional(),\n rewardCurrency: z.string().optional(),\n rewardData: z.record(z.unknown()).optional(),\n});\n\nexport type CreatePaymentParams = z.infer<typeof CreatePaymentSchema>;\n\nexport interface CreatePaymentOptions {\n idempotencyKey?: string;\n}\n\nexport enum WebhookEventType {\n PAYMENT_CREATED = 'payment.created',\n PAYMENT_PENDING = 'payment.pending',\n PAYMENT_CONFIRMED = 'payment.confirmed',\n PAYMENT_FAILED = 'payment.failed',\n PAYMENT_EXPIRED = 'payment.expired',\n PAYMENT_PARTIALLY_PAID = 'payment.partially_paid',\n}\n\nexport interface WebhookPayload {\n id: string; // Webhook delivery ID\n webhook_id: string; // Unique webhook ID for idempotency checks\n event: WebhookEventType;\n payment_id: string; // Payment ID (convenience field)\n payment: Payment;\n timestamp: string;\n createdAt: string;\n // Note: signature is in HTTP header 'X-Blazium-Signature', not in payload\n}\n\nexport interface PaymentStats {\n total: number;\n confirmed: number;\n pending: number;\n failed: number;\n totalVolume: number;\n currency: string;\n}\n\nexport interface PaginatedResponse<T> {\n data: T[];\n pagination: {\n page: number;\n pageSize: number;\n totalPages: number;\n totalItems: number;\n };\n}\n\nexport interface ListPaymentsParams {\n status?: PaymentStatus;\n currency?: string;\n page?: number;\n pageSize?: number;\n startDate?: string;\n endDate?: string;\n}\n\nexport interface MerchantBalance {\n chain: string;\n totalEarned: string;\n availableBalance: string;\n pendingBalance: string;\n totalWithdrawn: string;\n holdAmount: string;\n settlementPeriodDays: number;\n}\n\nexport interface Withdrawal {\n id: string;\n status: WithdrawalStatus;\n amount: string;\n chain: string;\n destinationAddress: string;\n txHash?: string;\n networkFee?: string;\n finalAmount?: string;\n errorMessage?: string;\n requestedAt: string;\n completedAt?: string;\n}\n\nexport interface WithdrawalRequest {\n chain: string;\n amount: number;\n destinationAddress: string;\n}","// sdk > src > errors.ts\n\nexport class BlaziumError extends Error {\n public code: string;\n public details?: unknown;\n\n constructor(message: string, code: string = 'UNKNOWN_ERROR', details?: unknown) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.details = details;\n \n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n \n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Convert error to JSON format\n */\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n details: this.details,\n stack: this.stack\n };\n }\n}\n\nexport class AuthenticationError extends BlaziumError {\n constructor(message: string = 'Invalid API Key provided') {\n super(message, 'AUTHENTICATION_ERROR');\n }\n}\n\nexport class ValidationError extends BlaziumError {\n constructor(message: string, errors?: unknown) {\n super(message, 'VALIDATION_ERROR', errors);\n }\n}\n\nexport class NetworkError extends BlaziumError {\n constructor(message: string = 'Network request failed') {\n super(message, 'NETWORK_ERROR');\n }\n}\n\nexport class RateLimitError extends BlaziumError {\n public retryAfter?: number;\n\n constructor(message: string = 'Too many requests', retryAfter?: number) {\n super(message, 'RATE_LIMIT_ERROR');\n this.retryAfter = retryAfter;\n }\n}\n\nexport class TimeoutError extends BlaziumError {\n constructor(message: string = 'Operation timed out', code: string = 'TIMEOUT_ERROR') {\n super(message, code);\n }\n}\n\nexport class APIError extends BlaziumError {\n public statusCode: number;\n\n constructor(message: string, statusCode: number, code: string = 'API_ERROR') {\n super(message, code);\n this.statusCode = statusCode;\n }\n}\n\n/**\n * ✅ NEW: Payment specific errors\n */\nexport class PaymentError extends BlaziumError {\n constructor(message: string, code: string = 'PAYMENT_ERROR', details?: unknown) {\n super(message, code, details);\n }\n}\n\nexport class PaymentNotFoundError extends PaymentError {\n constructor(paymentId: string) {\n super(`Payment with ID ${paymentId} not found`, 'PAYMENT_NOT_FOUND', { paymentId });\n }\n}\n\nexport class PaymentExpiredError extends PaymentError {\n constructor(paymentId: string) {\n super(`Payment ${paymentId} has expired`, 'PAYMENT_EXPIRED', { paymentId });\n }\n}\n\nexport class InsufficientPaymentError extends PaymentError {\n constructor(received: number, expected: number) {\n super(\n `Insufficient payment: received ${received}, expected ${expected}`,\n 'INSUFFICIENT_PAYMENT',\n { received, expected }\n );\n }\n}\n\n/**\n * ✅ NEW: Webhook specific errors\n */\nexport class WebhookError extends BlaziumError {\n constructor(message: string, code: string = 'WEBHOOK_ERROR', details?: unknown) {\n super(message, code, details);\n }\n}\n\nexport class InvalidSignatureError extends WebhookError {\n constructor() {\n super('Webhook signature verification failed', 'INVALID_SIGNATURE');\n }\n}","// sdk > src > client.ts\nimport { \n BlaziumConfig, \n BlaziumConfigSchema,\n BlaziumChain,\n Payment, \n CreatePaymentParams,\n CreatePaymentOptions,\n CreatePaymentSchema,\n PaymentStatus,\n WebhookPayload,\n WebhookEventType,\n ListPaymentsParams,\n PaginatedResponse,\n PaymentStats,\n MerchantBalance,\n Withdrawal,\n WithdrawalRequest\n} from './types';\nimport { \n BlaziumError, \n NetworkError, \n ValidationError, \n AuthenticationError, \n TimeoutError, \n APIError,\n RateLimitError \n} from './errors';\nimport axios, { AxiosInstance, AxiosError, AxiosRequestConfig } from 'axios';\nimport { createHmac, timingSafeEqual } from 'crypto';\n\nexport class BlaziumPayClient {\n private client: AxiosInstance;\n private config: BlaziumConfig;\n\n constructor(config: BlaziumConfig) {\n const validation = BlaziumConfigSchema.safeParse(config);\n if (!validation.success) {\n throw new ValidationError('Invalid configuration', validation.error.errors);\n }\n this.config = validation.data;\n\n this.client = axios.create({\n baseURL: this.config.baseUrl,\n timeout: this.config.timeout,\n headers: {\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'Content-Type': 'application/json',\n 'User-Agent': `BlaziumPay-SDK/1.0.0 (${this.config.environment})`,\n 'X-SDK-Version': '1.0.0'\n }\n });\n\n // Add retry logic for transient failures\n this.client.interceptors.request.use((config) => {\n (config as AxiosRequestConfig & { _retryCount?: number })._retryCount = \n ((config as AxiosRequestConfig & { _retryCount?: number })._retryCount || 0);\n return config;\n });\n\n this.client.interceptors.response.use(\n response => response,\n async (error: AxiosError & { config?: AxiosRequestConfig & { _retryCount?: number } }) => {\n const config = error.config;\n const retryCount = config?._retryCount || 0;\n const maxRetries = 3;\n const retryableStatuses = [429, 500, 502, 503, 504];\n const retryableCodes = ['ECONNABORTED', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNRESET'];\n\n // Retry logic for transient failures\n if (\n config &&\n retryCount < maxRetries &&\n (\n (error.response && retryableStatuses.includes(error.response.status)) ||\n (error.code && retryableCodes.includes(error.code)) ||\n (!error.response && error.request)\n )\n ) {\n config._retryCount = retryCount + 1;\n \n // Exponential backoff: 0.3s, 0.6s, 1.2s\n const delay = 300 * Math.pow(2, retryCount);\n await new Promise(resolve => setTimeout(resolve, delay));\n \n return this.client.request(config);\n }\n\n // Handle errors after retries exhausted or non-retryable errors\n if (error.response) {\n const status = error.response.status;\n const data = error.response.data as { error?: string; details?: unknown };\n const message = data?.error || error.message;\n\n if (status === 401 || status === 403) {\n throw new AuthenticationError(message);\n }\n if (status === 400 || status === 422) {\n throw new ValidationError(message, data?.details);\n }\n if (status === 404) {\n throw new APIError(message, 404, 'NOT_FOUND');\n }\n if (status === 429) {\n throw new RateLimitError(message);\n }\n if (status >= 500) {\n throw new APIError(message, status, 'SERVER_ERROR');\n }\n throw new APIError(message, status);\n } else if (error.code === 'ECONNABORTED') {\n throw new TimeoutError('Request timeout');\n } else if (error.request) {\n throw new NetworkError(error.message);\n } else {\n throw new BlaziumError(error.message);\n }\n }\n );\n }\n\n /**\n * Create a new payment with idempotency support.\n * \n * Note: rewardAmount and rewardCurrency are optional metadata fields for developer reference.\n * BlaziumPay does NOT automatically grant rewards - developers must implement their own\n * logic in webhook handlers to grant premium features, add currency, or perform other actions.\n */\n async createPayment(\n params: CreatePaymentParams,\n options?: CreatePaymentOptions\n ): Promise<Payment> {\n const validation = CreatePaymentSchema.safeParse(params);\n if (!validation.success) {\n throw new ValidationError('Invalid payment parameters', validation.error.errors);\n }\n\n const headers: Record<string, string> = {};\n \n if (options?.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n\n const response = await this.client.post<Record<string, unknown>>('/payments', validation.data, { headers });\n return this.normalizePayment(response.data);\n }\n\n /**\n * Get payment details\n */\n async getPayment(paymentId: string): Promise<Payment> {\n if (!paymentId) throw new ValidationError(\"Payment ID is required\");\n const response = await this.client.get<Record<string, unknown>>(`/payments/${paymentId}`);\n return this.normalizePayment(response.data);\n }\n\n /**\n * List payments with filters\n */\n async listPayments(params?: ListPaymentsParams): Promise<PaginatedResponse<Payment>> {\n const response = await this.client.get<{\n data: Record<string, unknown>[];\n pagination: {\n page: number;\n pageSize: number;\n totalPages: number;\n totalItems: number;\n };\n }>('/payments', {\n params\n });\n return {\n ...response.data,\n data: response.data.data.map(p => this.normalizePayment(p))\n };\n }\n\n /**\n * Cancel a payment\n */\n async cancelPayment(paymentId: string): Promise<Payment> {\n if (!paymentId) throw new ValidationError(\"Payment ID is required\");\n const response = await this.client.post<Record<string, unknown>>(`/payments/${paymentId}/cancel`);\n return this.normalizePayment(response.data);\n }\n\n /**\n * Get payment statistics\n */\n async getStats(): Promise<PaymentStats> {\n const response = await this.client.get<PaymentStats>('/payments/stats');\n return response.data;\n }\n\n /**\n * Get merchant balance for a specific chain\n */\n async getBalance(chain: string): Promise<MerchantBalance> {\n if (!chain) throw new ValidationError(\"Chain is required\");\n const response = await this.client.get<MerchantBalance>(`/balance`, {\n params: { chain: chain.toUpperCase() }\n });\n return response.data;\n }\n\n /**\n * Request withdrawal\n */\n async requestWithdrawal(request: WithdrawalRequest): Promise<Withdrawal> {\n if (!request.chain) throw new ValidationError(\"Chain is required\");\n if (!request.amount || request.amount <= 0) throw new ValidationError(\"Amount must be positive\");\n if (!request.destinationAddress) throw new ValidationError(\"Destination address is required\");\n\n const response = await this.client.post<Withdrawal>('/withdrawals', {\n chain: request.chain.toUpperCase(),\n amount: request.amount,\n destinationAddress: request.destinationAddress\n });\n return response.data;\n }\n\n /**\n * List withdrawal history\n */\n async listWithdrawals(): Promise<Withdrawal[]> {\n const response = await this.client.get<{ data: Withdrawal[] }>('/withdrawals');\n return response.data.data;\n }\n\n /**\n * Get specific withdrawal status\n */\n async getWithdrawal(withdrawalId: string): Promise<Withdrawal> {\n if (!withdrawalId) throw new ValidationError(\"Withdrawal ID is required\");\n const response = await this.client.get<Withdrawal>(`/withdrawals/${withdrawalId}`);\n return response.data;\n }\n\n /**\n * Wait for a payment to be confirmed (Long Polling helper)\n */\n async waitForPayment(\n paymentId: string, \n timeoutMs: number = 300000,\n pollIntervalMs: number = 3000\n ): Promise<Payment> {\n const start = Date.now();\n\n while (Date.now() - start < timeoutMs) {\n try {\n const payment = await this.getPayment(paymentId);\n \n if (payment.status === PaymentStatus.CONFIRMED) {\n return payment;\n }\n \n const finalStatuses: PaymentStatus[] = [\n PaymentStatus.FAILED,\n PaymentStatus.EXPIRED,\n PaymentStatus.CANCELLED\n ];\n \n if (finalStatuses.includes(payment.status)) {\n throw new BlaziumError(\n `Payment ended with status: ${payment.status}`,\n 'PAYMENT_NOT_CONFIRMED'\n );\n }\n \n await this.sleep(pollIntervalMs);\n } catch (e) {\n if (e instanceof BlaziumError && e.code === 'PAYMENT_NOT_CONFIRMED') {\n throw e;\n }\n if (!(e instanceof NetworkError || e instanceof TimeoutError)) {\n throw e;\n }\n }\n }\n \n throw new TimeoutError(\n `Payment confirmation timed out after ${timeoutMs}ms`,\n 'PAYMENT_TIMEOUT'\n );\n }\n\n /**\n * Verify webhook signature\n * \n * Note: Only verified webhooks receive events. Unverified webhooks will not receive\n * any webhook events from BlaziumPay. You must verify your webhook endpoint in the\n * dashboard before it will receive events and require signature verification.\n */\n verifyWebhookSignature(payload: string, signature: string): boolean {\n if (!this.config.webhookSecret) {\n throw new ValidationError(\n 'Webhook secret not configured. Set webhookSecret in config. ' +\n 'Note: Webhooks must be verified in the dashboard before they receive events. ' +\n 'Only verified webhooks are sent events by BlaziumPay.',\n 'WEBHOOK_SECRET_MISSING'\n );\n }\n\n try {\n const expectedSignature = createHmac('sha256', this.config.webhookSecret)\n .update(payload)\n .digest('hex');\n\n const expectedBuffer = Buffer.from(expectedSignature, 'hex');\n const actualBuffer = Buffer.from(signature.replace('sha256=', ''), 'hex');\n\n return expectedBuffer.length === actualBuffer.length && \n timingSafeEqual(expectedBuffer, actualBuffer);\n } catch {\n return false;\n }\n }\n\n /**\n * Parse and verify webhook payload\n * \n * @param rawPayload - Raw JSON string of webhook payload\n * @param signature - Signature from HTTP header 'X-Blazium-Signature'\n * @returns Parsed and verified webhook payload\n * \n * Note: Signature is verified from HTTP header, not from payload.\n * Only verified webhooks receive events. Unverified webhooks will not receive\n * any webhook events from BlaziumPay.\n */\n parseWebhook(rawPayload: string, signature: string): WebhookPayload {\n if (!this.verifyWebhookSignature(rawPayload, signature)) {\n throw new ValidationError(\n 'Invalid webhook signature. This webhook may be from an unverified endpoint. ' +\n 'Only verified webhooks receive events from BlaziumPay.',\n 'INVALID_SIGNATURE'\n );\n }\n\n try {\n const payload = JSON.parse(rawPayload) as {\n id: string;\n webhook_id: string;\n event: WebhookEventType;\n payment_id: string;\n payment: Record<string, unknown>;\n timestamp: string;\n createdAt: string;\n };\n \n return {\n id: payload.id,\n webhook_id: payload.webhook_id,\n event: payload.event,\n payment_id: payload.payment_id,\n payment: this.normalizePayment(payload.payment),\n timestamp: payload.timestamp,\n createdAt: payload.createdAt\n };\n } catch {\n throw new ValidationError(\n 'Invalid webhook payload format',\n 'INVALID_PAYLOAD'\n );\n }\n }\n\n // --- HELPERS ---\n\n private normalizePayment(payment: Record<string, unknown>): Payment {\n const metadata = (payment.metadata as Record<string, unknown>) || {};\n const partialPayment = metadata.partial_payment as Record<string, unknown> | undefined;\n \n return {\n id: payment.id as string,\n status: payment.status as PaymentStatus,\n amount: typeof payment.amount === 'string' ? Number(payment.amount) : (payment.amount as number),\n currency: payment.currency as string,\n checkoutUrl: payment.checkoutUrl as string,\n createdAt: payment.createdAt as string,\n expiresAt: payment.expiresAt as string,\n description: payment.description as string | undefined,\n metadata: payment.metadata as Record<string, unknown> | undefined,\n updatedAt: payment.updatedAt as string | undefined,\n payCurrency: payment.payCurrency as BlaziumChain | undefined,\n payAmount: payment.payAmount ? Number(payment.payAmount) : undefined,\n payAddress: payment.payAddress as string | undefined,\n txHash: payment.txHash as string | undefined,\n networkFee: payment.networkFee ? Number(payment.networkFee) : undefined,\n blockHeight: payment.blockHeight as string | undefined,\n confirmedAt: payment.confirmedAt as string | undefined,\n addressIndex: payment.addressIndex as number | undefined,\n quotedRate: payment.quotedRate ? Number(payment.quotedRate) : undefined,\n quoteExpiresAt: payment.quoteExpiresAt as string | undefined,\n rewardAmount: payment.rewardAmount ? Number(payment.rewardAmount) : undefined,\n rewardCurrency: payment.rewardCurrency as string | undefined,\n rewardData: payment.rewardData as Record<string, unknown> | undefined,\n rewardDelivered: payment.rewardDelivered as boolean | undefined,\n partialPayment: partialPayment ? {\n amount: Number(partialPayment.amount),\n txHash: partialPayment.txHash as string,\n detectedAt: partialPayment.detectedAt as string,\n expectedAmount: Number(partialPayment.expectedAmount ?? payment.payAmount ?? 0)\n } : undefined\n };\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n private isFinalStatus(status: PaymentStatus): boolean {\n return [\n PaymentStatus.CONFIRMED, \n PaymentStatus.FAILED, \n PaymentStatus.EXPIRED, \n PaymentStatus.CANCELLED\n ].includes(status);\n }\n\n isFinal(payment: Payment): boolean {\n return this.isFinalStatus(payment.status);\n }\n\n isPaid(payment: Payment): boolean {\n return payment.status === PaymentStatus.CONFIRMED;\n }\n\n isPartiallyPaid(payment: Payment): boolean {\n return payment.status === PaymentStatus.PARTIALLY_PAID;\n }\n\n isExpired(payment: Payment): boolean {\n return payment.status === PaymentStatus.EXPIRED;\n }\n\n getPaymentProgress(payment: Payment): number {\n if (!payment.payAmount || payment.amount <= 0) {\n return 0;\n }\n \n // If there's a partial payment, use that amount\n if (payment.partialPayment) {\n const progress = (payment.partialPayment.amount / payment.payAmount) * 100;\n return Math.min(100, Math.max(0, progress));\n }\n \n // If payment is confirmed, it's 100%\n if (payment.status === PaymentStatus.CONFIRMED) {\n return 100;\n }\n \n // Otherwise calculate based on payAmount vs expected amount\n // Note: This is approximate as we don't have real-time payment tracking\n return 0;\n }\n\n formatAmount(amount: number, currency: string): string {\n // Format crypto amounts with appropriate decimals\n const decimals: Record<string, number> = {\n 'TON': 4,\n 'SOL': 4,\n 'BTC': 8,\n };\n \n const decimalPlaces = decimals[currency.toUpperCase()] || 4;\n return `${amount.toFixed(decimalPlaces)} ${currency.toUpperCase()}`;\n }\n}"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@blazium/sdk",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Official Node.js SDK for BlaziumPay - Production-ready crypto payment infrastructure for TON, Solana, and Bitcoin",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"require": "./dist/index.js",
|
|
12
|
+
"import": "./dist/index.mjs"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsup",
|
|
26
|
+
"dev": "tsup --watch",
|
|
27
|
+
"typecheck": "tsc --noEmit",
|
|
28
|
+
"test": "node --test",
|
|
29
|
+
"prepublishOnly": "npm run typecheck && npm run build"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"blaziumpay",
|
|
33
|
+
"crypto",
|
|
34
|
+
"payments",
|
|
35
|
+
"blockchain",
|
|
36
|
+
"sdk",
|
|
37
|
+
"ton",
|
|
38
|
+
"solana",
|
|
39
|
+
"bitcoin",
|
|
40
|
+
"web3",
|
|
41
|
+
"cryptocurrency",
|
|
42
|
+
"payment-gateway",
|
|
43
|
+
"nodejs"
|
|
44
|
+
],
|
|
45
|
+
"author": "blaziumdev",
|
|
46
|
+
"license": "MIT",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "https://github.com/blaziumdev/blaziumpay-sdk.git"
|
|
50
|
+
},
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/blaziumdev/blaziumpay-sdk/issues"
|
|
53
|
+
},
|
|
54
|
+
"homepage": "https://blaziumpay.com",
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"tsup": "^8.0.1",
|
|
57
|
+
"typescript": "^5.3.3",
|
|
58
|
+
"@types/node": "^20.11.19"
|
|
59
|
+
},
|
|
60
|
+
"dependencies": {
|
|
61
|
+
"axios": "^1.6.7",
|
|
62
|
+
"zod": "^3.22.4"
|
|
63
|
+
},
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public"
|
|
66
|
+
}
|
|
67
|
+
}
|