@rozoai/intent-common 0.1.3 → 0.1.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.
@@ -1,483 +0,0 @@
1
- import { createPaymentBridgeConfig } from "../bridge-utils";
2
- import { getChainById } from "../chain";
3
- import { getKnownToken } from "../token";
4
- import { apiClient, ApiResponse, ApiVersion, setApiConfig } from "./base";
5
-
6
- /**
7
- * FeeType, Fee calculation type:
8
- * - exactIn (default): Fee deducted from input, recipient receives amount - fee
9
- * - exactOut: Fee added to input, recipient receives exact amount
10
- */
11
- export enum FeeType {
12
- ExactIn = "exactIn",
13
- ExactOut = "exactOut",
14
- }
15
-
16
- /**
17
- * PaymentStatus, Payment status
18
- */
19
- export enum PaymentStatus {
20
- PaymentBounced = "payment_bounced",
21
- PaymentCompleted = "payment_completed",
22
- PaymentExpired = "payment_expired",
23
- PaymentPayinCompleted = "payment_payin_completed",
24
- PaymentPayoutCompleted = "payment_payout_completed",
25
- PaymentRefunded = "payment_refunded",
26
- PaymentStarted = "payment_started",
27
- PaymentUnpaid = "payment_unpaid",
28
- }
29
-
30
- /**
31
- * PaymentErrorCode, Error code (only present when status is payment_bounced)
32
- */
33
- export enum PaymentErrorCode {
34
- AmountTooHigh = "amountTooHigh",
35
- AmountTooLow = "amountTooLow",
36
- ChainUnavailable = "chainUnavailable",
37
- InsufficientLiquidity = "insufficientLiquidity",
38
- InvalidRecipient = "invalidRecipient",
39
- MissingTrustline = "missingTrustline",
40
- NetworkError = "networkError",
41
- ProviderError = "providerError",
42
- ServiceMaintenance = "serviceMaintenance",
43
- }
44
-
45
- /**
46
- * DestinationRequest
47
- */
48
- export interface DestinationRequest {
49
- /**
50
- * Receive amount (required for type=exactOut).
51
- * For exactIn, this field is omitted in request and calculated in response.
52
- */
53
- amount?: string;
54
- chainId: number;
55
- /**
56
- * Final recipient's wallet address
57
- */
58
- receiverAddress: string;
59
- /**
60
- * Memo for Stellar/Solana destinations
61
- */
62
- receiverMemo?: string;
63
- /**
64
- * Override default token address
65
- */
66
- tokenAddress?: string;
67
- tokenSymbol: string;
68
- [property: string]: any;
69
- }
70
-
71
- /**
72
- * DisplayInfo
73
- */
74
- export interface DisplayInfo {
75
- /**
76
- * Display currency
77
- */
78
- currency: string;
79
- /**
80
- * Detailed description
81
- */
82
- description?: string;
83
- /**
84
- * Short title
85
- */
86
- title: string;
87
- [property: string]: any;
88
- }
89
-
90
- /**
91
- * SourceRequest
92
- */
93
- export interface SourceRequest {
94
- /**
95
- * Pay-in amount (required for type=exactIn).
96
- * For exactOut, this field is omitted in request and calculated in response.
97
- */
98
- amount?: string;
99
- chainId: number;
100
- /**
101
- * Override default token address
102
- */
103
- tokenAddress?: string;
104
- tokenSymbol: string;
105
- [property: string]: any;
106
- }
107
-
108
- /**
109
- * PaymentRequest
110
- */
111
- export interface CreatePaymentRequest {
112
- /**
113
- * Your application ID
114
- */
115
- appId: string;
116
- destination: DestinationRequest;
117
- display: DisplayInfo;
118
- /**
119
- * Custom metadata (max 4 KB recommended)
120
- */
121
- metadata?: { [key: string]: any };
122
- /**
123
- * Your order reference ID (for idempotency)
124
- */
125
- orderId?: string;
126
- source: SourceRequest;
127
- type?: FeeType;
128
- /**
129
- * Secret for HMAC-SHA256 signature verification.
130
- * If not provided, a unique secret is auto-generated.
131
- * The secret is returned in the response for you to store and use for verification.
132
- */
133
- webhookSecret?: string;
134
- /**
135
- * URL to receive payment status updates
136
- */
137
- webhookUrl?: string;
138
- [property: string]: any;
139
- }
140
-
141
- /**
142
- * DestinationResponse
143
- */
144
- export interface DestinationResponse {
145
- /**
146
- * Amount to be sent to recipient
147
- */
148
- amount?: string;
149
- chainId?: number;
150
- /**
151
- * Withdrawal confirmation time
152
- */
153
- confirmedAt?: Date;
154
- /**
155
- * Final recipient's wallet
156
- */
157
- receiverAddress?: string;
158
- /**
159
- * Memo for Stellar/Solana
160
- */
161
- receiverMemo?: string;
162
- /**
163
- * Token contract address
164
- */
165
- tokenAddress?: string;
166
- tokenSymbol?: string;
167
- /**
168
- * Withdrawal transaction hash
169
- */
170
- txHash?: string;
171
- [property: string]: any;
172
- }
173
-
174
- /**
175
- * SourceResponse
176
- */
177
- export interface SourceResponse {
178
- /**
179
- * Amount payer must send
180
- */
181
- amount?: string;
182
- /**
183
- * Actual amount received
184
- */
185
- amountReceived?: string;
186
- chainId?: number;
187
- /**
188
- * Deposit confirmation time
189
- */
190
- confirmedAt?: Date;
191
- /**
192
- * Fee amount
193
- */
194
- fee?: string;
195
- /**
196
- * **BRIDGE ADDRESS**: This is where you must send the payment.
197
- * The deposit address for the cross-chain bridge.
198
- */
199
- receiverAddress?: string;
200
- /**
201
- * **REQUIRED MEMO**: Must be included in transaction if present.
202
- * Required for Stellar (chainId: 1500) and Solana (chainId: 900) deposits.
203
- * The payment will fail if memo is not included when required.
204
- */
205
- receiverMemo?: string;
206
- /**
207
- * Payer's wallet address (populated after deposit)
208
- */
209
- senderAddress?: string;
210
- /**
211
- * Token contract address
212
- */
213
- tokenAddress?: string;
214
- tokenSymbol?: string;
215
- /**
216
- * Deposit transaction hash
217
- */
218
- txHash?: string;
219
- [property: string]: any;
220
- }
221
-
222
- /**
223
- * PaymentResponse
224
- */
225
- export interface PaymentResponse {
226
- /**
227
- * Your application ID
228
- */
229
- appId: string;
230
- /**
231
- * ISO 8601 timestamp
232
- */
233
- createdAt: Date;
234
- destination: DestinationResponse;
235
- display: DisplayInfo;
236
- errorCode: PaymentErrorCode | null;
237
- /**
238
- * ISO 8601 timestamp (when payment expires)
239
- */
240
- expiresAt: Date;
241
- /**
242
- * Payment ID
243
- */
244
- id: string;
245
- metadata: { [key: string]: any } | null;
246
- /**
247
- * Your order reference ID
248
- */
249
- orderId: string | null;
250
- source: SourceResponse;
251
- status: PaymentStatus;
252
- type: FeeType;
253
- /**
254
- * ISO 8601 timestamp
255
- */
256
- updatedAt: Date;
257
- /**
258
- * Secret for webhook signature verification.
259
- * Only present when webhookUrl was provided in the request.
260
- * Store this securely to verify incoming webhook signatures.
261
- */
262
- webhookSecret: string | null;
263
- [property: string]: any;
264
- }
265
-
266
- /**
267
- * Parameters for creating a new payment using the new backend interface
268
- */
269
- export interface CreateNewPaymentParams {
270
- /** App ID for authentication */
271
- appId: string;
272
- // Destination (where funds will be received)
273
- /** Destination chain ID (e.g., 8453 for Base, 900 for Solana, 1500 for Stellar) */
274
- toChain: number;
275
- /** Destination token address */
276
- toToken: string;
277
- /** Destination address - Can be EVM, Solana, or Stellar address */
278
- toAddress: string;
279
-
280
- // Preferred payment method (what user will pay with)
281
- /** Chain ID where user will pay from (e.g., 137 for Polygon, 8453 for Base) */
282
- preferredChain: number;
283
- /** Token address user will pay with */
284
- preferredTokenAddress: string;
285
-
286
- // Payment details
287
- /** Amount in human-readable units (e.g., "1" for 1 USDC, "0.5" for half a USDC) */
288
- toUnits?: string;
289
-
290
- // Optional fields
291
- /** Additional metadata to include */
292
- metadata?: Record<string, unknown>;
293
- /** Display title for the payment */
294
- title?: string;
295
- /** Display description for the payment */
296
- description?: string;
297
- /** Order reference ID (for idempotency) */
298
- orderId?: string;
299
- /** Fee calculation type (exactIn or exactOut) */
300
- feeType?: FeeType;
301
- /** Webhook URL to receive payment status updates */
302
- webhookUrl?: string;
303
- /** Secret for HMAC-SHA256 signature verification */
304
- webhookSecret?: string;
305
- /** Memo for Stellar/Solana destinations */
306
- receiverMemo?: string;
307
- /** API version to use (v1 or v2). Defaults to v2 */
308
- apiVersion?: ApiVersion;
309
- }
310
-
311
- /**
312
- * Creates a payment using the new backend interface
313
- *
314
- * This function creates a payment using the new backend API structure with
315
- * separate source and destination objects, enum-based chain IDs and token symbols.
316
- *
317
- * **IMPORTANT: After successfully creating a payment:**
318
- * - Send funds to the bridge address at `response.source.receiverAddress`
319
- * - If `response.source.receiverMemo` exists, it MUST be included in the transaction
320
- * (required for Stellar payments with preferredChain: 1500)
321
- *
322
- * @param params - Payment creation parameters
323
- * @returns Promise resolving to the payment response data
324
- * @throws Error if payment creation fails or required parameters are missing
325
- *
326
- * @example
327
- * ```typescript
328
- * // Simple same-chain payment
329
- * const payment = await createPayment({
330
- * toChain: 8453, // Base
331
- * toToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Base USDC
332
- * toAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
333
- * preferredChain: 8453, // User pays from Base
334
- * preferredTokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Base USDC
335
- * toUnits: "1", // 1 USDC
336
- * appId: "my-app-id",
337
- * title: "Payment",
338
- * });
339
- *
340
- * // Send funds to the bridge address
341
- * const bridgeAddress = payment.source.receiverAddress;
342
- * const bridgeMemo = payment.source.receiverMemo; // Required for Stellar
343
- * // ... perform transaction to bridgeAddress with memo (if exists)
344
- * ```
345
- */
346
- export async function createPayment(
347
- params: CreateNewPaymentParams
348
- ): Promise<PaymentResponse> {
349
- const {
350
- toChain,
351
- toToken,
352
- toAddress,
353
- preferredChain,
354
- preferredTokenAddress,
355
- toUnits,
356
- appId,
357
- metadata,
358
- title,
359
- description,
360
- orderId,
361
- feeType,
362
- webhookUrl,
363
- webhookSecret,
364
- receiverMemo,
365
- apiVersion,
366
- } = params;
367
-
368
- // Set API version if provided
369
- if (apiVersion) {
370
- setApiConfig({ version: apiVersion });
371
- }
372
-
373
- // Create payment bridge configuration
374
- const { preferred, destination } = createPaymentBridgeConfig({
375
- toChain,
376
- toToken,
377
- toAddress,
378
- toUnits: toUnits ?? "0",
379
- // Preferred payment method (what user will pay with)
380
- preferredChain,
381
- preferredTokenAddress,
382
- });
383
-
384
- const sourceChain = getChainById(Number(preferred.preferredChain));
385
- const sourceToken = getKnownToken(
386
- Number(preferred.preferredChain),
387
- preferred.preferredTokenAddress
388
- );
389
-
390
- const destinationChain = getChainById(Number(destination.chainId));
391
- const destinationToken = getKnownToken(
392
- Number(destination.chainId),
393
- destination.tokenAddress
394
- );
395
- const destinationAddress = destination.destinationAddress ?? toAddress;
396
-
397
- if (!sourceToken || !destinationToken) {
398
- throw new Error("Source or destination token not found");
399
- }
400
-
401
- // Build payment request data matching new backend interface
402
- const paymentData: CreatePaymentRequest = {
403
- appId,
404
- type: feeType ?? FeeType.ExactIn,
405
- ...(orderId ? { orderId } : {}),
406
- source: {
407
- chainId: sourceChain.chainId,
408
- tokenSymbol: sourceToken.symbol,
409
- amount: destination.amountUnits, // Use same amount for source
410
- ...(preferred.preferredTokenAddress
411
- ? { tokenAddress: preferred.preferredTokenAddress }
412
- : {}),
413
- },
414
- destination: {
415
- chainId: destinationChain.chainId,
416
- receiverAddress: destinationAddress,
417
- tokenSymbol: destinationToken.symbol,
418
- amount: destination.amountUnits,
419
- ...(destination.tokenAddress
420
- ? { tokenAddress: destination.tokenAddress }
421
- : {}),
422
- ...(receiverMemo ? { receiverMemo } : {}),
423
- },
424
- display: {
425
- currency: "USD",
426
- title: title ?? "Pay",
427
- ...(description ? { description } : {}),
428
- },
429
- metadata: {
430
- ...(metadata ?? {}),
431
- appId,
432
- },
433
- ...(webhookUrl ? { webhookUrl } : {}),
434
- ...(webhookSecret ? { webhookSecret } : {}),
435
- };
436
-
437
- if (apiVersion === "v1") {
438
- paymentData.display.intent = title ?? "Pay";
439
- paymentData.destination.amountUnits = destination.amountUnits;
440
- paymentData.destination.destinationAddress = destinationAddress;
441
- paymentData.preferredToken = sourceToken.symbol;
442
- paymentData.preferredChain = preferred.preferredChain;
443
- paymentData.preferredTokenAddress = preferred.preferredTokenAddress;
444
- }
445
-
446
- // Create payment via API
447
- const response = await apiClient.post<PaymentResponse>(
448
- "/payment-api",
449
- paymentData
450
- );
451
-
452
- if (!response?.data?.id) {
453
- throw new Error(response?.error?.message ?? "Payment creation failed");
454
- }
455
-
456
- return response.data;
457
- }
458
-
459
- /**
460
- * Gets payment details by ID using the new backend API
461
- * @param paymentId - Payment ID
462
- * @param apiVersion - Optional API version to use (v2 or v4). Defaults to v4
463
- * @returns Promise with payment response
464
- */
465
- export const getPayment = (
466
- paymentId: string,
467
- apiVersion?: ApiVersion
468
- ): Promise<ApiResponse<PaymentResponse>> => {
469
- // Set API version if provided
470
- if (apiVersion) {
471
- setApiConfig({ version: apiVersion });
472
- }
473
-
474
- if (apiVersion === "v1") {
475
- const isMugglePay = paymentId.includes("mugglepay_order");
476
- const endpoint = isMugglePay
477
- ? `/payment-api/${paymentId}`
478
- : `/payment/id/${paymentId}`;
479
- return apiClient.get<PaymentResponse>(endpoint);
480
- }
481
-
482
- return apiClient.get<PaymentResponse>(`/payment-api/payments/${paymentId}`);
483
- };
package/src/assert.ts DELETED
@@ -1,29 +0,0 @@
1
- import { debugJson } from "./debug";
2
-
3
- export function assert(condition: boolean, ...args: any[]): asserts condition {
4
- if (condition) return;
5
- let msg: string;
6
- if (args.length === 1 && typeof args[0] === "function") {
7
- msg = args[0]();
8
- } else {
9
- msg = args.map((a) => debugJson(a)).join(", ");
10
- }
11
- throw new Error("Assertion failed: " + msg);
12
- }
13
-
14
- export function assertNotNull<T>(
15
- value: T | null | undefined,
16
- ...args: any[]
17
- ): T {
18
- assert(value !== null && value !== undefined, ...args);
19
- return value;
20
- }
21
-
22
- export function assertEqual<T>(a: T, b: T, ...args: any[]): void {
23
- assert(a === b, ...args);
24
- }
25
-
26
- /** Used to compile-time check that switch statements are exhaustive, etc. */
27
- export function assertUnreachable(_: never): never {
28
- throw new Error("Unreachable");
29
- }