@rozoai/intent-common 0.1.0-beta.2 → 0.1.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/api/README.md DELETED
@@ -1,554 +0,0 @@
1
- # API Client Utility
2
-
3
- A clean, flexible TypeScript utility for handling API requests to the RozoAI API service.
4
-
5
- ## Overview
6
-
7
- This utility provides a modular approach to API requests with:
8
-
9
- - A base client for core HTTP operations
10
- - Endpoint-specific modules for domain operations
11
- - TypeScript interfaces for type safety
12
- - Configuration management for API URLs and tokens
13
- - Pre-configured defaults for RozoAI API
14
-
15
- ## Default Configuration
16
-
17
- The API client comes pre-configured with RozoAI production settings:
18
-
19
- ```typescript
20
- import { ROZO_API_URL, ROZO_API_TOKEN } from "@rozoai/intent-common";
21
-
22
- console.log(ROZO_API_URL); // "https://intentapiv2.rozo.ai/functions/v1"
23
- console.log(ROZO_API_TOKEN); // Pre-configured production token
24
- ```
25
-
26
- These defaults are automatically used by the API client, so you can start making requests immediately without any configuration.
27
-
28
- ## Structure
29
-
30
- ```bash
31
- api/
32
- ├── base.ts # Core API client functionality
33
- ├── fee.ts # Fee calculation endpoint
34
- ├── payment.ts # Payment-specific endpoints
35
- └── README.md # Documentation
36
- ```
37
-
38
- ## Base API Client
39
-
40
- The base client (`base.ts`) provides the foundation for all API requests:
41
-
42
- ```typescript
43
- import { apiClient, setApiConfig } from "@rozoai/intent-common";
44
-
45
- // Configure the API client (optional, uses defaults if not set)
46
- setApiConfig({
47
- baseUrl: "https://intentapiv2.rozo.ai/functions/v1",
48
- apiToken: "your-api-token",
49
- });
50
-
51
- // Make a GET request
52
- const response = await apiClient.get("/some-endpoint");
53
-
54
- // Make a POST request with data
55
- const response = await apiClient.post("/some-endpoint", { data: "value" });
56
-
57
- // Make a request with custom headers
58
- const response = await apiClient.get("/some-endpoint", {
59
- headers: { "Custom-Header": "value" },
60
- });
61
-
62
- // Make a request with query parameters
63
- const response = await apiClient.get("/some-endpoint", {
64
- params: { filter: "active", sort: "desc" },
65
- });
66
- ```
67
-
68
- ## Using Payment API
69
-
70
- The payment module provides typed functions for payment operations. The `createRozoPayment` function is the core method for creating cross-chain payments.
71
-
72
- ### Creating a Payment
73
-
74
- The `createRozoPayment` function requires a `PaymentRequestData` object with the following structure:
75
-
76
- ```typescript
77
- import {
78
- createRozoPayment,
79
- getRozoPayment,
80
- createPaymentBridgeConfig,
81
- mergedMetadata,
82
- PaymentRequestData,
83
- } from "@rozoai/intent-common";
84
-
85
- // Basic payment creation
86
- const handleSubmitPayment = async () => {
87
- // First, create payment bridge configuration
88
- // This determines the preferred payment method and destination
89
- // payInTokenAddress can be: USDC Base, USDC Polygon, USDC Solana, USDC Stellar, or USDT BNB
90
- const { preferred, destination } = createPaymentBridgeConfig({
91
- toChain: 8453, // Base chain
92
- toToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Base USDC
93
- toAddress: "0x1234567890123456789012345678901234567890",
94
- toUnits: "1000000", // 1 USDC (6 decimals)
95
- payInTokenAddress: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", // Polygon USDC
96
- });
97
-
98
- // Construct payment data
99
- const paymentData: PaymentRequestData = {
100
- appId: "your-app-id",
101
- display: {
102
- intent: "Pay for product",
103
- paymentValue: "1.00", // Display value in USD
104
- currency: "USD",
105
- },
106
- destination: {
107
- destinationAddress: destination.destinationAddress,
108
- chainId: destination.chainId,
109
- amountUnits: destination.amountUnits,
110
- tokenSymbol: destination.tokenSymbol,
111
- tokenAddress: destination.tokenAddress,
112
- },
113
- // Spread preferred payment configuration
114
- ...preferred,
115
- // Optional: external ID for tracking
116
- externalId: "order-123",
117
- // Optional: metadata
118
- metadata: {
119
- preferredChain: preferred.preferredChain,
120
- preferredToken: preferred.preferredToken,
121
- preferredTokenAddress: preferred.preferredTokenAddress,
122
- // Merge additional metadata
123
- ...mergedMetadata({
124
- customField: "value",
125
- }),
126
- },
127
- };
128
-
129
- // Create the payment
130
- const response = await createRozoPayment(paymentData);
131
-
132
- if (response.data) {
133
- console.log("Payment created:", response.data.id);
134
- console.log("Payment status:", response.data.status);
135
- console.log("Payment URL:", response.data.url);
136
- } else if (response.error) {
137
- console.error("Error creating payment:", response.error.message);
138
- }
139
- };
140
- ```
141
-
142
- ### Example: Pay Out to Stellar
143
-
144
- ```typescript
145
- // Paying out to a Stellar address
146
- const { preferred, destination } = createPaymentBridgeConfig({
147
- toStellarAddress: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", // REQUIRED: Stellar address
148
- toAddress: "0x1234567890123456789012345678901234567890", // REQUIRED: any valid EVM address
149
- // toChain and toToken are optional (default to USDC Base)
150
- toUnits: "1000000", // 1 USDC
151
- payInTokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Base USDC
152
- });
153
-
154
- const paymentData: PaymentRequestData = {
155
- appId: "your-app-id",
156
- display: {
157
- intent: "Pay to Stellar wallet",
158
- paymentValue: "1.00",
159
- currency: "USD",
160
- },
161
- ...preferred,
162
- destination,
163
- };
164
-
165
- const response = await createRozoPayment(paymentData);
166
- ```
167
-
168
- ### Example: Pay Out to Solana
169
-
170
- ```typescript
171
- // Paying out to a Solana address
172
- const { preferred, destination } = createPaymentBridgeConfig({
173
- toSolanaAddress: "So11111111111111111111111111111111111111112", // REQUIRED: Solana address
174
- toAddress: "0x1234567890123456789012345678901234567890", // REQUIRED: any valid EVM address
175
- // toChain and toToken are optional (default to USDC Base)
176
- toUnits: "1000000", // 1 USDC
177
- payInTokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Base USDC
178
- });
179
-
180
- const paymentData: PaymentRequestData = {
181
- appId: "your-app-id",
182
- display: {
183
- intent: "Pay to Solana wallet",
184
- paymentValue: "1.00",
185
- currency: "USD",
186
- },
187
- ...preferred,
188
- destination,
189
- };
190
-
191
- const response = await createRozoPayment(paymentData);
192
- ```
193
-
194
- ### Payment Request Data Structure
195
-
196
- The `PaymentRequestData` interface includes:
197
-
198
- - **`appId`** (required): Your application identifier
199
- - **`display`** (required): Payment display information
200
- - `intent`: Description of the payment
201
- - `paymentValue`: Amount as a string (e.g., "100.00")
202
- - `currency`: Currency code (e.g., "USD")
203
- - **`destination`** (required): Payment destination configuration
204
- - `destinationAddress`: Recipient address
205
- - `chainId`: Destination chain ID as string
206
- - `amountUnits`: Amount in smallest token unit (as string)
207
- - `tokenSymbol`: Token symbol (e.g., "USDC")
208
- - `tokenAddress`: Token contract address
209
- - **`preferredChain`** (optional): Preferred source chain ID
210
- - **`preferredToken`** (optional): Preferred source token symbol
211
- - **`preferredTokenAddress`** (optional): Preferred source token address
212
- - **`externalId`** (optional): External identifier for tracking
213
- - **`metadata`** (optional): Additional metadata object
214
-
215
- ### Using createPaymentBridgeConfig
216
-
217
- The `createPaymentBridgeConfig` helper function simplifies cross-chain payment configuration. It determines the preferred payment method based on the `payInTokenAddress` parameter.
218
-
219
- **Important Notes:**
220
-
221
- - **For EVM chain payouts (Base, Polygon, etc.)**: Provide `toAddress` with the destination EVM address. `toChain` and `toToken` are optional but default to USDC Base.
222
- - **For Stellar payouts**: You **must** provide `toStellarAddress` with the Stellar address. You **must** also provide `toAddress` with any valid EVM address (required for internal routing). `toChain` and `toToken` are optional but default to USDC Base.
223
- - **For Solana payouts**: You **must** provide `toSolanaAddress` with the Solana address. You **must** also provide `toAddress` with any valid EVM address (required for internal routing). `toChain` and `toToken` are optional but default to USDC Base.
224
-
225
- **Supported `payInTokenAddress` values:**
226
-
227
- - **USDC Base** - Base chain USDC token
228
- - **USDC Polygon** - Polygon chain USDC token
229
- - **USDC Solana** - Solana USDC token
230
- - **USDC Stellar** - Stellar USDC token (format: `USDC:issuerPK` or issuer public key)
231
- - **USDT BNB** - BSC (Binance Smart Chain) USDT token
232
-
233
- ```typescript
234
- import { createPaymentBridgeConfig } from "@rozoai/intent-common";
235
-
236
- // Example: User pays with Polygon USDC, receives on Base
237
- const { preferred, destination } = createPaymentBridgeConfig({
238
- toChain: 8453, // Base
239
- toToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Base USDC
240
- toAddress: "0x...",
241
- toUnits: "1000000", // 1 USDC
242
- payInTokenAddress: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", // Polygon USDC
243
- });
244
-
245
- // preferred contains: preferredChain, preferredToken, preferredTokenAddress
246
- // destination contains: destinationAddress, chainId, amountUnits, tokenSymbol, tokenAddress
247
- ```
248
-
249
- **More examples:**
250
-
251
- ```typescript
252
- // Pay with Base USDC
253
- const { preferred, destination } = createPaymentBridgeConfig({
254
- toChain: 8453,
255
- toToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
256
- toAddress: "0x...",
257
- toUnits: "1000000",
258
- payInTokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Base USDC
259
- });
260
-
261
- // Pay with Solana USDC - Pay Out to Solana
262
- // Note: toSolanaAddress is REQUIRED, toAddress is REQUIRED (any valid EVM address)
263
- // toChain and toToken are optional (default to USDC Base)
264
- const { preferred, destination } = createPaymentBridgeConfig({
265
- toSolanaAddress: "So11111111111111111111111111111111111111112", // Solana destination address
266
- toAddress: "0x1234567890123456789012345678901234567890", // Required: any valid EVM address
267
- // toChain and toToken are optional, default to USDC Base
268
- toUnits: "1000000",
269
- payInTokenAddress: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // Solana USDC
270
- });
271
-
272
- // Pay with Stellar USDC - Pay Out to Stellar
273
- // Note: toStellarAddress is REQUIRED, toAddress is REQUIRED (any valid EVM address)
274
- // toChain and toToken are optional (default to USDC Base)
275
- const { preferred, destination } = createPaymentBridgeConfig({
276
- toStellarAddress: "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", // Stellar destination address
277
- toAddress: "0x1234567890123456789012345678901234567890", // Required: any valid EVM address
278
- // toChain and toToken are optional, default to USDC Base
279
- toUnits: "1000000",
280
- payInTokenAddress:
281
- "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", // Stellar USDC
282
- });
283
-
284
- // Pay with BSC USDT
285
- const { preferred, destination } = createPaymentBridgeConfig({
286
- toChain: 8453,
287
- toToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
288
- toAddress: "0x...",
289
- toUnits: "1000000",
290
- payInTokenAddress: "0x55d398326f99059fF775485246999027B3197955", // BSC USDT
291
- });
292
- ```
293
-
294
- ### Getting Payment Details
295
-
296
- ```typescript
297
- // Get payment by ID
298
- const fetchPaymentDetails = async (paymentId: string) => {
299
- const response = await getRozoPayment(paymentId);
300
-
301
- if (response.data) {
302
- console.log("Payment status:", response.data.status);
303
- console.log("Payment intent:", response.data.display.intent);
304
- console.log(
305
- "Destination address:",
306
- response.data.destination.destinationAddress
307
- );
308
- console.log("Transaction hash:", response.data.destination.txHash);
309
- } else if (response.error) {
310
- console.error("Error fetching payment:", response.error.message);
311
- }
312
- };
313
- ```
314
-
315
- ### Real-World Usage Pattern
316
-
317
- In the SDK, `createRozoPayment` is typically used within payment flow effects:
318
-
319
- ```typescript
320
- // Example from paymentEffects.ts
321
- const paymentData: PaymentRequestData = {
322
- appId: payParams?.rozoAppId ?? payParams?.appId ?? DEFAULT_ROZO_APP_ID,
323
- display: {
324
- intent: order?.metadata?.intent ?? "",
325
- paymentValue: String(toUnits),
326
- currency: "USD",
327
- },
328
- ...preferred, // Spread preferred config from createPaymentBridgeConfig
329
- destination, // Destination config from createPaymentBridgeConfig
330
- externalId: order?.externalId ?? "",
331
- metadata: {
332
- preferredChain: preferred.preferredChain,
333
- preferredToken: preferred.preferredToken,
334
- preferredTokenAddress: preferred.preferredTokenAddress,
335
- ...mergedMetadata({
336
- ...(payParams?.metadata ?? {}),
337
- ...(order?.metadata ?? {}),
338
- ...(order.userMetadata ?? {}),
339
- }),
340
- },
341
- };
342
-
343
- const rozoPayment = await createRozoPayment(paymentData);
344
- if (!rozoPayment?.data?.id) {
345
- throw new Error(rozoPayment?.error?.message ?? "Payment creation failed");
346
- }
347
- ```
348
-
349
- ## React Hooks
350
-
351
- React hooks for these APIs are available in the `@rozoai/intent-pay` package. The SDK handles payment creation internally through the payment state machine, but you can access payment state using hooks:
352
-
353
- ```typescript
354
- // In @rozoai/intent-pay
355
- import { useRozoPay, useRozoPayStatus, useRozoPayUI } from "@rozoai/intent-pay";
356
-
357
- // Use in React components
358
- const PaymentComponent = () => {
359
- const { createPreviewOrder, payWallet } = useRozoPay();
360
- const { paymentStatus } = useRozoPayStatus();
361
- const { isOpen, openRozoPay, closeRozoPay } = useRozoPayUI();
362
-
363
- // Payment creation is handled internally by the SDK
364
- // when using RozoPayButton or calling createPreviewOrder
365
- // The SDK automatically uses createRozoPayment under the hood
366
-
367
- if (paymentStatus === "payment_completed") {
368
- return <div>Payment successful!</div>;
369
- }
370
-
371
- return <RozoPayButton {...paymentProps} />;
372
- };
373
- ```
374
-
375
- Note: The SDK's payment flow automatically handles `createRozoPayment` calls internally. You typically don't need to call it directly when using the SDK components.
376
-
377
- ## Error Handling
378
-
379
- All API responses include standardized error handling:
380
-
381
- ```typescript
382
- const response = await createRozoPayment(data);
383
-
384
- if (response.error) {
385
- // Handle error
386
- console.error("API Error:", response.error.message);
387
- return;
388
- }
389
-
390
- // Process successful response
391
- const paymentData = response.data;
392
- ```
393
-
394
- ## TypeScript Integration
395
-
396
- All functions are fully typed:
397
-
398
- ```typescript
399
- import { PaymentResponseData, ApiResponse } from "@rozoai/intent-common";
400
-
401
- const response: ApiResponse<PaymentResponseData> = await getRozoPayment(
402
- paymentId
403
- );
404
- // response.data will be typed as PaymentResponseData | null
405
- ```
406
-
407
- ## Configuration
408
-
409
- ### Using Default Configuration
410
-
411
- The API client is pre-configured with production RozoAI settings, so you can use it immediately:
412
-
413
- ```typescript
414
- import {
415
- createRozoPayment,
416
- createPaymentBridgeConfig,
417
- } from "@rozoai/intent-common";
418
-
419
- // Works out of the box with default configuration
420
- const { preferred, destination } = createPaymentBridgeConfig({
421
- toChain: 8453,
422
- toToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
423
- toAddress: "0x...",
424
- toUnits: "10000000",
425
- payInTokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
426
- });
427
-
428
- const response = await createRozoPayment({
429
- appId: "your-app-id",
430
- display: { intent: "Payment", paymentValue: "10.00", currency: "USD" },
431
- ...preferred,
432
- destination,
433
- });
434
- ```
435
-
436
- ### Customizing Configuration
437
-
438
- For testing, staging, or custom environments, you can override the defaults:
439
-
440
- ```typescript
441
- import {
442
- setApiConfig,
443
- getApiConfig,
444
- ROZO_API_URL,
445
- ROZO_API_TOKEN,
446
- } from "@rozoai/intent-common";
447
-
448
- // Override for staging environment
449
- setApiConfig({
450
- baseUrl: "https://staging-api.rozo.ai/v1",
451
- apiToken: "your-staging-token",
452
- });
453
-
454
- // Or reset to production defaults
455
- setApiConfig({
456
- baseUrl: ROZO_API_URL,
457
- apiToken: ROZO_API_TOKEN,
458
- });
459
-
460
- // Get current configuration
461
- const config = getApiConfig();
462
- console.log(config.baseUrl, config.apiToken);
463
- ```
464
-
465
- ### Configuration in Different Environments
466
-
467
- **Production (Default):**
468
-
469
- ```typescript
470
- // No configuration needed - uses ROZO_API_URL and ROZO_API_TOKEN automatically
471
- import { createRozoPayment } from "@rozoai/intent-common";
472
- const response = await createRozoPayment(data);
473
- ```
474
-
475
- **Staging:**
476
-
477
- ```typescript
478
- import { setApiConfig } from "@rozoai/intent-common";
479
-
480
- setApiConfig({
481
- baseUrl: "https://staging.intentapi.rozo.ai/v1",
482
- apiToken: process.env.STAGING_API_TOKEN,
483
- });
484
- ```
485
-
486
- **Development/Testing:**
487
-
488
- ```typescript
489
- import { setApiConfig } from "@rozoai/intent-common";
490
-
491
- setApiConfig({
492
- baseUrl: "http://localhost:3000/api",
493
- apiToken: "dev_token",
494
- });
495
- ```
496
-
497
- ## Using Fee API
498
-
499
- The fee module provides a function to calculate fees for payment amounts:
500
-
501
- ```typescript
502
- import { getFee } from "@rozoai/intent-common";
503
-
504
- // Get fee calculation (only amount is required)
505
- const calculateFee = async () => {
506
- const response = await getFee({
507
- amount: 0.1,
508
- // Optional parameters with defaults:
509
- // appId: "rozodemo",
510
- // currency: "USDC"
511
- });
512
-
513
- if (response.data) {
514
- console.log("Fee:", response.data.fee);
515
- console.log("Fee Percentage:", response.data.feePercentage);
516
- console.log("Amount Out:", response.data.amount_out);
517
- console.log("Minimum Fee:", response.data.minimumFee);
518
- } else if (response.error) {
519
- console.error("Error calculating fee:", response.error.message);
520
- // Error response includes details like max allowed amount
521
- }
522
- };
523
-
524
- // With custom appId and currency
525
- const response = await getFee({
526
- amount: 100,
527
- appId: "myapp",
528
- currency: "USDC",
529
- });
530
- ```
531
-
532
- ## Available Payment Functions
533
-
534
- - **`createRozoPayment(paymentData: PaymentRequestData)`** - Create a new cross-chain payment. Requires `appId`, `display`, and `destination`. Use `createPaymentBridgeConfig` to generate `preferred` and `destination` configurations. Returns `ApiResponse<PaymentResponseData>` with payment ID, status, and URL.
535
-
536
- - **`getRozoPayment(paymentId: string)`** - Get payment details by ID. Automatically handles both standard payment IDs and MugglePay order IDs. Returns `ApiResponse<PaymentResponseData>` with full payment information including status, destination, and transaction hashes.
537
-
538
- ### Helper Functions
539
-
540
- - **`createPaymentBridgeConfig(config: PaymentBridgeConfig)`** - Creates payment bridge configuration for cross-chain payments. Determines preferred payment method (source chain/token) and destination configuration. The `payInTokenAddress` parameter supports: USDC Base, USDC Polygon, USDC Solana, USDC Stellar, and USDT BNB. Returns `{ preferred: PreferredPaymentConfig, destination: DestinationConfig }`.
541
-
542
- - **`mergedMetadata(...metadataObjects)`** - Utility function to merge multiple metadata objects while handling conflicts and filtering sensitive fields.
543
-
544
- ## Available Fee Functions
545
-
546
- - `getFee(params)` - Calculate fee for a payment amount (amount required, appId and currency optional)
547
-
548
- ## Best Practices
549
-
550
- - Configure the API client once at app initialization
551
- - Leverage TypeScript interfaces for type safety
552
- - Handle loading, error, and success states properly
553
- - Use the React hooks (from @rozoai/intent-pay) when working in React components
554
- - Implement proper error handling for all API calls