@proofrails/sdk 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js ADDED
@@ -0,0 +1,567 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var React__default = /*#__PURE__*/_interopDefault(React);
8
+
9
+ // src/react.ts
10
+
11
+ // src/types/common.ts
12
+ var ProofRailsError = class extends Error {
13
+ constructor(message, code, statusCode, details) {
14
+ super(message);
15
+ this.code = code;
16
+ this.statusCode = statusCode;
17
+ this.details = details;
18
+ this.name = "ProofRailsError";
19
+ }
20
+ };
21
+
22
+ // src/client.ts
23
+ var APIClient = class {
24
+ constructor(config = {}) {
25
+ this.rateLimitInfo = null;
26
+ const envBaseUrl = typeof process !== "undefined" && process.env?.NEXT_PUBLIC_PROOFRAILS_BASE_URL;
27
+ const defaultBaseUrl = "https://proofrails-clone-middleware.onrender.com";
28
+ this.baseUrl = config.baseUrl || envBaseUrl || defaultBaseUrl;
29
+ this.apiKey = config.apiKey;
30
+ this.adminToken = config.adminToken;
31
+ this.timeout = config.timeout || 3e4;
32
+ this.retries = config.retries ?? 3;
33
+ this.retryDelay = config.retryDelay ?? 1e3;
34
+ }
35
+ getRateLimitInfo() {
36
+ return this.rateLimitInfo;
37
+ }
38
+ async get(endpoint, options = {}) {
39
+ return this.request("GET", endpoint, void 0, options);
40
+ }
41
+ async post(endpoint, body, options = {}) {
42
+ return this.request("POST", endpoint, body, options);
43
+ }
44
+ async put(endpoint, body, options = {}) {
45
+ return this.request("PUT", endpoint, body, options);
46
+ }
47
+ async delete(endpoint, options = {}) {
48
+ return this.request("DELETE", endpoint, void 0, options);
49
+ }
50
+ async request(method, endpoint, body, options = {}, attempt = 0) {
51
+ const url = `${this.baseUrl}${endpoint}`;
52
+ const headers = {
53
+ "Content-Type": "application/json",
54
+ ...options.headers || {}
55
+ };
56
+ if (this.apiKey) {
57
+ headers["X-API-Key"] = this.apiKey;
58
+ }
59
+ if (this.adminToken) {
60
+ headers["Authorization"] = `Bearer ${this.adminToken}`;
61
+ }
62
+ const controller = new AbortController();
63
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
64
+ try {
65
+ console.log(`[ProofRails SDK] ${method} ${url}${attempt > 0 ? ` (retry ${attempt}/${this.retries})` : ""}`);
66
+ const response = await fetch(url, {
67
+ method,
68
+ headers,
69
+ body: body ? JSON.stringify(body) : void 0,
70
+ signal: controller.signal,
71
+ ...options
72
+ });
73
+ clearTimeout(timeoutId);
74
+ this.extractRateLimitInfo(response);
75
+ if (!response.ok) {
76
+ const errorData = await response.json().catch(() => ({}));
77
+ const error = new ProofRailsError(
78
+ errorData.message || errorData.detail || `HTTP ${response.status}: ${response.statusText}`,
79
+ errorData.code,
80
+ response.status,
81
+ errorData
82
+ );
83
+ if (this.shouldRetry(response.status, attempt)) {
84
+ return this.retryRequest(method, endpoint, body, options, attempt);
85
+ }
86
+ throw error;
87
+ }
88
+ return await response.json();
89
+ } catch (error) {
90
+ clearTimeout(timeoutId);
91
+ if (error instanceof ProofRailsError) {
92
+ if (this.shouldRetry(0, attempt)) {
93
+ return this.retryRequest(method, endpoint, body, options, attempt);
94
+ }
95
+ throw error;
96
+ }
97
+ if (error instanceof Error) {
98
+ if (error.name === "AbortError") {
99
+ throw new ProofRailsError(`Request timeout after ${this.timeout}ms`, "TIMEOUT");
100
+ }
101
+ if (this.shouldRetry(0, attempt)) {
102
+ return this.retryRequest(method, endpoint, body, options, attempt);
103
+ }
104
+ throw new ProofRailsError(error.message, "NETWORK_ERROR");
105
+ }
106
+ throw new ProofRailsError("Unknown error occurred", "UNKNOWN_ERROR");
107
+ }
108
+ }
109
+ shouldRetry(statusCode, attempt) {
110
+ if (attempt >= this.retries) return false;
111
+ if (statusCode === 0) return true;
112
+ if (statusCode >= 500 && statusCode < 600) return true;
113
+ if (statusCode === 429) return true;
114
+ return false;
115
+ }
116
+ async retryRequest(method, endpoint, body, options, attempt) {
117
+ const delay = this.retryDelay * Math.pow(2, attempt);
118
+ console.log(`[ProofRails SDK] Retrying in ${delay}ms...`);
119
+ await new Promise((resolve) => setTimeout(resolve, delay));
120
+ return this.request(method, endpoint, body, options, attempt + 1);
121
+ }
122
+ extractRateLimitInfo(response) {
123
+ const limit = response.headers.get("X-RateLimit-Limit");
124
+ const remaining = response.headers.get("X-RateLimit-Remaining");
125
+ const reset = response.headers.get("X-RateLimit-Reset");
126
+ if (limit && remaining && reset) {
127
+ const resetTimestamp = parseInt(reset, 10);
128
+ this.rateLimitInfo = {
129
+ limit: parseInt(limit, 10),
130
+ remaining: parseInt(remaining, 10),
131
+ reset: resetTimestamp,
132
+ resetDate: new Date(resetTimestamp * 1e3)
133
+ };
134
+ }
135
+ }
136
+ setApiKey(apiKey) {
137
+ this.apiKey = apiKey;
138
+ }
139
+ setAdminToken(adminToken) {
140
+ this.adminToken = adminToken;
141
+ }
142
+ getBaseUrl() {
143
+ return this.baseUrl;
144
+ }
145
+ };
146
+
147
+ // src/modules/projects.ts
148
+ var ProjectsModule = class {
149
+ constructor(client) {
150
+ this.client = client;
151
+ }
152
+ async getInfo() {
153
+ return this.client.get("/v1/whoami");
154
+ }
155
+ async rotateKey() {
156
+ return this.client.post("/v1/api-keys/rotate");
157
+ }
158
+ async create(options = {}) {
159
+ return this.client.post("/v1/public/api-keys", options);
160
+ }
161
+ };
162
+ var AdminModule = class {
163
+ constructor(client) {
164
+ this.client = client;
165
+ }
166
+ async createKey(options) {
167
+ return this.client.post("/v1/admin/api-keys", options);
168
+ }
169
+ async deleteKey(keyId) {
170
+ return this.client.delete(`/v1/admin/api-keys/${keyId}`);
171
+ }
172
+ };
173
+
174
+ // src/modules/receipts.ts
175
+ var ReceiptsModule = class {
176
+ constructor(client) {
177
+ this.client = client;
178
+ }
179
+ async create(options) {
180
+ const payload = {
181
+ tip_tx_hash: options.transactionHash,
182
+ chain: options.chain,
183
+ amount: String(options.amount),
184
+ currency: options.currency,
185
+ sender_wallet: options.sender,
186
+ receiver_wallet: options.receiver,
187
+ reference: options.reference,
188
+ callback_url: options.callbackUrl
189
+ };
190
+ const response = await this.client.post(
191
+ "/v1/iso/record-tip",
192
+ payload
193
+ );
194
+ return {
195
+ id: response.receipt_id,
196
+ status: response.status,
197
+ transactionHash: options.transactionHash,
198
+ chain: options.chain,
199
+ amount: String(options.amount),
200
+ currency: options.currency,
201
+ sender: options.sender,
202
+ receiver: options.receiver,
203
+ reference: options.reference,
204
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
205
+ };
206
+ }
207
+ async get(receiptId) {
208
+ return this.client.get(`/v1/iso/receipts/${receiptId}`);
209
+ }
210
+ async list(options = {}) {
211
+ const params = new URLSearchParams();
212
+ if (options.limit) params.append("limit", String(options.limit));
213
+ if (options.page) params.append("page", String(options.page));
214
+ if (options.status) params.append("status", options.status);
215
+ const query = params.toString();
216
+ const endpoint = `/v1/iso/receipts${query ? `?${query}` : ""}`;
217
+ const response = await this.client.get(endpoint);
218
+ const items = Array.isArray(response) ? response : response.items || [];
219
+ return {
220
+ items,
221
+ total: items.length,
222
+ page: options.page || 1,
223
+ limit: options.limit || 10
224
+ };
225
+ }
226
+ async getArtifacts(receiptId) {
227
+ const messages = await this.client.get(`/v1/iso/messages/${receiptId}`);
228
+ const baseUrl = this.client.getBaseUrl();
229
+ const artifacts = {};
230
+ messages.forEach((msg) => {
231
+ switch (msg.type) {
232
+ case "pain.001":
233
+ artifacts.pain001Url = msg.url;
234
+ break;
235
+ case "pain.002":
236
+ artifacts.pain002Url = msg.url;
237
+ break;
238
+ case "pain.007":
239
+ artifacts.pain007Url = msg.url;
240
+ break;
241
+ case "pain.008":
242
+ artifacts.pain008Url = msg.url;
243
+ break;
244
+ case "camt.054":
245
+ artifacts.camt054Url = msg.url;
246
+ break;
247
+ }
248
+ });
249
+ artifacts.bundleUrl = `${baseUrl}/files/${receiptId}/evidence.zip`;
250
+ artifacts.manifestUrl = `${baseUrl}/files/${receiptId}/manifest.json`;
251
+ return artifacts;
252
+ }
253
+ };
254
+
255
+ // src/modules/verification.ts
256
+ var VerificationModule = class {
257
+ constructor(client) {
258
+ this.client = client;
259
+ }
260
+ async byReceiptId(receiptId) {
261
+ const receipt = await this.client.get(`/v1/iso/receipts/${receiptId}`);
262
+ return {
263
+ valid: receipt.status === "anchored",
264
+ bundleHash: receipt.bundle_hash || receipt.bundleHash || "",
265
+ onChain: !!receipt.anchor_tx || !!receipt.anchorTx,
266
+ anchorTx: receipt.anchor_tx || receipt.anchorTx,
267
+ timestamp: receipt.anchored_at || receipt.anchoredAt
268
+ };
269
+ }
270
+ async byUrl(bundleUrl) {
271
+ return this.client.post("/v1/iso/verify", {
272
+ bundle_url: bundleUrl
273
+ });
274
+ }
275
+ async byHash(bundleHash) {
276
+ return this.client.post("/v1/iso/verify", {
277
+ bundle_hash: bundleHash
278
+ });
279
+ }
280
+ async getProof(receiptId) {
281
+ const receipt = await this.client.get(`/v1/iso/receipts/${receiptId}`);
282
+ return {
283
+ receiptId,
284
+ bundleHash: receipt.bundle_hash || receipt.bundleHash,
285
+ anchorTx: receipt.anchor_tx || receipt.anchorTx,
286
+ blockNumber: receipt.block_number || 0,
287
+ timestamp: receipt.anchored_at || receipt.anchoredAt,
288
+ signature: receipt.signature || "",
289
+ network: receipt.chain,
290
+ contractAddress: receipt.contract_address || ""
291
+ };
292
+ }
293
+ };
294
+
295
+ // src/modules/statements.ts
296
+ var StatementsModule = class {
297
+ constructor(client) {
298
+ this.client = client;
299
+ }
300
+ async intraday(options = {}) {
301
+ const response = await this.client.post("/v1/iso/statement/camt052", {
302
+ date_from: options.dateFrom,
303
+ date_to: options.dateTo,
304
+ account_id: options.accountId
305
+ });
306
+ return {
307
+ type: "camt.052",
308
+ url: response.url,
309
+ downloadUrl: response.download_url || response.url,
310
+ messageId: response.message_id || response.messageId,
311
+ createdAt: response.created_at || (/* @__PURE__ */ new Date()).toISOString()
312
+ };
313
+ }
314
+ async endOfDay(options = {}) {
315
+ const response = await this.client.post("/v1/iso/statement/camt053", {
316
+ date: options.dateTo || options.dateFrom,
317
+ account_id: options.accountId
318
+ });
319
+ return {
320
+ type: "camt.053",
321
+ url: response.url,
322
+ downloadUrl: response.download_url || response.url,
323
+ messageId: response.message_id || response.messageId,
324
+ createdAt: response.created_at || (/* @__PURE__ */ new Date()).toISOString()
325
+ };
326
+ }
327
+ };
328
+
329
+ // src/modules/events.ts
330
+ var EventsModule = class {
331
+ constructor(client) {
332
+ this.client = client;
333
+ }
334
+ listen(receiptId, callback) {
335
+ const baseUrl = this.client.getBaseUrl();
336
+ const url = `${baseUrl}/v1/iso/events/${receiptId}`;
337
+ const eventSource = new EventSource(url);
338
+ eventSource.onmessage = (event) => {
339
+ try {
340
+ const data = JSON.parse(event.data);
341
+ callback({
342
+ id: receiptId,
343
+ status: data.status,
344
+ anchorTx: data.anchor_tx || data.anchorTx,
345
+ bundleHash: data.bundle_hash || data.bundleHash,
346
+ timestamp: data.timestamp || (/* @__PURE__ */ new Date()).toISOString()
347
+ });
348
+ } catch (error) {
349
+ console.error("Failed to parse SSE event:", error);
350
+ }
351
+ };
352
+ eventSource.onerror = (error) => {
353
+ console.error("SSE connection error:", error);
354
+ eventSource.close();
355
+ };
356
+ return {
357
+ stop: () => eventSource.close()
358
+ };
359
+ }
360
+ };
361
+
362
+ // src/modules/embed.ts
363
+ var EmbedModule = class {
364
+ constructor(client) {
365
+ this.client = client;
366
+ }
367
+ widget(receiptId, options = {}) {
368
+ const baseUrl = this.client.getBaseUrl();
369
+ const theme = options.theme || "light";
370
+ const width = options.width || "100%";
371
+ const height = options.height || "400px";
372
+ const embedUrl = `${baseUrl}/embed/receipt?rid=${receiptId}&theme=${theme}`;
373
+ const iframeHtml = `<iframe src="${embedUrl}" width="${width}" height="${height}" frameborder="0" style="border: none;"></iframe>`;
374
+ return {
375
+ iframeHtml,
376
+ embedUrl
377
+ };
378
+ }
379
+ fullPage(receiptId) {
380
+ const baseUrl = this.client.getBaseUrl();
381
+ return `${baseUrl}/receipt/${receiptId}`;
382
+ }
383
+ };
384
+
385
+ // src/templates/payment.ts
386
+ async function createPaymentReceipt(receiptsModule, options) {
387
+ return receiptsModule.create({
388
+ transactionHash: options.transactionHash,
389
+ chain: options.chain || "coston2",
390
+ // Smart default
391
+ amount: options.amount,
392
+ currency: options.currency || "C2FLR",
393
+ // Smart default
394
+ sender: options.senderWallet || options.from,
395
+ receiver: options.receiverWallet || options.to,
396
+ reference: `Payment: ${options.purpose} (Tx: ${options.transactionHash})`
397
+ });
398
+ }
399
+
400
+ // src/templates/donation.ts
401
+ async function createDonationReceipt(receiptsModule, options) {
402
+ return receiptsModule.create({
403
+ transactionHash: options.transactionHash,
404
+ chain: "coston2",
405
+ amount: options.amount,
406
+ currency: "FLR",
407
+ sender: options.donorWallet || options.donor,
408
+ receiver: options.organizationWallet || options.organization,
409
+ reference: `Donation: ${options.campaign} (Donor: ${options.donor}, Organization: ${options.organization})`
410
+ });
411
+ }
412
+
413
+ // src/templates/escrow.ts
414
+ async function createEscrowReceipt(receiptsModule, options) {
415
+ return receiptsModule.create({
416
+ transactionHash: options.transactionHash,
417
+ chain: "coston2",
418
+ amount: options.amount,
419
+ currency: "FLR",
420
+ sender: options.buyerWallet || options.buyer,
421
+ receiver: options.sellerWallet || options.seller,
422
+ reference: `Escrow Release: ${options.escrowId} - ${options.releaseReason} (Buyer: ${options.buyer}, Seller: ${options.seller})`
423
+ });
424
+ }
425
+
426
+ // src/templates/grant.ts
427
+ async function createGrantReceipt(receiptsModule, options) {
428
+ return receiptsModule.create({
429
+ transactionHash: options.transactionHash,
430
+ chain: "coston2",
431
+ amount: options.amount,
432
+ currency: "FLR",
433
+ sender: options.grantorWallet || options.grantor,
434
+ receiver: options.granteeWallet || options.grantee,
435
+ reference: `Grant: ${options.grantId} - ${options.purpose} (Grantor: ${options.grantor}, Grantee: ${options.grantee})`
436
+ });
437
+ }
438
+
439
+ // src/templates/refund.ts
440
+ async function createRefundReceipt(receiptsModule, options) {
441
+ return receiptsModule.create({
442
+ transactionHash: options.transactionHash,
443
+ chain: "coston2",
444
+ amount: options.amount,
445
+ currency: "FLR",
446
+ sender: options.businessWallet || "Business",
447
+ receiver: options.customerWallet || options.customer,
448
+ reference: `Refund: ${options.originalPayment} - ${options.reason} (Customer: ${options.customer})`
449
+ });
450
+ }
451
+
452
+ // src/sdk.ts
453
+ var ProofRails = class _ProofRails {
454
+ constructor(config = {}) {
455
+ this.client = new APIClient(config);
456
+ this.project = new ProjectsModule(this.client);
457
+ this.admin = new AdminModule(this.client);
458
+ this.receipts = new ReceiptsModule(this.client);
459
+ this.verify = new VerificationModule(this.client);
460
+ this.statements = new StatementsModule(this.client);
461
+ this.events = new EventsModule(this.client);
462
+ this.embed = new EmbedModule(this.client);
463
+ this.templates = {
464
+ payment: (options) => createPaymentReceipt(this.receipts, options),
465
+ donation: (options) => createDonationReceipt(this.receipts, options),
466
+ escrow: (options) => createEscrowReceipt(this.receipts, options),
467
+ grant: (options) => createGrantReceipt(this.receipts, options),
468
+ refund: (options) => createRefundReceipt(this.receipts, options)
469
+ };
470
+ }
471
+ /**
472
+ * Create a new project with API key (self-serve)
473
+ * This is a convenience method for beginners
474
+ */
475
+ static async createProject(options = {}) {
476
+ const tempClient = new _ProofRails({ network: options.network, baseUrl: options.baseUrl });
477
+ const result = await tempClient.project.create({ label: options.label });
478
+ const apiKey = result.api_key || result.apiKey;
479
+ const projectId = result.project_id || result.projectId;
480
+ const client = new _ProofRails({
481
+ apiKey,
482
+ network: options.network,
483
+ baseUrl: options.baseUrl
484
+ // Propagate baseUrl
485
+ });
486
+ return {
487
+ client,
488
+ apiKey,
489
+ projectId
490
+ };
491
+ }
492
+ /**
493
+ * Update the API key for this client
494
+ */
495
+ setApiKey(apiKey) {
496
+ this.client.setApiKey(apiKey);
497
+ }
498
+ /**
499
+ * Update the admin token for this client
500
+ */
501
+ setAdminToken(adminToken) {
502
+ this.client.setAdminToken(adminToken);
503
+ }
504
+ };
505
+
506
+ // src/react.ts
507
+ var ProofRailsContext = React.createContext(null);
508
+ var ProofRailsProvider = ({
509
+ apiKey,
510
+ config = {},
511
+ children
512
+ }) => {
513
+ const [client, setClient] = React.useState(null);
514
+ React.useEffect(() => {
515
+ const instance = new ProofRails({
516
+ apiKey,
517
+ ...config
518
+ });
519
+ setClient(instance);
520
+ }, [apiKey]);
521
+ if (!client) return null;
522
+ return React__default.default.createElement(
523
+ ProofRailsContext.Provider,
524
+ { value: client },
525
+ children
526
+ );
527
+ };
528
+ var useProofRails = () => {
529
+ const context = React.useContext(ProofRailsContext);
530
+ if (!context) {
531
+ throw new Error("useProofRails must be used within a ProofRailsProvider");
532
+ }
533
+ return context;
534
+ };
535
+ var useProofRailsPayment = () => {
536
+ const client = useProofRails();
537
+ const [isLoading, setIsLoading] = React.useState(false);
538
+ const [error, setError] = React.useState(null);
539
+ const [receipt, setReceipt] = React.useState(null);
540
+ const createPayment = async (options) => {
541
+ setIsLoading(true);
542
+ setError(null);
543
+ try {
544
+ const result = await client.templates.payment(options);
545
+ setReceipt(result);
546
+ return result;
547
+ } catch (err) {
548
+ const errorObj = err instanceof Error ? err : new Error("Payment creation failed");
549
+ setError(errorObj);
550
+ throw errorObj;
551
+ } finally {
552
+ setIsLoading(false);
553
+ }
554
+ };
555
+ return {
556
+ createPayment,
557
+ receipt,
558
+ isLoading,
559
+ error
560
+ };
561
+ };
562
+
563
+ exports.ProofRailsProvider = ProofRailsProvider;
564
+ exports.useProofRails = useProofRails;
565
+ exports.useProofRailsPayment = useProofRailsPayment;
566
+ //# sourceMappingURL=react.js.map
567
+ //# sourceMappingURL=react.js.map