@chainrails/react 0.1.5 → 0.1.6

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/README.md CHANGED
@@ -2,12 +2,32 @@
2
2
 
3
3
  React components and hooks for integrating Chainrails payments and blockchain utilities into your app.
4
4
 
5
+ ## What's New in v0.1.5 (January 2026)
6
+
7
+ ### Major Refactor: Session-Based Payment Flows
8
+
9
+ The payment modal integration has been completely redesigned around session tokens for improved security and flexibility:
10
+
11
+ - **New Hook**: `usePaymentSession` replaces `usePaymentModal` with full session lifecycle management
12
+ - **Enhanced Modal**: `PaymentModal` component now accepts session data with improved iframe communication
13
+ - **Better State Management**: Valtio-based reactive state for session data, tokens, and error handling
14
+ - **Automatic Expiration**: Built-in session expiration tracking with configurable callbacks
15
+ - **Message Protocol**: Secure cross-frame communication via postMessage API
16
+
17
+ ### New Features
18
+
19
+ - **Session Token Propagation**: Automatic secure passing of session tokens to iframe
20
+ - **Utility Functions**: New `convertToBaseUnits()` and `convertToNormalNumber()` helpers for token amount conversions
21
+ - **Enhanced Error Handling**: Better error state management and propagation
22
+ - **Improved TypeScript Support**: Full type definitions for session-based flows
23
+
5
24
  ## Features
6
25
 
7
- - **PaymentModal**: Drop-in modal for blockchain payments.
8
- - **usePaymentModal**: React hook for controlling the modal.
9
- - **Auto-included styles**: Importing the package automatically loads component CSS.
10
- - **Chainrails SDK access**: Re-exports Chainrails API and common utilities.
26
+ - **PaymentModal**: Drop-in modal for blockchain payments with session authentication
27
+ - **usePaymentSession**: Powerful React hook for complete session lifecycle management
28
+ - **Auto-included styles**: Importing the package automatically loads component CSS
29
+ - **Chainrails SDK access**: Re-exports Chainrails API and common utilities
30
+ - **Session Management**: Built-in session creation, expiration, and error handling
11
31
 
12
32
  ## Installation
13
33
 
@@ -19,43 +39,480 @@ pnpm add @chainrails/react
19
39
 
20
40
  ## Usage
21
41
 
42
+ ### Basic Usage with usePaymentSession
43
+
22
44
  ```tsx
23
- import { chains, tokens, PaymentModal, usePaymentModal, Chainrails } from "@chainrails/react"
45
+ import { chains, tokens, PaymentModal, usePaymentSession, Chainrails } from "@chainrails/react"
24
46
 
25
- Chainrails.config({ api_key: <ENTER_API_KEY> })
47
+ Chainrails.config({ api_key: "your_api_key" })
26
48
 
27
49
  function App() {
28
- const cr = usePaymentModal({
29
- to: "0xb25aa807118aa401896826147a6ecdaae91f2f90",
30
- chain: chains.BASE,
50
+ const session = usePaymentSession({
51
+ session_url: "http://localhost:4000/create-session",
52
+ destinationChain: chains.ARBITRUM,
31
53
  token: tokens.USDC,
54
+ recipient: "0xb25aa807118aa401896826147a6ecdaae91f2f90",
55
+ amount: 100,
32
56
  onSuccess: () => {
33
- console.log("Payment Successful")
57
+ console.log("Payment Successful!")
34
58
  },
59
+ onCancel: () => {
60
+ console.log("Payment Cancelled")
61
+ }
35
62
  })
36
63
 
37
64
  return (
38
65
  <div>
39
- <button onClick={cr.open}> Pay </button>
40
- <PaymentModal {...cr} amount={2} />
66
+ <button onClick={session.open}>Pay with Chainrails</button>
67
+ <PaymentModal
68
+ {...session}
69
+ data={session.data}
70
+ amount={100}
71
+ />
41
72
  </div>
42
73
  )
43
74
  }
75
+
76
+ export default App
44
77
  ```
45
78
 
46
- ## Style Customization
79
+ ### Advanced Usage: Custom Session Management
80
+
81
+ ```tsx
82
+ import { usePaymentSession, PaymentModal } from "@chainrails/react"
83
+
84
+ function PaymentFlow() {
85
+ const session = usePaymentSession({
86
+ session_url: process.env.VITE_SESSION_URL,
87
+ destinationChain: "BASE",
88
+ token: "USDC",
89
+ recipient: userAddress,
90
+ amount: paymentAmount,
91
+ onSuccess: async () => {
92
+ // Handle successful payment
93
+ await completeOrder()
94
+ session.close()
95
+ },
96
+ onCancel: () => {
97
+ // Handle cancellation
98
+ setPaymentCancelled(true)
99
+ }
100
+ })
47
101
 
48
- - Default styles are loaded automatically.
49
- - To override, add your own CSS with higher specificity or import your CSS after this package.
102
+ if (session.error) {
103
+ return <div>Error: {session.error}</div>
104
+ }
105
+
106
+ return (
107
+ <div>
108
+ <PaymentModal
109
+ {...session}
110
+ data={session.data}
111
+ isPending={session.isPending}
112
+ />
113
+ {session.isOpen ? (
114
+ <button onClick={session.close}>Cancel</button>
115
+ ) : (
116
+ <button onClick={session.open}>Open Payment</button>
117
+ )}
118
+ </div>
119
+ )
120
+ }
121
+ ```
122
+
123
+ ## API Reference
124
+
125
+ ### usePaymentSession Hook
126
+
127
+ Complete session-based payment flow management.
128
+
129
+ #### Parameters
130
+
131
+ ```typescript
132
+ interface UsePaymentSessionProps {
133
+ session_url: string // Endpoint to create sessions
134
+ destinationChain: chains // Target blockchain
135
+ token: tokens // Token to transfer
136
+ recipient: `0x${string}` // Recipient address
137
+ amount?: number // Transfer amount (optional)
138
+ onCancel?: () => void // Callback when payment cancelled
139
+ onSuccess?: () => void // Callback when payment succeeds
140
+ }
141
+ ```
142
+
143
+ #### Return Value
144
+
145
+ ```typescript
146
+ interface UsePaymentSessionReturn {
147
+ // State
148
+ data: {
149
+ sessionToken: string
150
+ sessionId: string
151
+ expiresAt: string
152
+ } | null
153
+ error: string | null
154
+ isPending: boolean
155
+ isOpen: boolean
156
+
157
+ // Methods
158
+ open: () => void // Open payment modal
159
+ close: () => void // Close payment modal
160
+ refresh: () => void // Refresh session
161
+ }
162
+ ```
163
+
164
+ #### Methods
165
+
166
+ - `open()` - Opens the payment modal and displays the payment interface
167
+ - `close()` - Closes the payment modal
168
+ - `refresh()` - Refreshes the session token (useful for extending expiration)
169
+
170
+ #### Properties
171
+
172
+ - `data` - Current session data including token and expiration
173
+ - `error` - Any error that occurred during session creation or management
174
+ - `isPending` - True while session is being created or updated
175
+ - `isOpen` - True when modal is currently visible
176
+
177
+ ### PaymentModal Component
178
+
179
+ Drop-in payment modal component with session support.
180
+
181
+ #### Props
182
+
183
+ ```typescript
184
+ interface PaymentModalProps extends React.HTMLAttributes<HTMLDivElement> {
185
+ // Required
186
+ recipient: string // Recipient address
187
+ destinationChain: string // Target blockchain
188
+ token: string // Token symbol
189
+ open: () => void // Function to open modal
190
+ close: () => void // Function to close modal
191
+ isOpen: boolean // Whether modal is open
192
+
193
+ // Optional
194
+ amount?: number // Payment amount
195
+ data?: { // Session data from usePaymentSession
196
+ sessionToken: string
197
+ expiresAt: string
198
+ sessionId: string
199
+ } | null
200
+ isPending?: boolean // Loading state
201
+ onCancel?: () => void // Callback on cancel
202
+ onSuccess?: () => void // Callback on success
203
+ }
204
+ ```
205
+
206
+ #### Features
207
+
208
+ - Automatic document overflow management (prevents body scroll)
209
+ - Secure iframe communication via postMessage
210
+ - Loading state during session token propagation
211
+ - Automatic closing on completion
212
+ - Customizable callbacks for success/cancel events
213
+
214
+ #### Styling
215
+
216
+ The component comes with built-in styles that are automatically imported. You can customize the appearance:
217
+
218
+ ```css
219
+ /* Override default styles */
220
+ .payment-modal-wrapper {
221
+ /* Your custom styles */
222
+ }
223
+
224
+ .payment-modal-wrapper.open {
225
+ /* Opened state */
226
+ }
227
+
228
+ .payment-modal-wrapper.closed {
229
+ /* Closed state */
230
+ }
231
+
232
+ .payment-modal-loader {
233
+ /* Loading spinner */
234
+ }
235
+ ```
236
+
237
+ ## Utility Functions
238
+
239
+ ### convertToBaseUnits
240
+
241
+ Converts human-readable token amounts to blockchain base units (wei for ETH, etc.).
242
+
243
+ ```typescript
244
+ import { convertToBaseUnits } from "@chainrails/react"
245
+
246
+ const weiAmount = convertToBaseUnits("1.5", 18) // "1500000000000000000"
247
+ const usdcAmount = convertToBaseUnits("100", 6) // "100000000"
248
+ ```
249
+
250
+ #### Parameters
251
+ - `amount: string | number` - Human-readable amount
252
+ - `decimals: number` - Token decimals (18 for ETH, 6 for USDC, etc.)
253
+
254
+ #### Returns
255
+ - `string` - Amount in base units
256
+
257
+ ### convertToNormalNumber
258
+
259
+ Converts blockchain base units to human-readable decimal numbers.
260
+
261
+ ```typescript
262
+ import { convertToNormalNumber } from "@chainrails/react"
263
+
264
+ const ethAmount = convertToNormalNumber("1500000000000000000", 18) // 1.5
265
+ const usdcAmount = convertToNormalNumber("100000000", 6) // 100
266
+ ```
267
+
268
+ #### Parameters
269
+ - `amount: string | number` - Amount in base units
270
+ - `decimals: number` - Token decimals
271
+
272
+ #### Returns
273
+ - `number` - Human-readable amount
274
+
275
+ ## Re-exported from SDK
276
+
277
+ The package re-exports commonly used utilities from `@chainrails/sdk`:
278
+
279
+ ```typescript
280
+ import {
281
+ chains, // Chain constants (ARBITRUM, BASE, etc.)
282
+ tokens, // Token constants (USDC, ETH, etc.)
283
+ Chainrails, // Configuration and environment
284
+ crapi, // Full SDK API
285
+ environment // Environment constants
286
+ } from "@chainrails/react"
287
+ ```
288
+
289
+ ## Styling
290
+
291
+ ### Default Styles
292
+
293
+ Default styles are automatically loaded when you import from the package:
294
+
295
+ ```typescript
296
+ import { PaymentModal } from "@chainrails/react"
297
+ // Styles are automatically included
298
+ ```
299
+
300
+ ### Customization
301
+
302
+ To override default styles, import your CSS after the package:
303
+
304
+ ```typescript
305
+ import { PaymentModal } from "@chainrails/react"
306
+ import "./custom-payment-styles.css" // Your overrides
307
+ ```
308
+
309
+ Or use higher CSS specificity:
310
+
311
+ ```css
312
+ .payment-modal-wrapper.custom-theme {
313
+ --primary-color: #your-color;
314
+ /* other overrides */
315
+ }
316
+ ```
317
+
318
+ ## Configuration
319
+
320
+ ### Environment Setup
321
+
322
+ Configure the SDK before using components:
323
+
324
+ ```typescript
325
+ import { Chainrails } from "@chainrails/react"
326
+
327
+ // Production
328
+ Chainrails.config({
329
+ api_key: process.env.REACT_APP_CHAINRAILS_API_KEY
330
+ })
331
+
332
+ // Or development/staging
333
+ Chainrails.config({
334
+ api_key: process.env.REACT_APP_CHAINRAILS_API_KEY,
335
+ env: "staging"
336
+ })
337
+ ```
338
+
339
+ ### Session URL Configuration
340
+
341
+ The session URL should point to your backend endpoint that creates sessions:
342
+
343
+ ```typescript
344
+ const session = usePaymentSession({
345
+ session_url: process.env.REACT_APP_SESSION_URL, // e.g., http://localhost:4000/create-session
346
+ // ... other config
347
+ })
348
+ ```
349
+
350
+ ## Breaking Changes from v0.0.x
351
+
352
+ If you're upgrading from an older version, note these breaking changes:
353
+
354
+ 1. **Hook Replacement**: `usePaymentModal` → `usePaymentSession`
355
+ ```typescript
356
+ // Old: usePaymentModal({ to, chain, token, ... })
357
+ // New: usePaymentSession({ session_url, destinationChain, token, recipient, ... })
358
+ ```
359
+
360
+ 2. **Session Data Required**: PaymentModal now requires session data
361
+ ```typescript
362
+ <PaymentModal {...session} data={session.data} />
363
+ ```
364
+
365
+ 3. **Parameter Changes**: Props have been renamed for clarity
366
+ - `to` → `recipient`
367
+ - `chain` → `destinationChain`
368
+ - New required: `session_url`
369
+
370
+ ## Examples
371
+
372
+ ### Example 1: E-commerce Integration
373
+
374
+ ```tsx
375
+ function CheckoutModal({ total, currency }) {
376
+ const session = usePaymentSession({
377
+ session_url: "/api/create-payment-session",
378
+ destinationChain: chains.BASE,
379
+ token: tokens[currency],
380
+ recipient: process.env.REACT_APP_MERCHANT_ADDRESS,
381
+ amount: total,
382
+ onSuccess: () => {
383
+ completeOrder()
384
+ sendConfirmationEmail()
385
+ }
386
+ })
387
+
388
+ return (
389
+ <>
390
+ <button onClick={session.open}>Proceed to Payment</button>
391
+ <PaymentModal {...session} data={session.data} />
392
+ </>
393
+ )
394
+ }
395
+ ```
396
+
397
+ ### Example 2: Multi-Chain Payment Option
398
+
399
+ ```tsx
400
+ function MultiChainPayment() {
401
+ const [selectedChain, setSelectedChain] = useState(chains.ARBITRUM)
402
+
403
+ const session = usePaymentSession({
404
+ session_url: "/api/sessions",
405
+ destinationChain: selectedChain,
406
+ token: tokens.USDC,
407
+ recipient: recipientAddress,
408
+ amount: 100
409
+ })
410
+
411
+ return (
412
+ <div>
413
+ <select onChange={(e) => setSelectedChain(e.target.value)}>
414
+ {Object.entries(chains).map(([key, value]) => (
415
+ <option key={key} value={value}>{key}</option>
416
+ ))}
417
+ </select>
418
+ <button onClick={session.open}>Pay on {selectedChain}</button>
419
+ <PaymentModal {...session} data={session.data} />
420
+ </div>
421
+ )
422
+ }
423
+ ```
424
+
425
+ ### Example 3: Error Handling
426
+
427
+ ```tsx
428
+ function SafePaymentFlow() {
429
+ const session = usePaymentSession({
430
+ session_url: "/api/create-session",
431
+ destinationChain: chains.BASE,
432
+ token: tokens.USDC,
433
+ recipient: recipientAddress,
434
+ onSuccess: () => showSuccessMessage(),
435
+ onCancel: () => showCancelledMessage()
436
+ })
437
+
438
+ if (session.error) {
439
+ return (
440
+ <div className="error">
441
+ <p>Failed to initialize payment: {session.error}</p>
442
+ <button onClick={session.refresh}>Retry</button>
443
+ </div>
444
+ )
445
+ }
446
+
447
+ return (
448
+ <>
449
+ <button onClick={session.open} disabled={session.isPending}>
450
+ {session.isPending ? "Loading..." : "Pay Now"}
451
+ </button>
452
+ <PaymentModal {...session} data={session.data} />
453
+ </>
454
+ )
455
+ }
456
+ ```
50
457
 
51
458
  ## Aliases & Monorepo
52
459
 
53
- - The package is aliased as `@chainrails/react` in Vite config for local development.
54
- - Styles and components are bundled for both dev and production.
460
+ - The package is aliased as `@chainrails/react` in Vite config for local development
461
+ - Styles and components are bundled for both dev and production
462
+ - Works seamlessly in monorepo setups
463
+
464
+ ## TypeScript Support
465
+
466
+ Full TypeScript support with complete type definitions:
467
+
468
+ ```typescript
469
+ import { usePaymentSession, PaymentModal } from "@chainrails/react"
470
+ import type { UsePaymentSessionProps } from "@chainrails/react"
471
+
472
+ const props: UsePaymentSessionProps = {
473
+ session_url: "...",
474
+ destinationChain: "BASE",
475
+ token: "USDC",
476
+ recipient: "0x...",
477
+ }
478
+ ```
479
+
480
+ ## Browser Support
481
+
482
+ - Modern browsers with ES2020+ support
483
+ - Requires:
484
+ - Fetch API
485
+ - SessionStorage
486
+ - postMessage API for iframe communication
487
+ - Web Components support (for modal)
488
+
489
+ ## Version History
490
+
491
+ **v0.1.5** (January 2026)
492
+ - Complete session-based payment flow refactor
493
+ - New usePaymentSession hook
494
+ - Enhanced PaymentModal component
495
+ - New utility functions
496
+ - Better error handling
497
+
498
+ **v0.0.28** and earlier
499
+ - Legacy usePaymentModal hook (deprecated)
500
+
501
+ ## Related Packages
502
+
503
+ - [`@chainrails/sdk`](../sdk/README.md) - Core SDK with all APIs
504
+ - [`@chainrails/common`](../common/README.md) - Shared types and utilities
505
+
506
+ ## License
507
+
508
+ MIT
509
+
510
+ ## Support
511
+
512
+ For issues and feature requests, visit:
513
+ https://github.com/horuslabsio/chainrails-sdk
55
514
 
56
- ## Exports
515
+ ---
57
516
 
58
- - `PaymentModal` React component for payments
59
- - `usePaymentModal` — Modal state management hook
60
- - `chains`, `tokens`, `Chainrails` — Blockchain utilities from `@chainrails/common`
61
- - `crapi` — Chainrails SDK API
517
+ **Last Updated**: January 6, 2026
518
+ **Current Version**: v0.1.5