@settlr/sdk 0.1.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.
@@ -0,0 +1,635 @@
1
+ import { PublicKey, Transaction, Connection } from '@solana/web3.js';
2
+ import * as react_jsx_runtime from 'react/jsx-runtime';
3
+ import { ReactNode, CSSProperties } from 'react';
4
+
5
+ declare const USDC_MINT_DEVNET: PublicKey;
6
+ declare const USDC_MINT_MAINNET: PublicKey;
7
+ declare const SETTLR_CHECKOUT_URL: {
8
+ readonly production: "https://settlr.dev/pay";
9
+ readonly development: "http://localhost:3000/pay";
10
+ };
11
+ declare const SUPPORTED_NETWORKS: readonly ["devnet", "mainnet-beta"];
12
+ type SupportedNetwork = typeof SUPPORTED_NETWORKS[number];
13
+
14
+ /**
15
+ * Payment status
16
+ */
17
+ type PaymentStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'expired' | 'refunded';
18
+ /**
19
+ * Options for creating a payment
20
+ */
21
+ interface CreatePaymentOptions {
22
+ /** Amount in USDC (e.g., 29.99) */
23
+ amount: number;
24
+ /** Optional memo/description for the payment */
25
+ memo?: string;
26
+ /** Optional order/invoice ID for your records */
27
+ orderId?: string;
28
+ /** Optional metadata to attach to the payment */
29
+ metadata?: Record<string, string>;
30
+ /** URL to redirect after successful payment */
31
+ successUrl?: string;
32
+ /** URL to redirect after cancelled payment */
33
+ cancelUrl?: string;
34
+ /** Expiration time in seconds (default: 3600 = 1 hour) */
35
+ expiresIn?: number;
36
+ }
37
+ /**
38
+ * Payment object returned after creation
39
+ */
40
+ interface Payment {
41
+ /** Unique payment ID */
42
+ id: string;
43
+ /** Amount in USDC */
44
+ amount: number;
45
+ /** Amount in lamports (USDC atomic units) */
46
+ amountLamports: bigint;
47
+ /** Current status */
48
+ status: PaymentStatus;
49
+ /** Merchant wallet address */
50
+ merchantAddress: string;
51
+ /** Checkout URL for the customer */
52
+ checkoutUrl: string;
53
+ /** QR code data URL (base64 PNG) */
54
+ qrCode: string;
55
+ /** Memo/description */
56
+ memo?: string;
57
+ /** Order ID */
58
+ orderId?: string;
59
+ /** Custom metadata */
60
+ metadata?: Record<string, string>;
61
+ /** Creation timestamp */
62
+ createdAt: Date;
63
+ /** Expiration timestamp */
64
+ expiresAt: Date;
65
+ /** Transaction signature (when completed) */
66
+ txSignature?: string;
67
+ /** Payer wallet address (when completed) */
68
+ payerAddress?: string;
69
+ }
70
+ /**
71
+ * Result of a direct payment (not via checkout link)
72
+ */
73
+ interface PaymentResult {
74
+ /** Whether the payment succeeded */
75
+ success: boolean;
76
+ /** Transaction signature */
77
+ signature: string;
78
+ /** Amount paid in USDC */
79
+ amount: number;
80
+ /** Merchant address */
81
+ merchantAddress: string;
82
+ /** Block time of confirmation */
83
+ blockTime?: number;
84
+ /** Error message if failed */
85
+ error?: string;
86
+ }
87
+ /**
88
+ * Merchant configuration
89
+ */
90
+ interface MerchantConfig {
91
+ /** Merchant display name */
92
+ name: string;
93
+ /** Merchant wallet address (receives payments) */
94
+ walletAddress: string | PublicKey;
95
+ /** Optional logo URL */
96
+ logoUrl?: string;
97
+ /** Optional website URL */
98
+ websiteUrl?: string;
99
+ /** Webhook URL for payment notifications */
100
+ webhookUrl?: string;
101
+ /** Webhook secret for signature verification */
102
+ webhookSecret?: string;
103
+ }
104
+ /**
105
+ * Transaction options for direct payments
106
+ */
107
+ interface TransactionOptions {
108
+ /** Skip preflight simulation */
109
+ skipPreflight?: boolean;
110
+ /** Commitment level */
111
+ commitment?: 'processed' | 'confirmed' | 'finalized';
112
+ /** Max retries */
113
+ maxRetries?: number;
114
+ }
115
+ /**
116
+ * Webhook event types
117
+ */
118
+ type WebhookEventType = 'payment.created' | 'payment.completed' | 'payment.failed' | 'payment.expired' | 'payment.refunded';
119
+ /**
120
+ * Webhook payload
121
+ */
122
+ interface WebhookPayload {
123
+ id: string;
124
+ type: WebhookEventType;
125
+ payment: Payment;
126
+ timestamp: string;
127
+ signature: string;
128
+ }
129
+
130
+ /**
131
+ * Settlr SDK configuration
132
+ */
133
+ interface SettlrConfig {
134
+ /** Settlr API key (required for production) */
135
+ apiKey: string;
136
+ /** Merchant configuration */
137
+ merchant: MerchantConfig;
138
+ /** Network to use (default: devnet) */
139
+ network?: SupportedNetwork;
140
+ /** Custom RPC endpoint */
141
+ rpcEndpoint?: string;
142
+ /** Use testnet/sandbox mode */
143
+ testMode?: boolean;
144
+ }
145
+ /**
146
+ * Settlr SDK Client
147
+ *
148
+ * @example
149
+ * ```typescript
150
+ * const settlr = new Settlr({
151
+ * apiKey: 'sk_live_xxxxxxxxxxxx',
152
+ * merchant: {
153
+ * name: 'My Store',
154
+ * walletAddress: 'YOUR_WALLET_ADDRESS',
155
+ * },
156
+ * });
157
+ *
158
+ * const payment = await settlr.createPayment({
159
+ * amount: 29.99,
160
+ * memo: 'Premium subscription',
161
+ * });
162
+ *
163
+ * // Redirect customer to checkout
164
+ * window.location.href = payment.checkoutUrl;
165
+ * ```
166
+ */
167
+ declare class Settlr {
168
+ private config;
169
+ private connection;
170
+ private usdcMint;
171
+ private merchantWallet;
172
+ private apiBaseUrl;
173
+ private validated;
174
+ private merchantId?;
175
+ private tier?;
176
+ constructor(config: SettlrConfig);
177
+ /**
178
+ * Validate API key with Settlr backend
179
+ */
180
+ private validateApiKey;
181
+ /**
182
+ * Get the current tier
183
+ */
184
+ getTier(): 'free' | 'pro' | 'enterprise' | undefined;
185
+ /**
186
+ * Create a payment link
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * const payment = await settlr.createPayment({
191
+ * amount: 29.99,
192
+ * memo: 'Order #1234',
193
+ * successUrl: 'https://mystore.com/success',
194
+ * });
195
+ *
196
+ * console.log(payment.checkoutUrl);
197
+ * // https://settlr.dev/pay?amount=29.99&merchant=...
198
+ * ```
199
+ */
200
+ createPayment(options: CreatePaymentOptions): Promise<Payment>;
201
+ /**
202
+ * Build a transaction for direct payment (for wallet integration)
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * const tx = await settlr.buildTransaction({
207
+ * payerPublicKey: wallet.publicKey,
208
+ * amount: 29.99,
209
+ * });
210
+ *
211
+ * const signature = await wallet.sendTransaction(tx, connection);
212
+ * ```
213
+ */
214
+ buildTransaction(options: {
215
+ payerPublicKey: PublicKey;
216
+ amount: number;
217
+ memo?: string;
218
+ }): Promise<Transaction>;
219
+ /**
220
+ * Execute a direct payment (requires wallet adapter)
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * const result = await settlr.pay({
225
+ * wallet,
226
+ * amount: 29.99,
227
+ * memo: 'Order #1234',
228
+ * });
229
+ *
230
+ * if (result.success) {
231
+ * console.log('Paid!', result.signature);
232
+ * }
233
+ * ```
234
+ */
235
+ pay(options: {
236
+ wallet: {
237
+ publicKey: PublicKey;
238
+ signTransaction: (tx: Transaction) => Promise<Transaction>;
239
+ };
240
+ amount: number;
241
+ memo?: string;
242
+ txOptions?: TransactionOptions;
243
+ }): Promise<PaymentResult>;
244
+ /**
245
+ * Check payment status by transaction signature
246
+ */
247
+ getPaymentStatus(signature: string): Promise<'pending' | 'completed' | 'failed'>;
248
+ /**
249
+ * Create a hosted checkout session (like Stripe Checkout)
250
+ *
251
+ * @example
252
+ * ```typescript
253
+ * const session = await settlr.createCheckoutSession({
254
+ * amount: 29.99,
255
+ * description: 'Premium Plan',
256
+ * successUrl: 'https://mystore.com/success',
257
+ * cancelUrl: 'https://mystore.com/cancel',
258
+ * webhookUrl: 'https://mystore.com/api/webhooks/settlr',
259
+ * });
260
+ *
261
+ * // Redirect customer to hosted checkout
262
+ * window.location.href = session.url;
263
+ * ```
264
+ */
265
+ createCheckoutSession(options: {
266
+ amount: number;
267
+ description?: string;
268
+ metadata?: Record<string, string>;
269
+ successUrl: string;
270
+ cancelUrl: string;
271
+ webhookUrl?: string;
272
+ }): Promise<{
273
+ id: string;
274
+ url: string;
275
+ expiresAt: number;
276
+ }>;
277
+ /**
278
+ * Get merchant's USDC balance
279
+ */
280
+ getMerchantBalance(): Promise<number>;
281
+ /**
282
+ * Generate QR code for payment URL
283
+ */
284
+ private generateQRCode;
285
+ /**
286
+ * Get the connection instance
287
+ */
288
+ getConnection(): Connection;
289
+ /**
290
+ * Get merchant wallet address
291
+ */
292
+ getMerchantAddress(): PublicKey;
293
+ /**
294
+ * Get USDC mint address
295
+ */
296
+ getUsdcMint(): PublicKey;
297
+ }
298
+
299
+ /**
300
+ * Format lamports to USDC string
301
+ * @param lamports - Amount in lamports (atomic units)
302
+ * @param decimals - Number of decimal places (default: 2)
303
+ */
304
+ declare function formatUSDC(lamports: bigint | number, decimals?: number): string;
305
+ /**
306
+ * Parse USDC amount to lamports
307
+ * @param amount - Amount in USDC (e.g., 29.99)
308
+ */
309
+ declare function parseUSDC(amount: number | string): bigint;
310
+ /**
311
+ * Shorten a Solana address for display
312
+ * @param address - Full address string
313
+ * @param chars - Number of chars to show on each end (default: 4)
314
+ */
315
+ declare function shortenAddress(address: string, chars?: number): string;
316
+
317
+ /**
318
+ * Settlr context value
319
+ */
320
+ interface SettlrContextValue {
321
+ /** Settlr client instance */
322
+ settlr: Settlr | null;
323
+ /** Whether wallet is connected */
324
+ connected: boolean;
325
+ /** Create a payment link */
326
+ createPayment: (options: CreatePaymentOptions) => Promise<Payment>;
327
+ /** Execute a direct payment */
328
+ pay: (options: {
329
+ amount: number;
330
+ memo?: string;
331
+ }) => Promise<PaymentResult>;
332
+ /** Get merchant's USDC balance */
333
+ getBalance: () => Promise<number>;
334
+ }
335
+ /**
336
+ * Settlr Provider Props
337
+ */
338
+ interface SettlrProviderProps {
339
+ children: ReactNode;
340
+ config: Omit<SettlrConfig, "rpcEndpoint">;
341
+ }
342
+ /**
343
+ * Settlr Provider - Wraps your app to provide Settlr functionality
344
+ *
345
+ * @example
346
+ * ```tsx
347
+ * import { SettlrProvider } from '@settlr/sdk';
348
+ *
349
+ * function App() {
350
+ * return (
351
+ * <WalletProvider wallets={wallets}>
352
+ * <SettlrProvider config={{
353
+ * merchant: {
354
+ * name: 'My Store',
355
+ * walletAddress: 'YOUR_WALLET',
356
+ * },
357
+ * }}>
358
+ * <YourApp />
359
+ * </SettlrProvider>
360
+ * </WalletProvider>
361
+ * );
362
+ * }
363
+ * ```
364
+ */
365
+ declare function SettlrProvider({ children, config }: SettlrProviderProps): react_jsx_runtime.JSX.Element;
366
+ /**
367
+ * useSettlr hook - Access Settlr functionality in your components
368
+ *
369
+ * @example
370
+ * ```tsx
371
+ * import { useSettlr } from '@settlr/sdk';
372
+ *
373
+ * function CheckoutButton() {
374
+ * const { createPayment, pay, connected } = useSettlr();
375
+ *
376
+ * const handlePay = async () => {
377
+ * // Option 1: Create payment link
378
+ * const payment = await createPayment({ amount: 29.99 });
379
+ * window.location.href = payment.checkoutUrl;
380
+ *
381
+ * // Option 2: Direct payment
382
+ * const result = await pay({ amount: 29.99 });
383
+ * if (result.success) {
384
+ * console.log('Paid!');
385
+ * }
386
+ * };
387
+ *
388
+ * return (
389
+ * <button onClick={handlePay} disabled={!connected}>
390
+ * Pay $29.99
391
+ * </button>
392
+ * );
393
+ * }
394
+ * ```
395
+ */
396
+ declare function useSettlr(): SettlrContextValue;
397
+
398
+ /**
399
+ * Settlr Buy Button - Drop-in payment button component
400
+ *
401
+ * @example
402
+ * ```tsx
403
+ * import { BuyButton } from '@settlr/sdk';
404
+ *
405
+ * function ProductPage() {
406
+ * return (
407
+ * <BuyButton
408
+ * amount={49.99}
409
+ * memo="Premium Game Bundle"
410
+ * onSuccess={(result) => {
411
+ * console.log('Payment successful!', result.signature);
412
+ * // Redirect to success page or unlock content
413
+ * }}
414
+ * onError={(error) => console.error(error)}
415
+ * >
416
+ * Buy Now - $49.99
417
+ * </BuyButton>
418
+ * );
419
+ * }
420
+ * ```
421
+ */
422
+ interface BuyButtonProps {
423
+ /** Payment amount in USDC */
424
+ amount: number;
425
+ /** Optional memo/description */
426
+ memo?: string;
427
+ /** Optional order ID for your records */
428
+ orderId?: string;
429
+ /** Button text/content (default: "Pay ${amount}") */
430
+ children?: ReactNode;
431
+ /** Called when payment succeeds */
432
+ onSuccess?: (result: {
433
+ signature: string;
434
+ amount: number;
435
+ merchantAddress: string;
436
+ }) => void;
437
+ /** Called when payment fails */
438
+ onError?: (error: Error) => void;
439
+ /** Called when payment starts processing */
440
+ onProcessing?: () => void;
441
+ /** Use redirect flow instead of direct payment */
442
+ useRedirect?: boolean;
443
+ /** Success URL for redirect flow */
444
+ successUrl?: string;
445
+ /** Cancel URL for redirect flow */
446
+ cancelUrl?: string;
447
+ /** Custom class name */
448
+ className?: string;
449
+ /** Custom styles */
450
+ style?: CSSProperties;
451
+ /** Disabled state */
452
+ disabled?: boolean;
453
+ /** Button variant */
454
+ variant?: "primary" | "secondary" | "outline";
455
+ /** Button size */
456
+ size?: "sm" | "md" | "lg";
457
+ }
458
+ declare function BuyButton({ amount, memo, orderId, children, onSuccess, onError, onProcessing, useRedirect, successUrl, cancelUrl, className, style, disabled, variant, size, }: BuyButtonProps): react_jsx_runtime.JSX.Element;
459
+ /**
460
+ * Checkout Widget - Embeddable checkout form
461
+ *
462
+ * @example
463
+ * ```tsx
464
+ * import { CheckoutWidget } from '@settlr/sdk';
465
+ *
466
+ * function CheckoutPage() {
467
+ * return (
468
+ * <CheckoutWidget
469
+ * amount={149.99}
470
+ * productName="Annual Subscription"
471
+ * productDescription="Full access to all premium features"
472
+ * onSuccess={(result) => {
473
+ * router.push('/success');
474
+ * }}
475
+ * />
476
+ * );
477
+ * }
478
+ * ```
479
+ */
480
+ interface CheckoutWidgetProps {
481
+ /** Payment amount in USDC */
482
+ amount: number;
483
+ /** Product/service name */
484
+ productName: string;
485
+ /** Optional description */
486
+ productDescription?: string;
487
+ /** Optional product image URL */
488
+ productImage?: string;
489
+ /** Merchant name (from config if not provided) */
490
+ merchantName?: string;
491
+ /** Optional memo for the transaction */
492
+ memo?: string;
493
+ /** Optional order ID */
494
+ orderId?: string;
495
+ /** Called when payment succeeds */
496
+ onSuccess?: (result: {
497
+ signature: string;
498
+ amount: number;
499
+ merchantAddress: string;
500
+ }) => void;
501
+ /** Called when payment fails */
502
+ onError?: (error: Error) => void;
503
+ /** Called when user cancels */
504
+ onCancel?: () => void;
505
+ /** Custom class name */
506
+ className?: string;
507
+ /** Custom styles */
508
+ style?: CSSProperties;
509
+ /** Theme */
510
+ theme?: "light" | "dark";
511
+ /** Show powered by Settlr badge */
512
+ showBranding?: boolean;
513
+ }
514
+ declare function CheckoutWidget({ amount, productName, productDescription, productImage, merchantName, memo, orderId, onSuccess, onError, onCancel, className, style, theme, showBranding, }: CheckoutWidgetProps): react_jsx_runtime.JSX.Element;
515
+ /**
516
+ * Payment Link Generator - Create shareable payment links
517
+ *
518
+ * @example
519
+ * ```tsx
520
+ * const { generateLink } = usePaymentLink({
521
+ * merchantWallet: 'YOUR_WALLET',
522
+ * merchantName: 'My Store',
523
+ * });
524
+ *
525
+ * const link = generateLink({
526
+ * amount: 29.99,
527
+ * memo: 'Order #1234',
528
+ * });
529
+ * // https://settlr.dev/pay?amount=29.99&merchant=My+Store&to=YOUR_WALLET&memo=Order+%231234
530
+ * ```
531
+ */
532
+ declare function usePaymentLink(config: {
533
+ merchantWallet: string;
534
+ merchantName: string;
535
+ baseUrl?: string;
536
+ }): {
537
+ generateLink: (options: {
538
+ amount: number;
539
+ memo?: string;
540
+ orderId?: string;
541
+ successUrl?: string;
542
+ cancelUrl?: string;
543
+ }) => string;
544
+ generateQRCode: (options: Parameters<(options: {
545
+ amount: number;
546
+ memo?: string;
547
+ orderId?: string;
548
+ successUrl?: string;
549
+ cancelUrl?: string;
550
+ }) => string>[0]) => Promise<string>;
551
+ };
552
+
553
+ /**
554
+ * Verify a webhook signature
555
+ * @param payload - The raw request body (string)
556
+ * @param signature - The signature from the X-Settlr-Signature header
557
+ * @param secret - Your webhook secret
558
+ * @returns Whether the signature is valid
559
+ */
560
+ declare function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean;
561
+ /**
562
+ * Parse and verify a webhook payload
563
+ * @param rawBody - The raw request body
564
+ * @param signature - The signature from headers
565
+ * @param secret - Your webhook secret
566
+ * @returns The parsed and verified payload
567
+ * @throws Error if signature is invalid
568
+ */
569
+ declare function parseWebhookPayload(rawBody: string, signature: string, secret: string): WebhookPayload;
570
+ /**
571
+ * Webhook event handler type
572
+ */
573
+ type WebhookHandler = (event: WebhookPayload) => Promise<void> | void;
574
+ /**
575
+ * Webhook event handlers map
576
+ */
577
+ interface WebhookHandlers {
578
+ 'payment.created'?: WebhookHandler;
579
+ 'payment.completed'?: WebhookHandler;
580
+ 'payment.failed'?: WebhookHandler;
581
+ 'payment.expired'?: WebhookHandler;
582
+ 'payment.refunded'?: WebhookHandler;
583
+ }
584
+ /**
585
+ * Create a webhook handler middleware
586
+ *
587
+ * @example Express.js
588
+ * ```typescript
589
+ * import express from 'express';
590
+ * import { createWebhookHandler } from '@settlr/sdk/webhooks';
591
+ *
592
+ * const app = express();
593
+ *
594
+ * app.post('/webhooks/settlr',
595
+ * express.raw({ type: 'application/json' }),
596
+ * createWebhookHandler({
597
+ * secret: process.env.SETTLR_WEBHOOK_SECRET!,
598
+ * handlers: {
599
+ * 'payment.completed': async (event) => {
600
+ * console.log('Payment completed:', event.payment.id);
601
+ * await fulfillOrder(event.payment.orderId);
602
+ * },
603
+ * 'payment.failed': async (event) => {
604
+ * console.log('Payment failed:', event.payment.id);
605
+ * await notifyCustomer(event.payment.orderId);
606
+ * },
607
+ * },
608
+ * })
609
+ * );
610
+ * ```
611
+ *
612
+ * @example Next.js API Route
613
+ * ```typescript
614
+ * // pages/api/webhooks/settlr.ts
615
+ * import { createWebhookHandler } from '@settlr/sdk/webhooks';
616
+ *
617
+ * export const config = { api: { bodyParser: false } };
618
+ *
619
+ * export default createWebhookHandler({
620
+ * secret: process.env.SETTLR_WEBHOOK_SECRET!,
621
+ * handlers: {
622
+ * 'payment.completed': async (event) => {
623
+ * await fulfillOrder(event.payment.orderId);
624
+ * },
625
+ * },
626
+ * });
627
+ * ```
628
+ */
629
+ declare function createWebhookHandler(options: {
630
+ secret: string;
631
+ handlers: WebhookHandlers;
632
+ onError?: (error: Error) => void;
633
+ }): (req: any, res: any) => Promise<void>;
634
+
635
+ export { BuyButton, type BuyButtonProps, CheckoutWidget, type CheckoutWidgetProps, type CreatePaymentOptions, type MerchantConfig, type Payment, type PaymentResult, type PaymentStatus, SETTLR_CHECKOUT_URL, SUPPORTED_NETWORKS, Settlr, type SettlrConfig, SettlrProvider, type TransactionOptions, USDC_MINT_DEVNET, USDC_MINT_MAINNET, type WebhookEventType, type WebhookHandler, type WebhookHandlers, type WebhookPayload, createWebhookHandler, formatUSDC, parseUSDC, parseWebhookPayload, shortenAddress, usePaymentLink, useSettlr, verifyWebhookSignature };