@txnlab/deflex 1.0.0-beta.1 → 1.0.0-beta.3
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 +27 -46
- package/dist/index.d.ts +43 -278
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +29 -314
- package/dist/index.js.map +1 -1
- package/package.json +2 -14
package/README.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
TypeScript/JavaScript SDK for [Deflex Order Router](https://txnlab.gitbook.io/deflex-api) - smart order routing and DEX aggregation on Algorand.
|
|
4
4
|
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
- **Deflex API Key** - Request an API key by emailing [support@txnlab.dev](mailto:support@txnlab.dev)
|
|
8
|
+
|
|
5
9
|
## Installation
|
|
6
10
|
|
|
7
11
|
```bash
|
|
@@ -67,13 +71,13 @@ const deflex = new DeflexClient({
|
|
|
67
71
|
|
|
68
72
|
### Get a Swap Quote
|
|
69
73
|
|
|
70
|
-
The [`newQuote()`](#deflexclientnewquote) method returns a [`DeflexQuote`](#deflexquote)
|
|
74
|
+
The [`newQuote()`](#deflexclientnewquote) method returns a [`DeflexQuote`](#deflexquote) object:
|
|
71
75
|
|
|
72
76
|
```typescript
|
|
73
77
|
// Basic quote
|
|
74
78
|
const quote = await deflex.newQuote({
|
|
75
|
-
|
|
76
|
-
|
|
79
|
+
fromASAID: 0, // ALGO
|
|
80
|
+
toASAID: 31566704, // USDC
|
|
77
81
|
amount: 1_000_000, // 1 ALGO
|
|
78
82
|
address: userAddress, // Required for auto opt-in detection
|
|
79
83
|
})
|
|
@@ -252,16 +256,16 @@ new DeflexClient(config: DeflexConfigParams)
|
|
|
252
256
|
|
|
253
257
|
#### DeflexClient.newQuote()
|
|
254
258
|
|
|
255
|
-
Fetch a swap quote and return a [`DeflexQuote`](#deflexquote)
|
|
259
|
+
Fetch a swap quote and return a [`DeflexQuote`](#deflexquote) object.
|
|
256
260
|
|
|
257
261
|
```typescript
|
|
258
|
-
async newQuote(params:
|
|
262
|
+
async newQuote(params: FetchQuoteParams): Promise<DeflexQuote>
|
|
259
263
|
```
|
|
260
264
|
|
|
261
265
|
| Parameter | Description | Type | Default |
|
|
262
266
|
| ------------------- | ------------------------------------------ | --------------------------------- | --------------- |
|
|
263
|
-
| `
|
|
264
|
-
| `
|
|
267
|
+
| `fromASAID` | Input asset ID | `bigint \| number` | **required** |
|
|
268
|
+
| `toASAID` | Output asset ID | `bigint \| number` | **required** |
|
|
265
269
|
| `amount` | Amount to swap in base units | `bigint \| number` | **required** |
|
|
266
270
|
| `type` | Quote type | `'fixed-input' \| 'fixed-output'` | `'fixed-input'` |
|
|
267
271
|
| `address` | User address (recommended for auto opt-in) | `string` | `undefined` |
|
|
@@ -280,7 +284,7 @@ async newSwap(config: SwapComposerConfig): Promise<SwapComposer>
|
|
|
280
284
|
|
|
281
285
|
| Parameter | Description | Type |
|
|
282
286
|
| ---------- | ------------------------------------------------- | --------------------------------------------------------------------------------------- |
|
|
283
|
-
| `quote` | Quote
|
|
287
|
+
| `quote` | Quote result or raw API response | `DeflexQuote \| FetchQuoteResponse` |
|
|
284
288
|
| `address` | Signer address | `string` |
|
|
285
289
|
| `slippage` | Slippage tolerance as percentage (e.g., 1 for 1%) | `number` |
|
|
286
290
|
| `signer` | Transaction signer function | `algosdk.TransactionSigner \| ((txns: algosdk.Transaction[]) => Promise<Uint8Array[]>)` |
|
|
@@ -300,16 +304,23 @@ async needsAssetOptIn(address: string, assetId: bigint | number): Promise<boolea
|
|
|
300
304
|
|
|
301
305
|
### DeflexQuote
|
|
302
306
|
|
|
303
|
-
|
|
307
|
+
Plain object returned by [`newQuote()`](#deflexclientnewquote). Extends the raw API response with additional metadata.
|
|
308
|
+
|
|
309
|
+
**Additional properties added by SDK:**
|
|
310
|
+
|
|
311
|
+
| Property | Description | Type |
|
|
312
|
+
| ----------- | ----------------------------------- | --------------------- |
|
|
313
|
+
| `quote` | Quoted amount (coerced to `bigint`) | `bigint` |
|
|
314
|
+
| `amount` | Original request amount | `bigint` |
|
|
315
|
+
| `address` | User address (if provided) | `string \| undefined` |
|
|
316
|
+
| `createdAt` | Timestamp when quote was created | `number` |
|
|
317
|
+
|
|
318
|
+
**All properties from API response:**
|
|
304
319
|
|
|
305
320
|
| Property | Description | Type |
|
|
306
321
|
| ------------------- | ------------------------------------------------ | ------------------------ |
|
|
307
|
-
| `
|
|
308
|
-
| `
|
|
309
|
-
| `address` | User address (if provided) | `string \| undefined` |
|
|
310
|
-
| `createdAt` | Timestamp when quote was created | `number` |
|
|
311
|
-
| `fromAssetId` | Input asset ID | `number` |
|
|
312
|
-
| `toAssetId` | Output asset ID | `number` |
|
|
322
|
+
| `fromASAID` | Input asset ID | `number` |
|
|
323
|
+
| `toASAID` | Output asset ID | `number` |
|
|
313
324
|
| `type` | Quote type (`'fixed-input'` or `'fixed-output'`) | `string` |
|
|
314
325
|
| `profit` | Profit information | `Profit` |
|
|
315
326
|
| `priceBaseline` | Baseline price without fees | `number` |
|
|
@@ -323,37 +334,7 @@ Wrapper class for quote responses returned by [`newQuote()`](#deflexclientnewquo
|
|
|
323
334
|
| `requiredAppOptIns` | Required app opt-ins | `number[]` |
|
|
324
335
|
| `txnPayload` | Encrypted transaction payload | `TxnPayload \| null` |
|
|
325
336
|
| `protocolFees` | Fees by protocol | `Record<string, number>` |
|
|
326
|
-
| `
|
|
327
|
-
|
|
328
|
-
#### DeflexQuote.getSlippageAmount()
|
|
329
|
-
|
|
330
|
-
Calculates the slippage-adjusted amount.
|
|
331
|
-
|
|
332
|
-
- For **fixed-input** swaps: Returns minimum output amount
|
|
333
|
-
- For **fixed-output** swaps: Returns maximum input amount
|
|
334
|
-
|
|
335
|
-
```typescript
|
|
336
|
-
getSlippageAmount(slippage: number): bigint
|
|
337
|
-
```
|
|
338
|
-
|
|
339
|
-
| Parameter | Description | Type |
|
|
340
|
-
| ---------- | ------------------------------------------------- | -------- |
|
|
341
|
-
| `slippage` | Slippage tolerance as percentage (e.g., 1 for 1%) | `number` |
|
|
342
|
-
|
|
343
|
-
**Example:**
|
|
344
|
-
|
|
345
|
-
```typescript
|
|
346
|
-
const quote = await deflex.newQuote({
|
|
347
|
-
fromAssetId: 0,
|
|
348
|
-
toAssetId: 31566704,
|
|
349
|
-
amount: 1_000_000,
|
|
350
|
-
type: 'fixed-input',
|
|
351
|
-
})
|
|
352
|
-
|
|
353
|
-
// Get minimum output with 1% slippage
|
|
354
|
-
const minOutput = quote.getSlippageAmount(1)
|
|
355
|
-
console.log(`Minimum you'll receive: ${minOutput}`)
|
|
356
|
-
```
|
|
337
|
+
| `timing` | Performance timing data | `unknown \| undefined` |
|
|
357
338
|
|
|
358
339
|
### SwapComposer
|
|
359
340
|
|
package/dist/index.d.ts
CHANGED
|
@@ -93,30 +93,7 @@ interface FetchQuoteParams {
|
|
|
93
93
|
/** Whether to include asset opt-in transaction (overrides config.autoOptIn if set) */
|
|
94
94
|
readonly optIn?: boolean;
|
|
95
95
|
/** Address of the account that will perform the swap (required if autoOptIn is enabled) */
|
|
96
|
-
readonly address?: string;
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Parameters for requesting a swap quote (class-based method)
|
|
100
|
-
*/
|
|
101
|
-
interface QuoteParams {
|
|
102
|
-
/** Input asset ID */
|
|
103
|
-
readonly fromAssetId: bigint | number;
|
|
104
|
-
/** Output asset ID */
|
|
105
|
-
readonly toAssetId: bigint | number;
|
|
106
|
-
/** Amount to swap (in base units) */
|
|
107
|
-
readonly amount: bigint | number;
|
|
108
|
-
/** Quote type (default: 'fixed-input') */
|
|
109
|
-
readonly type?: QuoteType;
|
|
110
|
-
/** Protocols to exclude from routing (default: []) */
|
|
111
|
-
readonly disabledProtocols?: readonly Protocol[];
|
|
112
|
-
/** Maximum transaction group size (default: 16) */
|
|
113
|
-
readonly maxGroupSize?: number;
|
|
114
|
-
/** Maximum depth of the route (default: 4) */
|
|
115
|
-
readonly maxDepth?: number;
|
|
116
|
-
/** Whether to include asset opt-in transaction (overrides config.autoOptIn if set) */
|
|
117
|
-
readonly optIn?: boolean;
|
|
118
|
-
/** Address of the account that will perform the swap (required if autoOptIn is enabled) */
|
|
119
|
-
readonly address?: string;
|
|
96
|
+
readonly address?: string | null;
|
|
120
97
|
}
|
|
121
98
|
/**
|
|
122
99
|
* Asset information from the Deflex API
|
|
@@ -225,6 +202,26 @@ interface FetchQuoteResponse {
|
|
|
225
202
|
/** Performance timing data */
|
|
226
203
|
readonly timing?: unknown;
|
|
227
204
|
}
|
|
205
|
+
/**
|
|
206
|
+
* Enhanced quote result returned by DeflexClient.newQuote()
|
|
207
|
+
*
|
|
208
|
+
* Extends the raw API response with additional metadata and type normalization.
|
|
209
|
+
*/
|
|
210
|
+
type DeflexQuote = Omit<FetchQuoteResponse, 'quote'> & {
|
|
211
|
+
/**
|
|
212
|
+
* The quoted output amount or input amount (coerced to bigint)
|
|
213
|
+
*
|
|
214
|
+
* For fixed-input swaps: This is the output amount you'll receive
|
|
215
|
+
* For fixed-output swaps: This is the input amount you'll need to provide
|
|
216
|
+
*/
|
|
217
|
+
readonly quote: bigint;
|
|
218
|
+
/** The original amount from the quote request (in base units) */
|
|
219
|
+
readonly amount: bigint;
|
|
220
|
+
/** The address parameter from the quote request (if provided) */
|
|
221
|
+
readonly address?: string;
|
|
222
|
+
/** Timestamp when the quote was created (in milliseconds) */
|
|
223
|
+
readonly createdAt: number;
|
|
224
|
+
};
|
|
228
225
|
/**
|
|
229
226
|
* Transaction signature from the Deflex API
|
|
230
227
|
*/
|
|
@@ -251,8 +248,8 @@ interface DeflexTransaction {
|
|
|
251
248
|
* Parameters for fetching executable swap transactions
|
|
252
249
|
*/
|
|
253
250
|
interface FetchSwapTxnsParams {
|
|
254
|
-
/** Quote response from fetchQuote() */
|
|
255
|
-
readonly quote: FetchQuoteResponse;
|
|
251
|
+
/** Quote response from fetchQuote() or newQuote() */
|
|
252
|
+
readonly quote: FetchQuoteResponse | DeflexQuote;
|
|
256
253
|
/** Algorand address that will sign the transactions */
|
|
257
254
|
readonly address: string;
|
|
258
255
|
/** Slippage tolerance as a percentage (e.g., 1 for 1%) */
|
|
@@ -320,8 +317,8 @@ declare enum SwapComposerStatus {
|
|
|
320
317
|
* Configuration for creating a SwapComposer instance
|
|
321
318
|
*/
|
|
322
319
|
interface SwapComposerConfig {
|
|
323
|
-
/** The quote response from fetchQuote() */
|
|
324
|
-
readonly quote: FetchQuoteResponse;
|
|
320
|
+
/** The quote response from fetchQuote() or newQuote() */
|
|
321
|
+
readonly quote: FetchQuoteResponse | DeflexQuote;
|
|
325
322
|
/** The swap transactions from fetchSwapTransactions() */
|
|
326
323
|
readonly deflexTxns: DeflexTransaction[];
|
|
327
324
|
/** AlgorandClient instance for blockchain operations */
|
|
@@ -357,7 +354,7 @@ declare class SwapComposer {
|
|
|
357
354
|
private swapTransactionsAdded;
|
|
358
355
|
private signedTxns;
|
|
359
356
|
private txIds;
|
|
360
|
-
private readonly
|
|
357
|
+
private readonly requiredAppOptIns;
|
|
361
358
|
private readonly deflexTxns;
|
|
362
359
|
private readonly algorand;
|
|
363
360
|
private readonly address;
|
|
@@ -369,7 +366,7 @@ declare class SwapComposer {
|
|
|
369
366
|
* this directly, as the factory method handles fetching swap transactions automatically.
|
|
370
367
|
*
|
|
371
368
|
* @param config - Configuration for the composer
|
|
372
|
-
* @param config.
|
|
369
|
+
* @param config.requiredAppOptIns - The quote response from fetchQuote()
|
|
373
370
|
* @param config.deflexTxns - The swap transactions from fetchSwapTransactions()
|
|
374
371
|
* @param config.algorand - AlgorandClient instance for blockchain operations
|
|
375
372
|
* @param config.address - The address of the account that will sign transactions
|
|
@@ -493,230 +490,6 @@ declare class SwapComposer {
|
|
|
493
490
|
private signDeflexTransaction;
|
|
494
491
|
}
|
|
495
492
|
//#endregion
|
|
496
|
-
//#region src/quote.d.ts
|
|
497
|
-
/**
|
|
498
|
-
* Configuration for creating a DeflexQuote instance
|
|
499
|
-
*/
|
|
500
|
-
interface DeflexQuoteConfig {
|
|
501
|
-
/** The raw quote response from the Deflex API */
|
|
502
|
-
response: FetchQuoteResponse;
|
|
503
|
-
/** The original amount from the quote request */
|
|
504
|
-
amount: bigint | number;
|
|
505
|
-
/** Optional address parameter from the quote request */
|
|
506
|
-
address?: string;
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* Wrapper class for Deflex quote responses with convenience methods
|
|
510
|
-
*
|
|
511
|
-
* The DeflexQuote class provides a developer-friendly interface for working with
|
|
512
|
-
* swap quotes from the Deflex API. It exposes all quote properties via getters
|
|
513
|
-
* and provides additional convenience methods for derived data.
|
|
514
|
-
*
|
|
515
|
-
* @example
|
|
516
|
-
* ```typescript
|
|
517
|
-
* const quote = await deflex.newQuote({
|
|
518
|
-
* address: 'ABC...',
|
|
519
|
-
* fromAssetId: 0,
|
|
520
|
-
* toAssetId: 31566704,
|
|
521
|
-
* amount: 1_000_000,
|
|
522
|
-
* })
|
|
523
|
-
*
|
|
524
|
-
* // Access quote properties directly
|
|
525
|
-
* console.log(quote.quote) // bigint (quoted amount)
|
|
526
|
-
* console.log(quote.fromAssetId) // number
|
|
527
|
-
* console.log(quote.toAssetId) // number
|
|
528
|
-
*
|
|
529
|
-
* // Access metadata
|
|
530
|
-
* console.log(quote.amount) // bigint (original request amount)
|
|
531
|
-
* console.log(quote.address) // string | undefined
|
|
532
|
-
* console.log(quote.createdAt) // number
|
|
533
|
-
*
|
|
534
|
-
* // Use convenience methods for derived data
|
|
535
|
-
* const minReceivedAmount = quote.getSlippageAmount(slippage) // fixed-input swap
|
|
536
|
-
* const maxSentAmount = quote.getSlippageAmount(slippage) // fixed-output swap
|
|
537
|
-
* ```
|
|
538
|
-
*/
|
|
539
|
-
declare class DeflexQuote {
|
|
540
|
-
private readonly _response;
|
|
541
|
-
private readonly _amount;
|
|
542
|
-
private readonly _address?;
|
|
543
|
-
private readonly _createdAt;
|
|
544
|
-
/**
|
|
545
|
-
* Create a new DeflexQuote instance
|
|
546
|
-
*
|
|
547
|
-
* Note: Most developers should use DeflexClient.newQuote() instead of constructing
|
|
548
|
-
* this directly, as the factory method handles fetching the quote automatically.
|
|
549
|
-
*
|
|
550
|
-
* @param config - Configuration for the quote instance
|
|
551
|
-
* @param config.response - The raw quote response from the Deflex API
|
|
552
|
-
* @param config.amount - The original amount from the quote request
|
|
553
|
-
* @param config.address - Optional address parameter from the quote request
|
|
554
|
-
*/
|
|
555
|
-
constructor(config: DeflexQuoteConfig);
|
|
556
|
-
/**
|
|
557
|
-
* Get the raw quote response from the Deflex API
|
|
558
|
-
*
|
|
559
|
-
* @returns The raw quote response from the Deflex API
|
|
560
|
-
*/
|
|
561
|
-
get response(): FetchQuoteResponse;
|
|
562
|
-
/**
|
|
563
|
-
* The original amount from the quote request (in base units)
|
|
564
|
-
*
|
|
565
|
-
* This is the amount that was provided when fetching the quote.
|
|
566
|
-
* For fixed-input swaps, this is the input amount.
|
|
567
|
-
* For fixed-output swaps, this is the desired output amount.
|
|
568
|
-
*
|
|
569
|
-
* @example
|
|
570
|
-
* ```typescript
|
|
571
|
-
* const quote = await deflex.newQuote({
|
|
572
|
-
* fromAssetId: 0,
|
|
573
|
-
* toAssetId: 31566704,
|
|
574
|
-
* amount: 1_000_000, // 1 ALGO
|
|
575
|
-
* type: 'fixed-input'
|
|
576
|
-
* })
|
|
577
|
-
* console.log(quote.amount) // 1000000n (input amount)
|
|
578
|
-
* console.log(quote.quote) // 5000000n (output amount quoted)
|
|
579
|
-
* ```
|
|
580
|
-
*/
|
|
581
|
-
get amount(): bigint;
|
|
582
|
-
/**
|
|
583
|
-
* The address parameter from the quote request
|
|
584
|
-
*
|
|
585
|
-
* This is the address that was provided when fetching the quote (if any).
|
|
586
|
-
* Useful for tracking which account the quote was fetched for, especially
|
|
587
|
-
* when using autoOptIn functionality.
|
|
588
|
-
*/
|
|
589
|
-
get address(): string | undefined;
|
|
590
|
-
/**
|
|
591
|
-
* Timestamp when the quote was created (in milliseconds)
|
|
592
|
-
*
|
|
593
|
-
* Can be used to determine quote freshness. Quotes may become stale
|
|
594
|
-
* over time as market conditions change.
|
|
595
|
-
*
|
|
596
|
-
* @example
|
|
597
|
-
* ```typescript
|
|
598
|
-
* const ageInSeconds = (Date.now() - quote.createdAt) / 1000
|
|
599
|
-
* if (ageInSeconds > 30) {
|
|
600
|
-
* console.log('Quote may be stale, consider refreshing')
|
|
601
|
-
* }
|
|
602
|
-
* ```
|
|
603
|
-
*/
|
|
604
|
-
get createdAt(): number;
|
|
605
|
-
/**
|
|
606
|
-
* The quoted output amount or input amount (depending on quote type)
|
|
607
|
-
*
|
|
608
|
-
* For fixed-input swaps: This is the output amount you'll receive
|
|
609
|
-
* For fixed-output swaps: This is the input amount you'll need to provide
|
|
610
|
-
*
|
|
611
|
-
* @returns The quote amount as a bigint in base units
|
|
612
|
-
*/
|
|
613
|
-
get quote(): bigint;
|
|
614
|
-
/**
|
|
615
|
-
* Profit information for the swap
|
|
616
|
-
*/
|
|
617
|
-
get profit(): Profit;
|
|
618
|
-
/**
|
|
619
|
-
* Baseline price without fees
|
|
620
|
-
*/
|
|
621
|
-
get priceBaseline(): number;
|
|
622
|
-
/**
|
|
623
|
-
* Price impact for the user
|
|
624
|
-
*/
|
|
625
|
-
get userPriceImpact(): number | undefined;
|
|
626
|
-
/**
|
|
627
|
-
* Overall market price impact
|
|
628
|
-
*/
|
|
629
|
-
get marketPriceImpact(): number | undefined;
|
|
630
|
-
/**
|
|
631
|
-
* USD value of input amount
|
|
632
|
-
*/
|
|
633
|
-
get usdIn(): number;
|
|
634
|
-
/**
|
|
635
|
-
* USD value of output amount
|
|
636
|
-
*/
|
|
637
|
-
get usdOut(): number;
|
|
638
|
-
/**
|
|
639
|
-
* The routing path(s) for the swap
|
|
640
|
-
*/
|
|
641
|
-
get route(): Route[];
|
|
642
|
-
/**
|
|
643
|
-
* Flattened view of routing percentages by protocol
|
|
644
|
-
*/
|
|
645
|
-
get flattenedRoute(): Record<string, number>;
|
|
646
|
-
/**
|
|
647
|
-
* Individual quotes from each DEX
|
|
648
|
-
*/
|
|
649
|
-
get quotes(): DexQuote[];
|
|
650
|
-
/**
|
|
651
|
-
* App IDs that require opt-in for this swap
|
|
652
|
-
*/
|
|
653
|
-
get requiredAppOptIns(): number[];
|
|
654
|
-
/**
|
|
655
|
-
* Encrypted transaction payload for generating swap transactions
|
|
656
|
-
*/
|
|
657
|
-
get txnPayload(): TxnPayload | null;
|
|
658
|
-
/**
|
|
659
|
-
* Fees charged by each protocol
|
|
660
|
-
*/
|
|
661
|
-
get protocolFees(): Record<string, number>;
|
|
662
|
-
/**
|
|
663
|
-
* Input asset ID
|
|
664
|
-
*/
|
|
665
|
-
get fromAssetId(): number;
|
|
666
|
-
/**
|
|
667
|
-
* Output asset ID
|
|
668
|
-
*/
|
|
669
|
-
get toAssetId(): number;
|
|
670
|
-
/**
|
|
671
|
-
* Quote type
|
|
672
|
-
*/
|
|
673
|
-
get type(): string;
|
|
674
|
-
/**
|
|
675
|
-
* Performance timing data
|
|
676
|
-
*/
|
|
677
|
-
get timing(): unknown | undefined;
|
|
678
|
-
/**
|
|
679
|
-
* Calculate the slippage-adjusted amount
|
|
680
|
-
*
|
|
681
|
-
* For fixed-input swaps: Returns the minimum amount you'll receive after slippage
|
|
682
|
-
* For fixed-output swaps: Returns the maximum amount you'll need to send after slippage
|
|
683
|
-
*
|
|
684
|
-
* @param slippage - Slippage tolerance as a percentage (e.g., 1 for 1%)
|
|
685
|
-
* @returns The slippage-adjusted amount as a bigint
|
|
686
|
-
*
|
|
687
|
-
* @example
|
|
688
|
-
* ```typescript
|
|
689
|
-
* // Fixed-input swap: 1 ALGO -> USDC
|
|
690
|
-
* const quote = await deflex.newQuote({
|
|
691
|
-
* fromAssetId: 0,
|
|
692
|
-
* toAssetId: 31566704,
|
|
693
|
-
* amount: 1_000_000,
|
|
694
|
-
* type: 'fixed-input'
|
|
695
|
-
* })
|
|
696
|
-
*
|
|
697
|
-
* // Get minimum output with 1% slippage
|
|
698
|
-
* const minOutput = quote.getSlippageAmount(1)
|
|
699
|
-
* console.log(`Minimum you'll receive: ${minOutput}`)
|
|
700
|
-
* ```
|
|
701
|
-
*
|
|
702
|
-
* @example
|
|
703
|
-
* ```typescript
|
|
704
|
-
* // Fixed-output swap: ALGO -> 10 USDC
|
|
705
|
-
* const quote = await deflex.newQuote({
|
|
706
|
-
* fromAssetId: 0,
|
|
707
|
-
* toAssetId: 31566704,
|
|
708
|
-
* amount: 10_000_000,
|
|
709
|
-
* type: 'fixed-output'
|
|
710
|
-
* })
|
|
711
|
-
*
|
|
712
|
-
* // Get maximum input with 1% slippage
|
|
713
|
-
* const maxInput = quote.getSlippageAmount(1)
|
|
714
|
-
* console.log(`Maximum you'll need to send: ${maxInput}`)
|
|
715
|
-
* ```
|
|
716
|
-
*/
|
|
717
|
-
getSlippageAmount(slippage: number): bigint;
|
|
718
|
-
}
|
|
719
|
-
//#endregion
|
|
720
493
|
//#region src/client.d.ts
|
|
721
494
|
/**
|
|
722
495
|
* Client for interacting with the Deflex order router API
|
|
@@ -836,14 +609,14 @@ declare class DeflexClient {
|
|
|
836
609
|
*/
|
|
837
610
|
fetchSwapTransactions(params: FetchSwapTxnsParams): Promise<FetchSwapTxnsResponse>;
|
|
838
611
|
/**
|
|
839
|
-
* Fetch a quote and return
|
|
612
|
+
* Fetch a quote and return an enhanced quote result
|
|
840
613
|
*
|
|
841
|
-
* This is the recommended way to fetch quotes. It
|
|
842
|
-
*
|
|
614
|
+
* This is the recommended way to fetch quotes. It returns an object that
|
|
615
|
+
* extends the raw API response with additional metadata and type normalization.
|
|
843
616
|
*
|
|
844
617
|
* @param params - Parameters for the quote request
|
|
845
|
-
* @param params.
|
|
846
|
-
* @param params.
|
|
618
|
+
* @param params.fromASAID - The ID of the asset to swap from
|
|
619
|
+
* @param params.toASAID - The ID of the asset to swap to
|
|
847
620
|
* @param params.amount - The amount of the asset to swap in base units
|
|
848
621
|
* @param params.type - The type of the quote (default: 'fixed-input')
|
|
849
622
|
* @param params.disabledProtocols - List of protocols to disable (default: [])
|
|
@@ -851,33 +624,25 @@ declare class DeflexClient {
|
|
|
851
624
|
* @param params.maxDepth - The maximum depth (default: 4)
|
|
852
625
|
* @param params.address - The address of the account that will perform the swap (recommended when using `config.autoOptIn` or `params.optIn`)
|
|
853
626
|
* @param params.optIn - Whether to include asset opt-in transaction
|
|
854
|
-
* @returns A DeflexQuote
|
|
627
|
+
* @returns A DeflexQuote enhanced quote result
|
|
855
628
|
*
|
|
856
629
|
* @example
|
|
857
630
|
* ```typescript
|
|
858
631
|
* const quote = await deflex.newQuote({
|
|
859
632
|
* address: 'ABC...',
|
|
860
|
-
*
|
|
861
|
-
*
|
|
633
|
+
* fromASAID: 0,
|
|
634
|
+
* toASAID: 31566704,
|
|
862
635
|
* amount: 1_000_000,
|
|
863
636
|
* })
|
|
864
637
|
*
|
|
865
|
-
* //
|
|
866
|
-
* console.log(quote.
|
|
867
|
-
* console.log(quote.
|
|
868
|
-
* console.log(quote.
|
|
869
|
-
*
|
|
870
|
-
* // Access metadata
|
|
871
|
-
* console.log(quote.amount) // bigint (original request amount)
|
|
872
|
-
* console.log(quote.address) // string | undefined
|
|
873
|
-
* console.log(quote.createdAt) // number
|
|
874
|
-
*
|
|
875
|
-
* // Use convenience methods
|
|
876
|
-
* const minReceivedAmount = quote.getSlippageAmount(slippage) // fixed-input swap
|
|
877
|
-
* const maxSentAmount = quote.getSlippageAmount(slippage) // fixed-output swap
|
|
638
|
+
* console.log(quote.quote) // bigint - quoted amount
|
|
639
|
+
* console.log(quote.fromASAID) // number - input asset ID
|
|
640
|
+
* console.log(quote.toASAID) // number - output asset ID
|
|
641
|
+
* console.log(quote.amount) // bigint - original request amount
|
|
642
|
+
* console.log(quote.createdAt) // number - timestamp
|
|
878
643
|
* ```
|
|
879
644
|
*/
|
|
880
|
-
newQuote(params:
|
|
645
|
+
newQuote(params: FetchQuoteParams): Promise<DeflexQuote>;
|
|
881
646
|
/**
|
|
882
647
|
* Create a SwapComposer instance
|
|
883
648
|
*
|
|
@@ -885,7 +650,7 @@ declare class DeflexClient {
|
|
|
885
650
|
* before and after the swap transactions, with automatic handling of pre-signed transactions
|
|
886
651
|
* and opt-ins.
|
|
887
652
|
*
|
|
888
|
-
* @param config.quote - The quote
|
|
653
|
+
* @param config.quote - The quote result from newQuote() or raw API response from fetchQuote()
|
|
889
654
|
* @param config.address - The address of the signer
|
|
890
655
|
* @param config.slippage - The slippage tolerance
|
|
891
656
|
* @param config.signer - Transaction signer function
|
|
@@ -969,5 +734,5 @@ declare class HTTPError extends Error {
|
|
|
969
734
|
*/
|
|
970
735
|
declare function request<T>(url: string, options?: RequestInit): Promise<T>;
|
|
971
736
|
//#endregion
|
|
972
|
-
export { Asset, DEFAULT_ALGOD_PORT, DEFAULT_ALGOD_TOKEN, DEFAULT_ALGOD_URI, DEFAULT_API_BASE_URL, DEFAULT_AUTO_OPT_IN, DEFAULT_CONFIRMATION_ROUNDS, DEFAULT_FEE_BPS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_GROUP_SIZE, DEPRECATED_PROTOCOLS, DeflexClient, DeflexConfig, DeflexConfigParams, DeflexQuote,
|
|
737
|
+
export { Asset, DEFAULT_ALGOD_PORT, DEFAULT_ALGOD_TOKEN, DEFAULT_ALGOD_URI, DEFAULT_API_BASE_URL, DEFAULT_AUTO_OPT_IN, DEFAULT_CONFIRMATION_ROUNDS, DEFAULT_FEE_BPS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_GROUP_SIZE, DEPRECATED_PROTOCOLS, DeflexClient, DeflexConfig, DeflexConfigParams, DeflexQuote, DeflexSignature, DeflexTransaction, DexQuote, FetchQuoteParams, FetchQuoteResponse, FetchSwapTxnsBody, FetchSwapTxnsParams, FetchSwapTxnsResponse, HTTPError, MAX_FEE_BPS, PathElement, Profit, Protocol, QuoteType, Route, SignerFunction, SwapComposer, SwapComposerConfig, SwapComposerStatus, SwapTransaction, TxnPayload, request };
|
|
973
738
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/constants.ts","../src/types.ts","../src/composer.ts","../src/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/constants.ts","../src/types.ts","../src/composer.ts","../src/client.ts","../src/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;aAGY,QAAA;EAAA,SAAA,GAAQ,WAAA;EAcP,MAAA,GAAA,QAAA;EAGA,QAAA,GAAA,UAAiB;EAGjB,IAAA,GAAA,MAAA;EAGA,KAAA,GAAA,OAAA;EAGA,KAAA,GAAA,OAAA;AAGb;AAGA;AAGA;AAGA;AAGA;AAGA;cA9Ba;;cAGA,iBAAA;ACdb;AA4BY,cDXC,mBAAA,GCWW,EAAA;;AACtB,cDTW,kBAAA,GCSX,GAAA;;AAD6B,cDLlB,oBAAA,GCKkB,+BAAA;AAU/B;AAKiB,cDjBJ,eAAA,GC4BK,EAAA;AAqBlB;AAkBiB,cDhEJ,WAAA,GCoEQ,GAAA;AAMrB;AAciB,cDrFJ,sBAAA,GCyFe,EAAA;AAM5B;AAYiB,cDxGJ,iBAAA,GCwGc,CAAA;AAU3B;AAImB,cDnHN,mBAAA,GCmHM,KAAA;;AAcQ,cD9Hd,2BAAA,GC8Hc,CAAA;;;;;AD1K3B;AAca,UCXI,kBAAA,CDWiD;EAGrD;EAGA,SAAA,MAAA,EAAA,MAAmB;EAGnB;EAGA,SAAA,QAAA,CAAA,EAAA,MAAoB;EAGpB;EAGA,SAAA,UAAW,CAAA,EAAA,MAAA;EAGX;EAGA,SAAA,SAAA,CAAA,EAAiB,MAAA,GAAA,MAAA;EAGjB;EAGA,SAAA,eAAA,CAAA,EAAA,MAA2B;;;;ECzCvB,SAAA,SAAA,CAAA,EAAkB,OAAA;AA4BnC;;;;;AAUA;AAKiB,KAfL,YAAA,GAAe,IAeM,CAd/B,QAyBgB,CAzBP,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AAA,EAAA,MAAA,EAAA,IAAA,EAAA,OAAA;AAGhC;AAGA;AAGA;AAGA;AAGA;AAGA;AAGA;AAGA;;;;ACzCA;AA4BY,iBGTU,OHSE,CAAA,CAAA,CAAA,CAAA,GAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EGPZ,WHOY,CAAA,EGNrB,OHMqB,CGNb,CHMa,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -85,7 +85,7 @@ var SwapComposer = class SwapComposer {
|
|
|
85
85
|
swapTransactionsAdded = false;
|
|
86
86
|
signedTxns = [];
|
|
87
87
|
txIds = [];
|
|
88
|
-
|
|
88
|
+
requiredAppOptIns;
|
|
89
89
|
deflexTxns;
|
|
90
90
|
algorand;
|
|
91
91
|
address;
|
|
@@ -97,7 +97,7 @@ var SwapComposer = class SwapComposer {
|
|
|
97
97
|
* this directly, as the factory method handles fetching swap transactions automatically.
|
|
98
98
|
*
|
|
99
99
|
* @param config - Configuration for the composer
|
|
100
|
-
* @param config.
|
|
100
|
+
* @param config.requiredAppOptIns - The quote response from fetchQuote()
|
|
101
101
|
* @param config.deflexTxns - The swap transactions from fetchSwapTransactions()
|
|
102
102
|
* @param config.algorand - AlgorandClient instance for blockchain operations
|
|
103
103
|
* @param config.address - The address of the account that will sign transactions
|
|
@@ -109,7 +109,7 @@ var SwapComposer = class SwapComposer {
|
|
|
109
109
|
if (config.deflexTxns.length === 0) throw new Error("Swap transactions array cannot be empty");
|
|
110
110
|
if (!config.algorand) throw new Error("AlgorandClient instance is required");
|
|
111
111
|
if (!config.signer) throw new Error("Signer is required");
|
|
112
|
-
this.
|
|
112
|
+
this.requiredAppOptIns = config.quote.requiredAppOptIns;
|
|
113
113
|
this.deflexTxns = config.deflexTxns;
|
|
114
114
|
this.algorand = config.algorand;
|
|
115
115
|
this.address = this.validateAddress(config.address);
|
|
@@ -309,7 +309,7 @@ var SwapComposer = class SwapComposer {
|
|
|
309
309
|
*/
|
|
310
310
|
async processRequiredAppOptIns() {
|
|
311
311
|
const userApps = (await this.algorand.account.getInformation(this.address))?.appsLocalState?.map((app) => Number(app.id)) || [];
|
|
312
|
-
const appsToOptIn = this.
|
|
312
|
+
const appsToOptIn = this.requiredAppOptIns.filter((appId) => !userApps.includes(appId));
|
|
313
313
|
const appOptInTxns = [];
|
|
314
314
|
if (appsToOptIn.length > 0) {
|
|
315
315
|
const suggestedParams = await this.algorand.client.algod.getTransactionParams().do();
|
|
@@ -358,275 +358,6 @@ var SwapComposer = class SwapComposer {
|
|
|
358
358
|
}
|
|
359
359
|
};
|
|
360
360
|
|
|
361
|
-
//#endregion
|
|
362
|
-
//#region src/quote.ts
|
|
363
|
-
/**
|
|
364
|
-
* Wrapper class for Deflex quote responses with convenience methods
|
|
365
|
-
*
|
|
366
|
-
* The DeflexQuote class provides a developer-friendly interface for working with
|
|
367
|
-
* swap quotes from the Deflex API. It exposes all quote properties via getters
|
|
368
|
-
* and provides additional convenience methods for derived data.
|
|
369
|
-
*
|
|
370
|
-
* @example
|
|
371
|
-
* ```typescript
|
|
372
|
-
* const quote = await deflex.newQuote({
|
|
373
|
-
* address: 'ABC...',
|
|
374
|
-
* fromAssetId: 0,
|
|
375
|
-
* toAssetId: 31566704,
|
|
376
|
-
* amount: 1_000_000,
|
|
377
|
-
* })
|
|
378
|
-
*
|
|
379
|
-
* // Access quote properties directly
|
|
380
|
-
* console.log(quote.quote) // bigint (quoted amount)
|
|
381
|
-
* console.log(quote.fromAssetId) // number
|
|
382
|
-
* console.log(quote.toAssetId) // number
|
|
383
|
-
*
|
|
384
|
-
* // Access metadata
|
|
385
|
-
* console.log(quote.amount) // bigint (original request amount)
|
|
386
|
-
* console.log(quote.address) // string | undefined
|
|
387
|
-
* console.log(quote.createdAt) // number
|
|
388
|
-
*
|
|
389
|
-
* // Use convenience methods for derived data
|
|
390
|
-
* const minReceivedAmount = quote.getSlippageAmount(slippage) // fixed-input swap
|
|
391
|
-
* const maxSentAmount = quote.getSlippageAmount(slippage) // fixed-output swap
|
|
392
|
-
* ```
|
|
393
|
-
*/
|
|
394
|
-
var DeflexQuote = class {
|
|
395
|
-
_response;
|
|
396
|
-
_amount;
|
|
397
|
-
_address;
|
|
398
|
-
_createdAt;
|
|
399
|
-
/**
|
|
400
|
-
* Create a new DeflexQuote instance
|
|
401
|
-
*
|
|
402
|
-
* Note: Most developers should use DeflexClient.newQuote() instead of constructing
|
|
403
|
-
* this directly, as the factory method handles fetching the quote automatically.
|
|
404
|
-
*
|
|
405
|
-
* @param config - Configuration for the quote instance
|
|
406
|
-
* @param config.response - The raw quote response from the Deflex API
|
|
407
|
-
* @param config.amount - The original amount from the quote request
|
|
408
|
-
* @param config.address - Optional address parameter from the quote request
|
|
409
|
-
*/
|
|
410
|
-
constructor(config) {
|
|
411
|
-
if (!config?.response) throw new Error("Quote response is required");
|
|
412
|
-
if (config.amount === void 0 || config.amount === null) throw new Error("Amount is required");
|
|
413
|
-
this._response = config.response;
|
|
414
|
-
this._amount = BigInt(config.amount);
|
|
415
|
-
this._address = config.address;
|
|
416
|
-
this._createdAt = Date.now();
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* Get the raw quote response from the Deflex API
|
|
420
|
-
*
|
|
421
|
-
* @returns The raw quote response from the Deflex API
|
|
422
|
-
*/
|
|
423
|
-
get response() {
|
|
424
|
-
return this._response;
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* The original amount from the quote request (in base units)
|
|
428
|
-
*
|
|
429
|
-
* This is the amount that was provided when fetching the quote.
|
|
430
|
-
* For fixed-input swaps, this is the input amount.
|
|
431
|
-
* For fixed-output swaps, this is the desired output amount.
|
|
432
|
-
*
|
|
433
|
-
* @example
|
|
434
|
-
* ```typescript
|
|
435
|
-
* const quote = await deflex.newQuote({
|
|
436
|
-
* fromAssetId: 0,
|
|
437
|
-
* toAssetId: 31566704,
|
|
438
|
-
* amount: 1_000_000, // 1 ALGO
|
|
439
|
-
* type: 'fixed-input'
|
|
440
|
-
* })
|
|
441
|
-
* console.log(quote.amount) // 1000000n (input amount)
|
|
442
|
-
* console.log(quote.quote) // 5000000n (output amount quoted)
|
|
443
|
-
* ```
|
|
444
|
-
*/
|
|
445
|
-
get amount() {
|
|
446
|
-
return this._amount;
|
|
447
|
-
}
|
|
448
|
-
/**
|
|
449
|
-
* The address parameter from the quote request
|
|
450
|
-
*
|
|
451
|
-
* This is the address that was provided when fetching the quote (if any).
|
|
452
|
-
* Useful for tracking which account the quote was fetched for, especially
|
|
453
|
-
* when using autoOptIn functionality.
|
|
454
|
-
*/
|
|
455
|
-
get address() {
|
|
456
|
-
return this._address;
|
|
457
|
-
}
|
|
458
|
-
/**
|
|
459
|
-
* Timestamp when the quote was created (in milliseconds)
|
|
460
|
-
*
|
|
461
|
-
* Can be used to determine quote freshness. Quotes may become stale
|
|
462
|
-
* over time as market conditions change.
|
|
463
|
-
*
|
|
464
|
-
* @example
|
|
465
|
-
* ```typescript
|
|
466
|
-
* const ageInSeconds = (Date.now() - quote.createdAt) / 1000
|
|
467
|
-
* if (ageInSeconds > 30) {
|
|
468
|
-
* console.log('Quote may be stale, consider refreshing')
|
|
469
|
-
* }
|
|
470
|
-
* ```
|
|
471
|
-
*/
|
|
472
|
-
get createdAt() {
|
|
473
|
-
return this._createdAt;
|
|
474
|
-
}
|
|
475
|
-
/**
|
|
476
|
-
* The quoted output amount or input amount (depending on quote type)
|
|
477
|
-
*
|
|
478
|
-
* For fixed-input swaps: This is the output amount you'll receive
|
|
479
|
-
* For fixed-output swaps: This is the input amount you'll need to provide
|
|
480
|
-
*
|
|
481
|
-
* @returns The quote amount as a bigint in base units
|
|
482
|
-
*/
|
|
483
|
-
get quote() {
|
|
484
|
-
const rawQuote = this._response.quote;
|
|
485
|
-
return rawQuote === "" ? 0n : BigInt(rawQuote);
|
|
486
|
-
}
|
|
487
|
-
/**
|
|
488
|
-
* Profit information for the swap
|
|
489
|
-
*/
|
|
490
|
-
get profit() {
|
|
491
|
-
return this._response.profit;
|
|
492
|
-
}
|
|
493
|
-
/**
|
|
494
|
-
* Baseline price without fees
|
|
495
|
-
*/
|
|
496
|
-
get priceBaseline() {
|
|
497
|
-
return this._response.priceBaseline;
|
|
498
|
-
}
|
|
499
|
-
/**
|
|
500
|
-
* Price impact for the user
|
|
501
|
-
*/
|
|
502
|
-
get userPriceImpact() {
|
|
503
|
-
return this._response.userPriceImpact;
|
|
504
|
-
}
|
|
505
|
-
/**
|
|
506
|
-
* Overall market price impact
|
|
507
|
-
*/
|
|
508
|
-
get marketPriceImpact() {
|
|
509
|
-
return this._response.marketPriceImpact;
|
|
510
|
-
}
|
|
511
|
-
/**
|
|
512
|
-
* USD value of input amount
|
|
513
|
-
*/
|
|
514
|
-
get usdIn() {
|
|
515
|
-
return this._response.usdIn;
|
|
516
|
-
}
|
|
517
|
-
/**
|
|
518
|
-
* USD value of output amount
|
|
519
|
-
*/
|
|
520
|
-
get usdOut() {
|
|
521
|
-
return this._response.usdOut;
|
|
522
|
-
}
|
|
523
|
-
/**
|
|
524
|
-
* The routing path(s) for the swap
|
|
525
|
-
*/
|
|
526
|
-
get route() {
|
|
527
|
-
return this._response.route;
|
|
528
|
-
}
|
|
529
|
-
/**
|
|
530
|
-
* Flattened view of routing percentages by protocol
|
|
531
|
-
*/
|
|
532
|
-
get flattenedRoute() {
|
|
533
|
-
return this._response.flattenedRoute;
|
|
534
|
-
}
|
|
535
|
-
/**
|
|
536
|
-
* Individual quotes from each DEX
|
|
537
|
-
*/
|
|
538
|
-
get quotes() {
|
|
539
|
-
return this._response.quotes;
|
|
540
|
-
}
|
|
541
|
-
/**
|
|
542
|
-
* App IDs that require opt-in for this swap
|
|
543
|
-
*/
|
|
544
|
-
get requiredAppOptIns() {
|
|
545
|
-
return this._response.requiredAppOptIns;
|
|
546
|
-
}
|
|
547
|
-
/**
|
|
548
|
-
* Encrypted transaction payload for generating swap transactions
|
|
549
|
-
*/
|
|
550
|
-
get txnPayload() {
|
|
551
|
-
return this._response.txnPayload;
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Fees charged by each protocol
|
|
555
|
-
*/
|
|
556
|
-
get protocolFees() {
|
|
557
|
-
return this._response.protocolFees;
|
|
558
|
-
}
|
|
559
|
-
/**
|
|
560
|
-
* Input asset ID
|
|
561
|
-
*/
|
|
562
|
-
get fromAssetId() {
|
|
563
|
-
return this._response.fromASAID;
|
|
564
|
-
}
|
|
565
|
-
/**
|
|
566
|
-
* Output asset ID
|
|
567
|
-
*/
|
|
568
|
-
get toAssetId() {
|
|
569
|
-
return this._response.toASAID;
|
|
570
|
-
}
|
|
571
|
-
/**
|
|
572
|
-
* Quote type
|
|
573
|
-
*/
|
|
574
|
-
get type() {
|
|
575
|
-
return this._response.type;
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* Performance timing data
|
|
579
|
-
*/
|
|
580
|
-
get timing() {
|
|
581
|
-
return this._response.timing;
|
|
582
|
-
}
|
|
583
|
-
/**
|
|
584
|
-
* Calculate the slippage-adjusted amount
|
|
585
|
-
*
|
|
586
|
-
* For fixed-input swaps: Returns the minimum amount you'll receive after slippage
|
|
587
|
-
* For fixed-output swaps: Returns the maximum amount you'll need to send after slippage
|
|
588
|
-
*
|
|
589
|
-
* @param slippage - Slippage tolerance as a percentage (e.g., 1 for 1%)
|
|
590
|
-
* @returns The slippage-adjusted amount as a bigint
|
|
591
|
-
*
|
|
592
|
-
* @example
|
|
593
|
-
* ```typescript
|
|
594
|
-
* // Fixed-input swap: 1 ALGO -> USDC
|
|
595
|
-
* const quote = await deflex.newQuote({
|
|
596
|
-
* fromAssetId: 0,
|
|
597
|
-
* toAssetId: 31566704,
|
|
598
|
-
* amount: 1_000_000,
|
|
599
|
-
* type: 'fixed-input'
|
|
600
|
-
* })
|
|
601
|
-
*
|
|
602
|
-
* // Get minimum output with 1% slippage
|
|
603
|
-
* const minOutput = quote.getSlippageAmount(1)
|
|
604
|
-
* console.log(`Minimum you'll receive: ${minOutput}`)
|
|
605
|
-
* ```
|
|
606
|
-
*
|
|
607
|
-
* @example
|
|
608
|
-
* ```typescript
|
|
609
|
-
* // Fixed-output swap: ALGO -> 10 USDC
|
|
610
|
-
* const quote = await deflex.newQuote({
|
|
611
|
-
* fromAssetId: 0,
|
|
612
|
-
* toAssetId: 31566704,
|
|
613
|
-
* amount: 10_000_000,
|
|
614
|
-
* type: 'fixed-output'
|
|
615
|
-
* })
|
|
616
|
-
*
|
|
617
|
-
* // Get maximum input with 1% slippage
|
|
618
|
-
* const maxInput = quote.getSlippageAmount(1)
|
|
619
|
-
* console.log(`Maximum you'll need to send: ${maxInput}`)
|
|
620
|
-
* ```
|
|
621
|
-
*/
|
|
622
|
-
getSlippageAmount(slippage) {
|
|
623
|
-
const quoteAmount = this.quote;
|
|
624
|
-
const slippageBps = BigInt(Math.floor(slippage * 100));
|
|
625
|
-
if (this._response.type === "fixed-input") return quoteAmount * (10000n - slippageBps) / 10000n;
|
|
626
|
-
else return quoteAmount * (10000n + slippageBps) / 10000n;
|
|
627
|
-
}
|
|
628
|
-
};
|
|
629
|
-
|
|
630
361
|
//#endregion
|
|
631
362
|
//#region src/utils.ts
|
|
632
363
|
/**
|
|
@@ -845,14 +576,14 @@ var DeflexClient = class {
|
|
|
845
576
|
});
|
|
846
577
|
}
|
|
847
578
|
/**
|
|
848
|
-
* Fetch a quote and return
|
|
579
|
+
* Fetch a quote and return an enhanced quote result
|
|
849
580
|
*
|
|
850
|
-
* This is the recommended way to fetch quotes. It
|
|
851
|
-
*
|
|
581
|
+
* This is the recommended way to fetch quotes. It returns an object that
|
|
582
|
+
* extends the raw API response with additional metadata and type normalization.
|
|
852
583
|
*
|
|
853
584
|
* @param params - Parameters for the quote request
|
|
854
|
-
* @param params.
|
|
855
|
-
* @param params.
|
|
585
|
+
* @param params.fromASAID - The ID of the asset to swap from
|
|
586
|
+
* @param params.toASAID - The ID of the asset to swap to
|
|
856
587
|
* @param params.amount - The amount of the asset to swap in base units
|
|
857
588
|
* @param params.type - The type of the quote (default: 'fixed-input')
|
|
858
589
|
* @param params.disabledProtocols - List of protocols to disable (default: [])
|
|
@@ -860,48 +591,33 @@ var DeflexClient = class {
|
|
|
860
591
|
* @param params.maxDepth - The maximum depth (default: 4)
|
|
861
592
|
* @param params.address - The address of the account that will perform the swap (recommended when using `config.autoOptIn` or `params.optIn`)
|
|
862
593
|
* @param params.optIn - Whether to include asset opt-in transaction
|
|
863
|
-
* @returns A DeflexQuote
|
|
594
|
+
* @returns A DeflexQuote enhanced quote result
|
|
864
595
|
*
|
|
865
596
|
* @example
|
|
866
597
|
* ```typescript
|
|
867
598
|
* const quote = await deflex.newQuote({
|
|
868
599
|
* address: 'ABC...',
|
|
869
|
-
*
|
|
870
|
-
*
|
|
600
|
+
* fromASAID: 0,
|
|
601
|
+
* toASAID: 31566704,
|
|
871
602
|
* amount: 1_000_000,
|
|
872
603
|
* })
|
|
873
604
|
*
|
|
874
|
-
* //
|
|
875
|
-
* console.log(quote.
|
|
876
|
-
* console.log(quote.
|
|
877
|
-
* console.log(quote.
|
|
878
|
-
*
|
|
879
|
-
* // Access metadata
|
|
880
|
-
* console.log(quote.amount) // bigint (original request amount)
|
|
881
|
-
* console.log(quote.address) // string | undefined
|
|
882
|
-
* console.log(quote.createdAt) // number
|
|
883
|
-
*
|
|
884
|
-
* // Use convenience methods
|
|
885
|
-
* const minReceivedAmount = quote.getSlippageAmount(slippage) // fixed-input swap
|
|
886
|
-
* const maxSentAmount = quote.getSlippageAmount(slippage) // fixed-output swap
|
|
605
|
+
* console.log(quote.quote) // bigint - quoted amount
|
|
606
|
+
* console.log(quote.fromASAID) // number - input asset ID
|
|
607
|
+
* console.log(quote.toASAID) // number - output asset ID
|
|
608
|
+
* console.log(quote.amount) // bigint - original request amount
|
|
609
|
+
* console.log(quote.createdAt) // number - timestamp
|
|
887
610
|
* ```
|
|
888
611
|
*/
|
|
889
612
|
async newQuote(params) {
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
maxDepth: params.maxDepth,
|
|
899
|
-
optIn: params.optIn,
|
|
900
|
-
address: params.address
|
|
901
|
-
}),
|
|
902
|
-
amount: params.amount,
|
|
903
|
-
address: params.address
|
|
904
|
-
});
|
|
613
|
+
const response = await this.fetchQuote(params);
|
|
614
|
+
return {
|
|
615
|
+
...response,
|
|
616
|
+
quote: response.quote === "" ? 0n : BigInt(response.quote),
|
|
617
|
+
amount: BigInt(params.amount),
|
|
618
|
+
address: params.address ?? void 0,
|
|
619
|
+
createdAt: Date.now()
|
|
620
|
+
};
|
|
905
621
|
}
|
|
906
622
|
/**
|
|
907
623
|
* Create a SwapComposer instance
|
|
@@ -910,7 +626,7 @@ var DeflexClient = class {
|
|
|
910
626
|
* before and after the swap transactions, with automatic handling of pre-signed transactions
|
|
911
627
|
* and opt-ins.
|
|
912
628
|
*
|
|
913
|
-
* @param config.quote - The quote
|
|
629
|
+
* @param config.quote - The quote result from newQuote() or raw API response from fetchQuote()
|
|
914
630
|
* @param config.address - The address of the signer
|
|
915
631
|
* @param config.slippage - The slippage tolerance
|
|
916
632
|
* @param config.signer - Transaction signer function
|
|
@@ -953,11 +669,10 @@ var DeflexClient = class {
|
|
|
953
669
|
*/
|
|
954
670
|
async newSwap(config) {
|
|
955
671
|
const { quote, address, slippage, signer } = config;
|
|
956
|
-
const quoteResponse = quote instanceof DeflexQuote ? quote.response : quote;
|
|
957
672
|
return new SwapComposer({
|
|
958
|
-
quote
|
|
673
|
+
quote,
|
|
959
674
|
deflexTxns: (await this.fetchSwapTransactions({
|
|
960
|
-
quote
|
|
675
|
+
quote,
|
|
961
676
|
address,
|
|
962
677
|
slippage
|
|
963
678
|
})).txns,
|
|
@@ -990,5 +705,5 @@ var DeflexClient = class {
|
|
|
990
705
|
};
|
|
991
706
|
|
|
992
707
|
//#endregion
|
|
993
|
-
export { DEFAULT_ALGOD_PORT, DEFAULT_ALGOD_TOKEN, DEFAULT_ALGOD_URI, DEFAULT_API_BASE_URL, DEFAULT_AUTO_OPT_IN, DEFAULT_CONFIRMATION_ROUNDS, DEFAULT_FEE_BPS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_GROUP_SIZE, DEPRECATED_PROTOCOLS, DeflexClient,
|
|
708
|
+
export { DEFAULT_ALGOD_PORT, DEFAULT_ALGOD_TOKEN, DEFAULT_ALGOD_URI, DEFAULT_API_BASE_URL, DEFAULT_AUTO_OPT_IN, DEFAULT_CONFIRMATION_ROUNDS, DEFAULT_FEE_BPS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_GROUP_SIZE, DEPRECATED_PROTOCOLS, DeflexClient, HTTPError, MAX_FEE_BPS, Protocol, SwapComposer, SwapComposerStatus, request };
|
|
994
709
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["userTransactions: Transaction[]","userTransactionIndexes: number[]","deflexSignedTxns: Uint8Array[]","userSignedTxns: Uint8Array[]","signedTxns: Uint8Array[]","appOptIns: SwapTransaction[]","swapTxns: SwapTransaction[]","appOptInTxns: Transaction[]","status: number","statusText: string","data: unknown","errorData: unknown","body: FetchSwapTxnsBody"],"sources":["../src/constants.ts","../src/composer.ts","../src/quote.ts","../src/utils.ts","../src/client.ts"],"sourcesContent":["/**\n * Supported DEX protocols for swap routing\n */\nexport enum Protocol {\n TinymanV2 = 'TinymanV2',\n Algofi = 'Algofi',\n Algomint = 'Algomint',\n Pact = 'Pact',\n Folks = 'Folks',\n TAlgo = 'TAlgo',\n}\n\n/**\n * Deprecated protocols that are automatically excluded from routing\n *\n * @internal\n */\nexport const DEPRECATED_PROTOCOLS = ['Humble', 'Tinyman'] as const\n\n/** Default Algod node URI for mainnet */\nexport const DEFAULT_ALGOD_URI = 'https://mainnet-api.4160.nodely.dev/'\n\n/** Default Algod node token (empty for public nodes) */\nexport const DEFAULT_ALGOD_TOKEN = ''\n\n/** Default Algod node port */\nexport const DEFAULT_ALGOD_PORT = 443\n\n/** Default Deflex API base URL */\nexport const DEFAULT_API_BASE_URL = 'https://deflex.txnlab.dev/api'\n\n/** Default fee in basis points (0.15%) */\nexport const DEFAULT_FEE_BPS = 15\n\n/** Maximum allowed fee in basis points (3.00%) */\nexport const MAX_FEE_BPS = 300\n\n/** Default maximum transaction group size */\nexport const DEFAULT_MAX_GROUP_SIZE = 16\n\n/** Default maximum routing depth (number of hops) */\nexport const DEFAULT_MAX_DEPTH = 4\n\n/** Default auto opt-in setting (automatic asset/app opt-in detection) */\nexport const DEFAULT_AUTO_OPT_IN = false\n\n/** Default number of rounds to wait for transaction confirmation */\nexport const DEFAULT_CONFIRMATION_ROUNDS = 4\n","import {\n assignGroupID,\n decodeUnsignedTransaction,\n isValidAddress,\n signLogicSigTransactionObject,\n signTransaction,\n LogicSigAccount,\n makeApplicationOptInTxnFromObject,\n msgpackRawDecode,\n Transaction,\n waitForConfirmation,\n} from 'algosdk'\nimport { DEFAULT_CONFIRMATION_ROUNDS } from './constants'\nimport type {\n FetchQuoteResponse,\n DeflexTransaction,\n SwapTransaction,\n DeflexSignature,\n} from './types'\nimport type { AlgorandClient } from '@algorandfoundation/algokit-utils'\nimport type { TransactionSigner } from 'algosdk'\n\n/**\n * A signer function for signing transaction groups\n *\n * Can be either:\n * - A TransactionSigner: algosdk.TransactionSigner\n * - A simpler inline function that only accepts the transaction group\n */\nexport type SignerFunction =\n | TransactionSigner\n | ((txns: Transaction[]) => Promise<Uint8Array[]>)\n\n/**\n * Status of the SwapComposer transaction group lifecycle\n */\nexport enum SwapComposerStatus {\n /** The atomic group is still under construction. */\n BUILDING,\n\n /** The atomic group has been finalized, but not yet signed. */\n BUILT,\n\n /** The atomic group has been finalized and signed, but not yet submitted to the network. */\n SIGNED,\n\n /** The atomic group has been finalized, signed, and submitted to the network. */\n SUBMITTED,\n\n /** The atomic group has been finalized, signed, submitted, and successfully committed to a block. */\n COMMITTED,\n}\n\n/**\n * Configuration for creating a SwapComposer instance\n */\nexport interface SwapComposerConfig {\n /** The quote response from fetchQuote() */\n readonly quote: FetchQuoteResponse\n /** The swap transactions from fetchSwapTransactions() */\n readonly deflexTxns: DeflexTransaction[]\n /** AlgorandClient instance for blockchain operations */\n readonly algorand: AlgorandClient\n /** The address of the account that will sign transactions */\n readonly address: string\n /** Transaction signer function */\n readonly signer: SignerFunction\n}\n\n/**\n * Composer for building and executing atomic swap transaction groups\n *\n * The SwapComposer allows you to build complex transaction groups by adding custom\n * transactions before and after swap transactions. It handles pre-signed transactions,\n * automatic app opt-ins, and provides a fluent API for transaction group construction.\n *\n * @example\n * ```typescript\n * const quote = await deflex.fetchQuote({ ... })\n * const composer = await deflex.newSwap({ quote, address, slippage })\n *\n * await composer\n * .addTransaction(customTxn)\n * .addSwapTransactions()\n * .execute(signer)\n * ```\n */\nexport class SwapComposer {\n /** The maximum size of an atomic transaction group. */\n static MAX_GROUP_SIZE: number = 16\n\n private status: SwapComposerStatus = SwapComposerStatus.BUILDING\n private transactions: SwapTransaction[] = []\n private swapTransactionsAdded = false\n private signedTxns: Uint8Array[] = []\n private txIds: string[] = []\n\n private readonly quote: FetchQuoteResponse\n private readonly deflexTxns: DeflexTransaction[]\n private readonly algorand: AlgorandClient\n private readonly address: string\n private readonly signer: TransactionSigner | SignerFunction\n\n /**\n * Create a new SwapComposer instance\n *\n * Note: Most developers should use DeflexClient.newSwap() instead of constructing\n * this directly, as the factory method handles fetching swap transactions automatically.\n *\n * @param config - Configuration for the composer\n * @param config.quote - The quote response from fetchQuote()\n * @param config.deflexTxns - The swap transactions from fetchSwapTransactions()\n * @param config.algorand - AlgorandClient instance for blockchain operations\n * @param config.address - The address of the account that will sign transactions\n * @param config.signer - Transaction signer function\n */\n constructor(config: SwapComposerConfig) {\n // Validate required parameters\n if (!config.quote) {\n throw new Error('Quote is required')\n }\n if (!config.deflexTxns) {\n throw new Error('Swap transactions are required')\n }\n if (config.deflexTxns.length === 0) {\n throw new Error('Swap transactions array cannot be empty')\n }\n if (!config.algorand) {\n throw new Error('AlgorandClient instance is required')\n }\n if (!config.signer) {\n throw new Error('Signer is required')\n }\n\n this.quote = config.quote\n this.deflexTxns = config.deflexTxns\n this.algorand = config.algorand\n this.address = this.validateAddress(config.address)\n this.signer = config.signer\n }\n\n /**\n * Get the status of this composer's transaction group\n *\n * @returns The current status of the transaction group\n */\n getStatus(): SwapComposerStatus {\n return this.status\n }\n\n /**\n * Get the number of transactions currently in this atomic group\n *\n * @returns The number of transactions in the group\n */\n count(): number {\n return this.transactions.length\n }\n\n /**\n * Add a transaction to the atomic group\n *\n * Transactions are added in the order methods are called. For example:\n * ```typescript\n * composer\n * .addTransaction(txn1) // Added first\n * .addSwapTransactions() // Added second\n * .addTransaction(txn2) // Added third\n * ```\n *\n * @param transaction - The transaction to add\n * @returns This composer instance for chaining\n * @throws Error if the composer is not in the BUILDING status\n * @throws Error if the maximum group size is exceeded\n */\n addTransaction(transaction: Transaction): this {\n if (this.status !== SwapComposerStatus.BUILDING) {\n throw new Error(\n 'Cannot add transactions when composer status is not BUILDING',\n )\n }\n\n if (this.transactions.length === SwapComposer.MAX_GROUP_SIZE) {\n throw new Error(\n `Adding an additional transaction exceeds the maximum atomic group size of ${SwapComposer.MAX_GROUP_SIZE}`,\n )\n }\n\n this.transactions.push({ txn: transaction })\n return this\n }\n\n /**\n * Add swap transactions to the atomic group\n *\n * This method automatically processes required app opt-ins and adds all swap\n * transactions from the quote. Can only be called once per composer instance.\n *\n * @returns This composer instance for chaining\n * @throws Error if the swap transactions have already been added\n * @throws Error if the composer is not in the BUILDING status\n * @throws Error if the maximum group size is exceeded\n */\n async addSwapTransactions(): Promise<this> {\n if (this.swapTransactionsAdded) {\n throw new Error('Swap transactions have already been added')\n }\n\n if (this.status !== SwapComposerStatus.BUILDING) {\n throw new Error(\n 'Cannot add swap transactions when composer status is not BUILDING',\n )\n }\n\n const processedTxns = await this.processSwapTransactions()\n const newLength = this.transactions.length + processedTxns.length\n\n if (newLength > SwapComposer.MAX_GROUP_SIZE) {\n throw new Error(\n `Adding swap transactions exceeds the maximum atomic group size of ${SwapComposer.MAX_GROUP_SIZE}`,\n )\n }\n\n this.transactions.push(...processedTxns)\n\n this.swapTransactionsAdded = true\n return this\n }\n\n /**\n * Sign the transaction group\n *\n * Automatically adds swap transactions if not already added, builds the atomic group,\n * and signs all transactions using the configured signer.\n *\n * @returns A promise that resolves to an array of signed transaction blobs\n *\n * @example\n * ```typescript\n * const signedTxns = await composer.sign()\n * ```\n */\n async sign(): Promise<Uint8Array[]> {\n if (this.status >= SwapComposerStatus.SIGNED) {\n return this.signedTxns\n }\n\n // Auto-add swap transactions if needed\n if (!this.swapTransactionsAdded) {\n await this.addSwapTransactions()\n }\n\n // Build the transaction group, ensure status is BUILT\n const transactions = this.buildGroup()\n\n // Separate user transactions and pre-signed transactions\n const userTransactions: Transaction[] = []\n const userTransactionIndexes: number[] = []\n const deflexSignedTxns: Uint8Array[] = []\n\n for (let i = 0; i < transactions.length; i++) {\n const item = transactions[i]\n if (!item) continue\n\n if (!item.deflexSignature) {\n // User transaction - needs user signature\n userTransactions.push(item.txn)\n userTransactionIndexes.push(userTransactions.length - 1)\n } else {\n // Pre-signed transaction - re-sign with Deflex signature\n const signedTxnBlob = this.signDeflexTransaction(\n item.txn,\n item.deflexSignature,\n )\n deflexSignedTxns.push(signedTxnBlob)\n }\n }\n\n // Sign user transactions\n let userSignedTxns: Uint8Array[] = []\n if (userTransactions.length > 0) {\n userSignedTxns = await (this.signer as TransactionSigner)(\n userTransactions,\n userTransactionIndexes,\n )\n }\n\n // Combine user-signed and pre-signed transactions in correct order\n const signedTxns: Uint8Array[] = []\n let userSignedIndex = 0\n let deflexSignedIndex = 0\n\n for (const item of transactions) {\n if (!item.deflexSignature) {\n const signedTxn = userSignedTxns[userSignedIndex]\n if (signedTxn) {\n signedTxns.push(signedTxn)\n }\n userSignedIndex++\n } else {\n const deflexSignedTxn = deflexSignedTxns[deflexSignedIndex]\n if (deflexSignedTxn) {\n signedTxns.push(deflexSignedTxn)\n }\n deflexSignedIndex++\n }\n }\n\n const txIds = this.transactions.map((t) => t.txn.txID())\n\n this.signedTxns = signedTxns\n this.txIds = txIds\n this.status = SwapComposerStatus.SIGNED\n\n return signedTxns\n }\n\n /**\n * Submit the signed transactions to the network\n *\n * This method signs the transaction group (if not already signed) and submits\n * it to the Algorand network. Does not wait for confirmation.\n *\n * @returns The transaction IDs\n * @throws Error if the transaction group has already been submitted\n *\n * @example\n * ```typescript\n * const txIds = await composer.submit()\n * console.log('Submitted transactions:', txIds)\n * ```\n */\n async submit(): Promise<string[]> {\n if (this.status > SwapComposerStatus.SUBMITTED) {\n throw new Error('Transaction group cannot be resubmitted')\n }\n\n const stxns = await this.sign()\n await this.algorand.client.algod.sendRawTransaction(stxns).do()\n\n this.status = SwapComposerStatus.SUBMITTED\n return this.txIds\n }\n\n /**\n * Execute the swap\n *\n * Signs the transaction group, submits it to the network, and waits for confirmation.\n * This is the primary method for executing swaps and combines sign(), submit(), and\n * waitForConfirmation() into a single call.\n *\n * @param waitRounds - The number of rounds to wait for confirmation (default: 4)\n * @returns Object containing the confirmed round and transaction IDs\n * @throws Error if the transaction group has already been committed\n *\n * @example\n * ```typescript\n * const result = await composer.execute()\n * console.log(`Confirmed in round ${result.confirmedRound}`)\n * console.log('Transaction IDs:', result.txIds)\n * ```\n */\n async execute(waitRounds: number = DEFAULT_CONFIRMATION_ROUNDS): Promise<{\n confirmedRound: bigint\n txIds: string[]\n }> {\n if (this.status === SwapComposerStatus.COMMITTED) {\n throw new Error(\n 'Transaction group has already been executed successfully',\n )\n }\n\n const txIds = await this.submit()\n\n const confirmedTxnInfo = await waitForConfirmation(\n this.algorand.client.algod,\n txIds[0]!,\n waitRounds,\n )\n\n this.status = SwapComposerStatus.COMMITTED\n\n const confirmedRound = confirmedTxnInfo.confirmedRound!\n\n return {\n confirmedRound,\n txIds,\n }\n }\n\n /**\n * Validates an Algorand address\n */\n private validateAddress(address: string): string {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid Algorand address: ${address}`)\n }\n return address\n }\n\n /**\n * Processes app opt-ins and decodes swap transactions from API response\n */\n private async processSwapTransactions(): Promise<SwapTransaction[]> {\n // Process required app opt-ins\n const appOptIns: SwapTransaction[] = await this.processRequiredAppOptIns()\n\n // Decode and process swap transactions from API\n const swapTxns: SwapTransaction[] = []\n for (let i = 0; i < this.deflexTxns.length; i++) {\n const deflexTxn = this.deflexTxns[i]\n if (!deflexTxn) continue\n\n try {\n // Decode transaction from base64 data\n const txnBytes = Buffer.from(deflexTxn.data, 'base64')\n const txn = decodeUnsignedTransaction(txnBytes)\n\n // Remove group ID (will be reassigned later)\n delete txn.group\n\n if (deflexTxn.signature !== false) {\n // Pre-signed transaction - needs re-signing with provided signature\n swapTxns.push({\n txn,\n deflexSignature: deflexTxn.signature,\n })\n } else {\n // User transaction - needs user signature\n swapTxns.push({\n txn,\n })\n }\n } catch (error) {\n throw new Error(\n `Failed to process swap transaction at index ${i}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n return [...appOptIns, ...swapTxns]\n }\n\n /**\n * Creates opt-in transactions for apps the user hasn't opted into yet\n */\n private async processRequiredAppOptIns(): Promise<SwapTransaction[]> {\n // Fetch account information\n const accountInfo = await this.algorand.account.getInformation(this.address)\n\n // Check app opt-ins\n const userApps =\n accountInfo?.appsLocalState?.map((app) => Number(app.id)) || []\n const appsToOptIn = this.quote.requiredAppOptIns.filter(\n (appId) => !userApps.includes(appId),\n )\n\n // Create opt-in transactions if needed\n const appOptInTxns: Transaction[] = []\n if (appsToOptIn.length > 0) {\n const suggestedParams = await this.algorand.client.algod\n .getTransactionParams()\n .do()\n\n for (const appId of appsToOptIn) {\n const optInTxn = makeApplicationOptInTxnFromObject({\n sender: this.address,\n appIndex: appId,\n suggestedParams,\n })\n appOptInTxns.push(optInTxn)\n }\n }\n\n return appOptInTxns.map((txn) => ({ txn }))\n }\n\n /**\n * Finalizes the transaction group by assigning group IDs\n *\n * The composer's status will be at least BUILT after executing this method.\n */\n private buildGroup(): SwapTransaction[] {\n if (this.status === SwapComposerStatus.BUILDING) {\n if (this.transactions.length === 0) {\n throw new Error('Cannot build a group with 0 transactions')\n }\n if (this.transactions.length > 1) {\n assignGroupID(this.transactions.map((t) => t.txn))\n }\n this.status = SwapComposerStatus.BUILT\n }\n return this.transactions\n }\n\n /**\n * Re-signs a Deflex transaction using the provided logic signature or secret key\n */\n private signDeflexTransaction(\n transaction: Transaction,\n signature: DeflexSignature,\n ): Uint8Array {\n try {\n if (signature.type === 'logic_signature') {\n // Decode the signature value to extract the logic signature\n const valueArray = signature.value as Record<string, number>\n const valueBytes = new Uint8Array(Object.values(valueArray))\n const decoded = msgpackRawDecode(valueBytes) as {\n lsig?: { l: Uint8Array; arg?: Uint8Array[] }\n }\n\n if (!decoded.lsig) {\n throw new Error('Logic signature structure missing lsig field')\n }\n\n const lsig = decoded.lsig\n const logicSigAccount = new LogicSigAccount(lsig.l, lsig.arg)\n\n const signedTxn = signLogicSigTransactionObject(\n transaction,\n logicSigAccount,\n )\n return signedTxn.blob\n } else if (signature.type === 'secret_key') {\n // Convert signature.value (Record<string, number>) to Uint8Array\n const valueArray = signature.value as Record<string, number>\n const secretKey = new Uint8Array(Object.values(valueArray))\n const signedTxn = signTransaction(transaction, secretKey)\n return signedTxn.blob\n } else {\n throw new Error(`Unsupported signature type: ${signature.type}`)\n }\n } catch (error) {\n throw new Error(\n `Failed to re-sign transaction: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n","import type {\n FetchQuoteResponse,\n Profit,\n Route,\n DexQuote,\n TxnPayload,\n} from './types'\n\n/**\n * Configuration for creating a DeflexQuote instance\n */\nexport interface DeflexQuoteConfig {\n /** The raw quote response from the Deflex API */\n response: FetchQuoteResponse\n /** The original amount from the quote request */\n amount: bigint | number\n /** Optional address parameter from the quote request */\n address?: string\n}\n\n/**\n * Wrapper class for Deflex quote responses with convenience methods\n *\n * The DeflexQuote class provides a developer-friendly interface for working with\n * swap quotes from the Deflex API. It exposes all quote properties via getters\n * and provides additional convenience methods for derived data.\n *\n * @example\n * ```typescript\n * const quote = await deflex.newQuote({\n * address: 'ABC...',\n * fromAssetId: 0,\n * toAssetId: 31566704,\n * amount: 1_000_000,\n * })\n *\n * // Access quote properties directly\n * console.log(quote.quote) // bigint (quoted amount)\n * console.log(quote.fromAssetId) // number\n * console.log(quote.toAssetId) // number\n *\n * // Access metadata\n * console.log(quote.amount) // bigint (original request amount)\n * console.log(quote.address) // string | undefined\n * console.log(quote.createdAt) // number\n *\n * // Use convenience methods for derived data\n * const minReceivedAmount = quote.getSlippageAmount(slippage) // fixed-input swap\n * const maxSentAmount = quote.getSlippageAmount(slippage) // fixed-output swap\n * ```\n */\nexport class DeflexQuote {\n private readonly _response: FetchQuoteResponse\n private readonly _amount: bigint\n private readonly _address?: string\n private readonly _createdAt: number\n\n /**\n * Create a new DeflexQuote instance\n *\n * Note: Most developers should use DeflexClient.newQuote() instead of constructing\n * this directly, as the factory method handles fetching the quote automatically.\n *\n * @param config - Configuration for the quote instance\n * @param config.response - The raw quote response from the Deflex API\n * @param config.amount - The original amount from the quote request\n * @param config.address - Optional address parameter from the quote request\n */\n constructor(config: DeflexQuoteConfig) {\n if (!config?.response) {\n throw new Error('Quote response is required')\n }\n if (config.amount === undefined || config.amount === null) {\n throw new Error('Amount is required')\n }\n this._response = config.response\n this._amount = BigInt(config.amount)\n this._address = config.address\n this._createdAt = Date.now()\n }\n\n /**\n * Get the raw quote response from the Deflex API\n *\n * @returns The raw quote response from the Deflex API\n */\n get response(): FetchQuoteResponse {\n return this._response\n }\n\n // ============================================================================\n // Quote Metadata (not from API response)\n // ============================================================================\n\n /**\n * The original amount from the quote request (in base units)\n *\n * This is the amount that was provided when fetching the quote.\n * For fixed-input swaps, this is the input amount.\n * For fixed-output swaps, this is the desired output amount.\n *\n * @example\n * ```typescript\n * const quote = await deflex.newQuote({\n * fromAssetId: 0,\n * toAssetId: 31566704,\n * amount: 1_000_000, // 1 ALGO\n * type: 'fixed-input'\n * })\n * console.log(quote.amount) // 1000000n (input amount)\n * console.log(quote.quote) // 5000000n (output amount quoted)\n * ```\n */\n get amount(): bigint {\n return this._amount\n }\n\n /**\n * The address parameter from the quote request\n *\n * This is the address that was provided when fetching the quote (if any).\n * Useful for tracking which account the quote was fetched for, especially\n * when using autoOptIn functionality.\n */\n get address(): string | undefined {\n return this._address\n }\n\n /**\n * Timestamp when the quote was created (in milliseconds)\n *\n * Can be used to determine quote freshness. Quotes may become stale\n * over time as market conditions change.\n *\n * @example\n * ```typescript\n * const ageInSeconds = (Date.now() - quote.createdAt) / 1000\n * if (ageInSeconds > 30) {\n * console.log('Quote may be stale, consider refreshing')\n * }\n * ```\n */\n get createdAt(): number {\n return this._createdAt\n }\n\n // ============================================================================\n // Quote Response Properties (exposed via getters)\n // ============================================================================\n\n /**\n * The quoted output amount or input amount (depending on quote type)\n *\n * For fixed-input swaps: This is the output amount you'll receive\n * For fixed-output swaps: This is the input amount you'll need to provide\n *\n * @returns The quote amount as a bigint in base units\n */\n get quote(): bigint {\n const rawQuote = this._response.quote\n return rawQuote === '' ? 0n : BigInt(rawQuote)\n }\n\n /**\n * Profit information for the swap\n */\n get profit(): Profit {\n return this._response.profit\n }\n\n /**\n * Baseline price without fees\n */\n get priceBaseline(): number {\n return this._response.priceBaseline\n }\n\n /**\n * Price impact for the user\n */\n get userPriceImpact(): number | undefined {\n return this._response.userPriceImpact\n }\n\n /**\n * Overall market price impact\n */\n get marketPriceImpact(): number | undefined {\n return this._response.marketPriceImpact\n }\n\n /**\n * USD value of input amount\n */\n get usdIn(): number {\n return this._response.usdIn\n }\n\n /**\n * USD value of output amount\n */\n get usdOut(): number {\n return this._response.usdOut\n }\n\n /**\n * The routing path(s) for the swap\n */\n get route(): Route[] {\n return this._response.route\n }\n\n /**\n * Flattened view of routing percentages by protocol\n */\n get flattenedRoute(): Record<string, number> {\n return this._response.flattenedRoute\n }\n\n /**\n * Individual quotes from each DEX\n */\n get quotes(): DexQuote[] {\n return this._response.quotes\n }\n\n /**\n * App IDs that require opt-in for this swap\n */\n get requiredAppOptIns(): number[] {\n return this._response.requiredAppOptIns\n }\n\n /**\n * Encrypted transaction payload for generating swap transactions\n */\n get txnPayload(): TxnPayload | null {\n return this._response.txnPayload\n }\n\n /**\n * Fees charged by each protocol\n */\n get protocolFees(): Record<string, number> {\n return this._response.protocolFees\n }\n\n /**\n * Input asset ID\n */\n get fromAssetId(): number {\n return this._response.fromASAID\n }\n\n /**\n * Output asset ID\n */\n get toAssetId(): number {\n return this._response.toASAID\n }\n\n /**\n * Quote type\n */\n get type(): string {\n return this._response.type\n }\n\n /**\n * Performance timing data\n */\n get timing(): unknown | undefined {\n return this._response.timing\n }\n\n // ============================================================================\n // Convenience Methods (derived/computed properties)\n // ============================================================================\n\n /**\n * Calculate the slippage-adjusted amount\n *\n * For fixed-input swaps: Returns the minimum amount you'll receive after slippage\n * For fixed-output swaps: Returns the maximum amount you'll need to send after slippage\n *\n * @param slippage - Slippage tolerance as a percentage (e.g., 1 for 1%)\n * @returns The slippage-adjusted amount as a bigint\n *\n * @example\n * ```typescript\n * // Fixed-input swap: 1 ALGO -> USDC\n * const quote = await deflex.newQuote({\n * fromAssetId: 0,\n * toAssetId: 31566704,\n * amount: 1_000_000,\n * type: 'fixed-input'\n * })\n *\n * // Get minimum output with 1% slippage\n * const minOutput = quote.getSlippageAmount(1)\n * console.log(`Minimum you'll receive: ${minOutput}`)\n * ```\n *\n * @example\n * ```typescript\n * // Fixed-output swap: ALGO -> 10 USDC\n * const quote = await deflex.newQuote({\n * fromAssetId: 0,\n * toAssetId: 31566704,\n * amount: 10_000_000,\n * type: 'fixed-output'\n * })\n *\n * // Get maximum input with 1% slippage\n * const maxInput = quote.getSlippageAmount(1)\n * console.log(`Maximum you'll need to send: ${maxInput}`)\n * ```\n */\n getSlippageAmount(slippage: number): bigint {\n const quoteAmount = this.quote\n const slippageBps = BigInt(Math.floor(slippage * 100))\n\n if (this._response.type === 'fixed-input') {\n // For fixed-input: reduce output by slippage (minimum received)\n return (quoteAmount * (10000n - slippageBps)) / 10000n\n } else {\n // For fixed-output: increase input by slippage (maximum sent)\n return (quoteAmount * (10000n + slippageBps)) / 10000n\n }\n }\n}\n","/**\n * HTTP error with status code and response data\n */\nexport class HTTPError extends Error {\n constructor(\n public status: number,\n public statusText: string,\n public data: unknown,\n ) {\n super(`HTTP ${status} ${statusText}`)\n this.name = 'HTTPError'\n }\n}\n\n/**\n * Make an HTTP request and parse JSON response\n *\n * Simple wrapper around native fetch for API calls. Throws HTTPError for\n * non-2xx responses.\n *\n * @param url - The URL to request\n * @param options - Fetch options\n * @returns Parsed JSON response\n * @throws HTTPError if the response status is not ok\n */\nexport async function request<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n const response = await fetch(url, options)\n\n if (!response.ok) {\n let errorData: unknown\n\n try {\n errorData = await response.json()\n } catch {\n try {\n errorData = await response.text()\n } catch {\n errorData = 'Failed to parse error response'\n }\n }\n\n throw new HTTPError(\n response.status,\n response.statusText,\n JSON.stringify(errorData),\n )\n }\n\n return response.json() as Promise<T>\n}\n","import { AlgorandClient } from '@algorandfoundation/algokit-utils'\nimport { isValidAddress } from 'algosdk'\nimport { SwapComposer, type SignerFunction } from './composer'\nimport {\n DEFAULT_ALGOD_PORT,\n DEFAULT_ALGOD_TOKEN,\n DEFAULT_ALGOD_URI,\n DEFAULT_API_BASE_URL,\n DEFAULT_AUTO_OPT_IN,\n DEFAULT_FEE_BPS,\n DEFAULT_MAX_DEPTH,\n DEFAULT_MAX_GROUP_SIZE,\n DEPRECATED_PROTOCOLS,\n MAX_FEE_BPS,\n} from './constants'\nimport { DeflexQuote } from './quote'\nimport { request } from './utils'\nimport type {\n FetchQuoteResponse,\n FetchSwapTxnsResponse,\n DeflexConfig,\n DeflexConfigParams,\n FetchSwapTxnsParams,\n FetchSwapTxnsBody,\n FetchQuoteParams,\n QuoteParams,\n} from './types'\n\n/**\n * Client for interacting with the Deflex order router API\n *\n * The DeflexClient provides methods to fetch swap quotes and create transaction composers\n * for executing swaps on the Algorand blockchain. It handles API communication, transaction\n * validation, and automatic asset/app opt-in detection.\n *\n * @example\n * ```typescript\n * const deflex = new DeflexClient({\n * apiKey: 'your-api-key',\n * })\n * ```\n *\n * @example\n * ```typescript\n * const deflex = new DeflexClient({\n * apiKey: 'your-api-key',\n * algodUri: 'https://mainnet-api.4160.nodely.dev/',\n * algodToken: '',\n * algodPort: 443,\n * referrerAddress: 'REFERRER_ADDRESS...',\n * feeBps: 15,\n * autoOptIn: false,\n * })\n * ```\n */\nexport class DeflexClient {\n private readonly baseUrl: string = DEFAULT_API_BASE_URL\n private readonly config: DeflexConfig\n private readonly algorand: AlgorandClient\n\n /**\n * Create a new DeflexClient instance\n *\n * @param config - Configuration parameters\n * @param config.apiKey - API key for Deflex API (required)\n * @param config.algodUri - Algod node URI (default: https://mainnet-api.4160.nodely.dev/)\n * @param config.algodToken - Algod node token (default: '')\n * @param config.algodPort - Algod node port (default: 443)\n * @param config.referrerAddress - Referrer address for fee sharing (receives 25% of swap fees)\n * @param config.feeBps - Fee in basis points (default: 15 = 0.15%, max: 300 = 3.00%)\n * @param config.autoOptIn - Automatically detect and add required opt-in transactions (default: false)\n */\n constructor(config: DeflexConfigParams) {\n // Validate and set config\n this.config = {\n apiKey: this.validateApiKey(config.apiKey),\n algodUri: config.algodUri ?? DEFAULT_ALGOD_URI,\n algodToken: config.algodToken ?? DEFAULT_ALGOD_TOKEN,\n algodPort: config.algodPort ?? DEFAULT_ALGOD_PORT,\n referrerAddress: config.referrerAddress\n ? this.validateAddress(config.referrerAddress)\n : undefined,\n feeBps: this.validateFeeBps(config.feeBps ?? DEFAULT_FEE_BPS),\n autoOptIn: config.autoOptIn ?? DEFAULT_AUTO_OPT_IN,\n }\n\n // Create AlgorandClient\n this.algorand = AlgorandClient.fromConfig({\n algodConfig: {\n server: this.config.algodUri,\n port: this.config.algodPort,\n token: this.config.algodToken,\n },\n })\n }\n\n /**\n * Fetch a swap quote from the Deflex API\n *\n * Requests optimal swap routing from the Deflex API. The quote includes routing\n * information, price impact, required opt-ins, and an encrypted transaction payload.\n *\n * @param params - Parameters for the quote request\n * @param params.fromASAID - The ID of the asset to swap from\n * @param params.toASAID - The ID of the asset to swap to\n * @param params.amount - The amount of the asset to swap in base units\n * @param params.type - The type of the quote (default: 'fixed-input')\n * @param params.disabledProtocols - List of protocols to disable (default: [])\n * @param params.maxGroupSize - The maximum group size (default: 16)\n * @param params.maxDepth - The maximum depth (default: 4)\n * @param params.address - The address of the account that will perform the swap (recommended when using `config.autoOptIn` or `params.optIn`)\n * @param params.optIn - Whether to include asset opt-in transaction\n * - If true: API reduces maxGroupSize by 1 and includes opt-in (always included, even if not needed)\n * - If false: No opt-in transaction included\n * - If undefined: Falls back to `config.autoOptIn` behavior with account check (if `params.address` is provided)\n * @returns A FetchQuoteResponse object with routing information\n *\n * @example\n * ```typescript\n * const quote = await deflex.fetchQuote({\n * address: 'ABC...',\n * fromASAID: 0, // ALGO\n * toASAID: 31566704, // USDC\n * amount: 1_000_000, // 1 ALGO\n * })\n * ```\n */\n async fetchQuote(params: FetchQuoteParams): Promise<FetchQuoteResponse> {\n const {\n fromASAID,\n toASAID,\n amount,\n type = 'fixed-input',\n disabledProtocols = [],\n maxGroupSize = DEFAULT_MAX_GROUP_SIZE,\n maxDepth = DEFAULT_MAX_DEPTH,\n optIn,\n address,\n } = params\n\n // Always include deprecated protocols in disabled list\n const allDisabledProtocols = [\n ...new Set([...DEPRECATED_PROTOCOLS, ...disabledProtocols]),\n ]\n\n let includeOptIn = optIn\n if (includeOptIn === undefined && this.config.autoOptIn) {\n if (address) {\n includeOptIn = await this.needsAssetOptIn(\n this.validateAddress(address),\n toASAID,\n )\n } else {\n console.warn(\n 'autoOptIn is enabled but no address provided to fetchQuote(). Asset opt-in check skipped.',\n )\n }\n }\n\n const url = new URL(`${this.baseUrl}/fetchQuote`)\n\n url.searchParams.append('apiKey', this.config.apiKey)\n url.searchParams.append('algodUri', this.config.algodUri)\n url.searchParams.append('algodToken', this.config.algodToken)\n url.searchParams.append('algodPort', String(this.config.algodPort))\n url.searchParams.append('feeBps', this.config.feeBps.toString())\n url.searchParams.append('fromASAID', BigInt(fromASAID).toString())\n url.searchParams.append('toASAID', BigInt(toASAID).toString())\n url.searchParams.append('amount', BigInt(amount).toString())\n url.searchParams.append('type', type)\n url.searchParams.append('disabledProtocols', allDisabledProtocols.join(','))\n url.searchParams.append('maxGroupSize', maxGroupSize.toString())\n url.searchParams.append('maxDepth', maxDepth.toString())\n url.searchParams.append('optIn', String(includeOptIn))\n\n if (this.config.referrerAddress) {\n url.searchParams.append('referrerAddress', this.config.referrerAddress)\n }\n\n return request<FetchQuoteResponse>(url.toString())\n }\n\n /**\n * Check if asset opt-in is required for the output asset\n *\n * Convenience method to determine if an address needs to opt into the output asset\n * of a swap. This is useful when you want to get a quote without requiring wallet\n * connection upfront, but need to know whether to set `optIn: true` in fetchQuote()\n * to ensure proper routing (as opt-ins reduce maxGroupSize by 1).\n *\n * Note: If you enable `config.autoOptIn`, this check is handled automatically when\n * an address is provided to fetchQuote().\n *\n * @param address - The address to check\n * @param assetId - The output asset ID to check\n * @returns True if asset opt-in is required, false otherwise (always false for ALGO)\n *\n * @example\n * ```typescript\n * // Check if opt-in needed for output asset before fetching quote\n * const needsOptIn = await deflex.needsAssetOptIn(userAddress, toAssetId)\n * const quote = await deflex.fetchQuote({\n * fromAssetId,\n * toAssetId,\n * amount,\n * optIn: needsOptIn,\n * })\n * ```\n */\n async needsAssetOptIn(\n address: string,\n assetId: number | bigint,\n ): Promise<boolean> {\n // Fetch account information\n const accountInfo = await this.algorand.account.getInformation(address)\n\n // Check if asset opt-in is required\n return (\n BigInt(assetId) !== 0n &&\n accountInfo?.assets?.find(\n (asset) => asset.assetId === BigInt(assetId),\n ) === undefined\n )\n }\n\n /**\n * Fetch swap transactions from the Deflex API\n *\n * Decrypts the quote payload and generates executable swap transactions for the\n * specified signer address with the given slippage tolerance.\n *\n * @param params - Parameters for the swap transaction request\n * @param params.quote - The quote response from fetchQuote()\n * @param params.address - The address of the signer\n * @param params.slippage - The slippage tolerance as a percentage (e.g., 1 for 1%)\n * @returns A FetchSwapTxnsResponse object with transaction data\n */\n async fetchSwapTransactions(\n params: FetchSwapTxnsParams,\n ): Promise<FetchSwapTxnsResponse> {\n const { quote, address, slippage } = params\n\n // Validate signer address\n this.validateAddress(address)\n\n const url = new URL(`${this.baseUrl}/fetchExecuteSwapTxns`)\n\n const body: FetchSwapTxnsBody = {\n apiKey: this.config.apiKey,\n address,\n txnPayloadJSON: quote.txnPayload,\n slippage,\n }\n\n return request<FetchSwapTxnsResponse>(url.toString(), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n })\n }\n\n /**\n * Fetch a quote and return a DeflexQuote wrapper instance\n *\n * This is the recommended way to fetch quotes. It wraps the raw API response\n * in a DeflexQuote class that provides convenient methods for accessing quote data.\n *\n * @param params - Parameters for the quote request\n * @param params.fromAssetId - The ID of the asset to swap from\n * @param params.toAssetId - The ID of the asset to swap to\n * @param params.amount - The amount of the asset to swap in base units\n * @param params.type - The type of the quote (default: 'fixed-input')\n * @param params.disabledProtocols - List of protocols to disable (default: [])\n * @param params.maxGroupSize - The maximum group size (default: 16)\n * @param params.maxDepth - The maximum depth (default: 4)\n * @param params.address - The address of the account that will perform the swap (recommended when using `config.autoOptIn` or `params.optIn`)\n * @param params.optIn - Whether to include asset opt-in transaction\n * @returns A DeflexQuote instance with convenience methods\n *\n * @example\n * ```typescript\n * const quote = await deflex.newQuote({\n * address: 'ABC...',\n * fromAssetId: 0,\n * toAssetId: 31566704,\n * amount: 1_000_000,\n * })\n *\n * // Access quote data\n * console.log(quote.quote) // bigint (quoted amount)\n * console.log(quote.fromAssetId) // number\n * console.log(quote.toAssetId) // number\n *\n * // Access metadata\n * console.log(quote.amount) // bigint (original request amount)\n * console.log(quote.address) // string | undefined\n * console.log(quote.createdAt) // number\n *\n * // Use convenience methods\n * const minReceivedAmount = quote.getSlippageAmount(slippage) // fixed-input swap\n * const maxSentAmount = quote.getSlippageAmount(slippage) // fixed-output swap\n * ```\n */\n async newQuote(params: QuoteParams): Promise<DeflexQuote> {\n const response = await this.fetchQuote({\n fromASAID: params.fromAssetId,\n toASAID: params.toAssetId,\n amount: params.amount,\n type: params.type,\n disabledProtocols: params.disabledProtocols,\n maxGroupSize: params.maxGroupSize,\n maxDepth: params.maxDepth,\n optIn: params.optIn,\n address: params.address,\n })\n\n // Create the quote wrapper\n const quote = new DeflexQuote({\n response,\n amount: params.amount,\n address: params.address,\n })\n\n return quote\n }\n\n /**\n * Create a SwapComposer instance\n *\n * This factory method creates a composer that allows you to add custom transactions\n * before and after the swap transactions, with automatic handling of pre-signed transactions\n * and opt-ins.\n *\n * @param config.quote - The quote response from fetchQuote() or a DeflexQuote instance\n * @param config.address - The address of the signer\n * @param config.slippage - The slippage tolerance\n * @param config.signer - Transaction signer function\n * @returns A SwapComposer instance ready for building transaction groups\n *\n * @example\n * ```typescript\n * // Basic swap\n * const quote = await deflex.newQuote({ ... })\n * await deflex.newSwap({ quote, address, slippage, signer })\n * .execute()\n * ```\n *\n * @example\n * ```typescript\n * // Advanced swap with custom transactions\n * const quote = await deflex.newQuote({ ... })\n * const swap = await deflex.newSwap({\n * quote,\n * address,\n * slippage,\n * signer,\n * })\n *\n * console.log(swap.getStatus()) // BUILDING\n *\n * const signedTxns = await swap\n * .addTransaction(beforeTxn)\n * .addSwapTransactions() // Adds swap transactions to the group\n * .addTransaction(afterTxn)\n * .sign()\n *\n * console.log(swap.getStatus()) // SIGNED\n *\n * const result = await swap.execute(waitRounds)\n * console.log(result.confirmedRound, result.txIds)\n *\n * console.log(swap.getStatus()) // COMMITTED\n * ```\n */\n async newSwap(config: {\n quote: DeflexQuote | FetchQuoteResponse\n address: string\n slippage: number\n signer: SignerFunction\n }): Promise<SwapComposer> {\n const { quote, address, slippage, signer } = config\n\n const quoteResponse = quote instanceof DeflexQuote ? quote.response : quote\n\n const swapResponse = await this.fetchSwapTransactions({\n quote: quoteResponse,\n address,\n slippage,\n })\n\n // Create the composer\n const composer = new SwapComposer({\n quote: quoteResponse,\n deflexTxns: swapResponse.txns,\n algorand: this.algorand,\n address,\n signer,\n })\n\n return composer\n }\n\n /**\n * Validates the API key\n */\n private validateApiKey(apiKey: string): string {\n if (!apiKey) {\n throw new Error('API key is required')\n }\n return apiKey\n }\n\n /**\n * Validates an Algorand address\n */\n private validateAddress(address: string): string {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid Algorand address: ${address}`)\n }\n return address\n }\n\n /**\n * Validates the fee in basis points (max 300 = 3.00%)\n */\n private validateFeeBps(feeBps: number): number {\n if (feeBps < 0 || feeBps > MAX_FEE_BPS) {\n throw new Error(\n `Invalid fee: ${feeBps} basis points (must be between 0 and ${MAX_FEE_BPS})`,\n )\n }\n return feeBps\n }\n}\n"],"mappings":";;;;;;;AAGA,IAAY,gDAAL;AACL;AACA;AACA;AACA;AACA;AACA;;;;;;;;AAQF,MAAa,uBAAuB,CAAC,UAAU,UAAU;;AAGzD,MAAa,oBAAoB;;AAGjC,MAAa,sBAAsB;;AAGnC,MAAa,qBAAqB;;AAGlC,MAAa,uBAAuB;;AAGpC,MAAa,kBAAkB;;AAG/B,MAAa,cAAc;;AAG3B,MAAa,yBAAyB;;AAGtC,MAAa,oBAAoB;;AAGjC,MAAa,sBAAsB;;AAGnC,MAAa,8BAA8B;;;;;;;ACX3C,IAAY,oEAAL;;AAEL;;AAGA;;AAGA;;AAGA;;AAGA;;;;;;;;;;;;;;;;;;;;;AAqCF,IAAa,eAAb,MAAa,aAAa;;CAExB,OAAO,iBAAyB;CAEhC,AAAQ,SAA6B,mBAAmB;CACxD,AAAQ,eAAkC,EAAE;CAC5C,AAAQ,wBAAwB;CAChC,AAAQ,aAA2B,EAAE;CACrC,AAAQ,QAAkB,EAAE;CAE5B,AAAiB;CACjB,AAAiB;CAC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OAAO;IACrB,UAAU,OAAO;IACjB,OAAO,OAAO;IACd,SAAS,OAAO;IACjB,CAAC;GAKA,QAAQ,OAAO;GACf,SAAS,OAAO;GACjB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDJ,MAAM,QAAQ,QAKY;EACxB,MAAM,EAAE,OAAO,SAAS,UAAU,WAAW;EAE7C,MAAM,gBAAgB,iBAAiB,cAAc,MAAM,WAAW;AAiBtE,SARiB,IAAI,aAAa;GAChC,OAAO;GACP,aATmB,MAAM,KAAK,sBAAsB;IACpD,OAAO;IACP;IACA;IACD,CAAC,EAKyB;GACzB,UAAU,KAAK;GACf;GACA;GACD,CAAC;;;;;CAQJ,AAAQ,eAAe,QAAwB;AAC7C,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,sBAAsB;AAExC,SAAO;;;;;CAMT,AAAQ,gBAAgB,SAAyB;AAC/C,MAAI,CAAC,eAAe,QAAQ,CAC1B,OAAM,IAAI,MAAM,6BAA6B,UAAU;AAEzD,SAAO;;;;;CAMT,AAAQ,eAAe,QAAwB;AAC7C,MAAI,SAAS,KAAK,SAAS,YACzB,OAAM,IAAI,MACR,gBAAgB,OAAO,uCAAuC,YAAY,GAC3E;AAEH,SAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["userTransactions: Transaction[]","userTransactionIndexes: number[]","deflexSignedTxns: Uint8Array[]","userSignedTxns: Uint8Array[]","signedTxns: Uint8Array[]","appOptIns: SwapTransaction[]","swapTxns: SwapTransaction[]","appOptInTxns: Transaction[]","status: number","statusText: string","data: unknown","errorData: unknown","body: FetchSwapTxnsBody"],"sources":["../src/constants.ts","../src/composer.ts","../src/utils.ts","../src/client.ts"],"sourcesContent":["/**\n * Supported DEX protocols for swap routing\n */\nexport enum Protocol {\n TinymanV2 = 'TinymanV2',\n Algofi = 'Algofi',\n Algomint = 'Algomint',\n Pact = 'Pact',\n Folks = 'Folks',\n TAlgo = 'TAlgo',\n}\n\n/**\n * Deprecated protocols that are automatically excluded from routing\n *\n * @internal\n */\nexport const DEPRECATED_PROTOCOLS = ['Humble', 'Tinyman'] as const\n\n/** Default Algod node URI for mainnet */\nexport const DEFAULT_ALGOD_URI = 'https://mainnet-api.4160.nodely.dev/'\n\n/** Default Algod node token (empty for public nodes) */\nexport const DEFAULT_ALGOD_TOKEN = ''\n\n/** Default Algod node port */\nexport const DEFAULT_ALGOD_PORT = 443\n\n/** Default Deflex API base URL */\nexport const DEFAULT_API_BASE_URL = 'https://deflex.txnlab.dev/api'\n\n/** Default fee in basis points (0.15%) */\nexport const DEFAULT_FEE_BPS = 15\n\n/** Maximum allowed fee in basis points (3.00%) */\nexport const MAX_FEE_BPS = 300\n\n/** Default maximum transaction group size */\nexport const DEFAULT_MAX_GROUP_SIZE = 16\n\n/** Default maximum routing depth (number of hops) */\nexport const DEFAULT_MAX_DEPTH = 4\n\n/** Default auto opt-in setting (automatic asset/app opt-in detection) */\nexport const DEFAULT_AUTO_OPT_IN = false\n\n/** Default number of rounds to wait for transaction confirmation */\nexport const DEFAULT_CONFIRMATION_ROUNDS = 4\n","import {\n assignGroupID,\n decodeUnsignedTransaction,\n isValidAddress,\n signLogicSigTransactionObject,\n signTransaction,\n LogicSigAccount,\n makeApplicationOptInTxnFromObject,\n msgpackRawDecode,\n Transaction,\n waitForConfirmation,\n} from 'algosdk'\nimport { DEFAULT_CONFIRMATION_ROUNDS } from './constants'\nimport type {\n FetchQuoteResponse,\n DeflexTransaction,\n SwapTransaction,\n DeflexSignature,\n DeflexQuote,\n} from './types'\nimport type { AlgorandClient } from '@algorandfoundation/algokit-utils'\nimport type { TransactionSigner } from 'algosdk'\n\n/**\n * A signer function for signing transaction groups\n *\n * Can be either:\n * - A TransactionSigner: algosdk.TransactionSigner\n * - A simpler inline function that only accepts the transaction group\n */\nexport type SignerFunction =\n | TransactionSigner\n | ((txns: Transaction[]) => Promise<Uint8Array[]>)\n\n/**\n * Status of the SwapComposer transaction group lifecycle\n */\nexport enum SwapComposerStatus {\n /** The atomic group is still under construction. */\n BUILDING,\n\n /** The atomic group has been finalized, but not yet signed. */\n BUILT,\n\n /** The atomic group has been finalized and signed, but not yet submitted to the network. */\n SIGNED,\n\n /** The atomic group has been finalized, signed, and submitted to the network. */\n SUBMITTED,\n\n /** The atomic group has been finalized, signed, submitted, and successfully committed to a block. */\n COMMITTED,\n}\n\n/**\n * Configuration for creating a SwapComposer instance\n */\nexport interface SwapComposerConfig {\n /** The quote response from fetchQuote() or newQuote() */\n readonly quote: FetchQuoteResponse | DeflexQuote\n /** The swap transactions from fetchSwapTransactions() */\n readonly deflexTxns: DeflexTransaction[]\n /** AlgorandClient instance for blockchain operations */\n readonly algorand: AlgorandClient\n /** The address of the account that will sign transactions */\n readonly address: string\n /** Transaction signer function */\n readonly signer: SignerFunction\n}\n\n/**\n * Composer for building and executing atomic swap transaction groups\n *\n * The SwapComposer allows you to build complex transaction groups by adding custom\n * transactions before and after swap transactions. It handles pre-signed transactions,\n * automatic app opt-ins, and provides a fluent API for transaction group construction.\n *\n * @example\n * ```typescript\n * const quote = await deflex.fetchQuote({ ... })\n * const composer = await deflex.newSwap({ quote, address, slippage })\n *\n * await composer\n * .addTransaction(customTxn)\n * .addSwapTransactions()\n * .execute(signer)\n * ```\n */\nexport class SwapComposer {\n /** The maximum size of an atomic transaction group. */\n static MAX_GROUP_SIZE: number = 16\n\n private status: SwapComposerStatus = SwapComposerStatus.BUILDING\n private transactions: SwapTransaction[] = []\n private swapTransactionsAdded = false\n private signedTxns: Uint8Array[] = []\n private txIds: string[] = []\n\n private readonly requiredAppOptIns: number[]\n private readonly deflexTxns: DeflexTransaction[]\n private readonly algorand: AlgorandClient\n private readonly address: string\n private readonly signer: TransactionSigner | SignerFunction\n\n /**\n * Create a new SwapComposer instance\n *\n * Note: Most developers should use DeflexClient.newSwap() instead of constructing\n * this directly, as the factory method handles fetching swap transactions automatically.\n *\n * @param config - Configuration for the composer\n * @param config.requiredAppOptIns - The quote response from fetchQuote()\n * @param config.deflexTxns - The swap transactions from fetchSwapTransactions()\n * @param config.algorand - AlgorandClient instance for blockchain operations\n * @param config.address - The address of the account that will sign transactions\n * @param config.signer - Transaction signer function\n */\n constructor(config: SwapComposerConfig) {\n // Validate required parameters\n if (!config.quote) {\n throw new Error('Quote is required')\n }\n if (!config.deflexTxns) {\n throw new Error('Swap transactions are required')\n }\n if (config.deflexTxns.length === 0) {\n throw new Error('Swap transactions array cannot be empty')\n }\n if (!config.algorand) {\n throw new Error('AlgorandClient instance is required')\n }\n if (!config.signer) {\n throw new Error('Signer is required')\n }\n\n this.requiredAppOptIns = config.quote.requiredAppOptIns\n this.deflexTxns = config.deflexTxns\n this.algorand = config.algorand\n this.address = this.validateAddress(config.address)\n this.signer = config.signer\n }\n\n /**\n * Get the status of this composer's transaction group\n *\n * @returns The current status of the transaction group\n */\n getStatus(): SwapComposerStatus {\n return this.status\n }\n\n /**\n * Get the number of transactions currently in this atomic group\n *\n * @returns The number of transactions in the group\n */\n count(): number {\n return this.transactions.length\n }\n\n /**\n * Add a transaction to the atomic group\n *\n * Transactions are added in the order methods are called. For example:\n * ```typescript\n * composer\n * .addTransaction(txn1) // Added first\n * .addSwapTransactions() // Added second\n * .addTransaction(txn2) // Added third\n * ```\n *\n * @param transaction - The transaction to add\n * @returns This composer instance for chaining\n * @throws Error if the composer is not in the BUILDING status\n * @throws Error if the maximum group size is exceeded\n */\n addTransaction(transaction: Transaction): this {\n if (this.status !== SwapComposerStatus.BUILDING) {\n throw new Error(\n 'Cannot add transactions when composer status is not BUILDING',\n )\n }\n\n if (this.transactions.length === SwapComposer.MAX_GROUP_SIZE) {\n throw new Error(\n `Adding an additional transaction exceeds the maximum atomic group size of ${SwapComposer.MAX_GROUP_SIZE}`,\n )\n }\n\n this.transactions.push({ txn: transaction })\n return this\n }\n\n /**\n * Add swap transactions to the atomic group\n *\n * This method automatically processes required app opt-ins and adds all swap\n * transactions from the quote. Can only be called once per composer instance.\n *\n * @returns This composer instance for chaining\n * @throws Error if the swap transactions have already been added\n * @throws Error if the composer is not in the BUILDING status\n * @throws Error if the maximum group size is exceeded\n */\n async addSwapTransactions(): Promise<this> {\n if (this.swapTransactionsAdded) {\n throw new Error('Swap transactions have already been added')\n }\n\n if (this.status !== SwapComposerStatus.BUILDING) {\n throw new Error(\n 'Cannot add swap transactions when composer status is not BUILDING',\n )\n }\n\n const processedTxns = await this.processSwapTransactions()\n const newLength = this.transactions.length + processedTxns.length\n\n if (newLength > SwapComposer.MAX_GROUP_SIZE) {\n throw new Error(\n `Adding swap transactions exceeds the maximum atomic group size of ${SwapComposer.MAX_GROUP_SIZE}`,\n )\n }\n\n this.transactions.push(...processedTxns)\n\n this.swapTransactionsAdded = true\n return this\n }\n\n /**\n * Sign the transaction group\n *\n * Automatically adds swap transactions if not already added, builds the atomic group,\n * and signs all transactions using the configured signer.\n *\n * @returns A promise that resolves to an array of signed transaction blobs\n *\n * @example\n * ```typescript\n * const signedTxns = await composer.sign()\n * ```\n */\n async sign(): Promise<Uint8Array[]> {\n if (this.status >= SwapComposerStatus.SIGNED) {\n return this.signedTxns\n }\n\n // Auto-add swap transactions if needed\n if (!this.swapTransactionsAdded) {\n await this.addSwapTransactions()\n }\n\n // Build the transaction group, ensure status is BUILT\n const transactions = this.buildGroup()\n\n // Separate user transactions and pre-signed transactions\n const userTransactions: Transaction[] = []\n const userTransactionIndexes: number[] = []\n const deflexSignedTxns: Uint8Array[] = []\n\n for (let i = 0; i < transactions.length; i++) {\n const item = transactions[i]\n if (!item) continue\n\n if (!item.deflexSignature) {\n // User transaction - needs user signature\n userTransactions.push(item.txn)\n userTransactionIndexes.push(userTransactions.length - 1)\n } else {\n // Pre-signed transaction - re-sign with Deflex signature\n const signedTxnBlob = this.signDeflexTransaction(\n item.txn,\n item.deflexSignature,\n )\n deflexSignedTxns.push(signedTxnBlob)\n }\n }\n\n // Sign user transactions\n let userSignedTxns: Uint8Array[] = []\n if (userTransactions.length > 0) {\n userSignedTxns = await (this.signer as TransactionSigner)(\n userTransactions,\n userTransactionIndexes,\n )\n }\n\n // Combine user-signed and pre-signed transactions in correct order\n const signedTxns: Uint8Array[] = []\n let userSignedIndex = 0\n let deflexSignedIndex = 0\n\n for (const item of transactions) {\n if (!item.deflexSignature) {\n const signedTxn = userSignedTxns[userSignedIndex]\n if (signedTxn) {\n signedTxns.push(signedTxn)\n }\n userSignedIndex++\n } else {\n const deflexSignedTxn = deflexSignedTxns[deflexSignedIndex]\n if (deflexSignedTxn) {\n signedTxns.push(deflexSignedTxn)\n }\n deflexSignedIndex++\n }\n }\n\n const txIds = this.transactions.map((t) => t.txn.txID())\n\n this.signedTxns = signedTxns\n this.txIds = txIds\n this.status = SwapComposerStatus.SIGNED\n\n return signedTxns\n }\n\n /**\n * Submit the signed transactions to the network\n *\n * This method signs the transaction group (if not already signed) and submits\n * it to the Algorand network. Does not wait for confirmation.\n *\n * @returns The transaction IDs\n * @throws Error if the transaction group has already been submitted\n *\n * @example\n * ```typescript\n * const txIds = await composer.submit()\n * console.log('Submitted transactions:', txIds)\n * ```\n */\n async submit(): Promise<string[]> {\n if (this.status > SwapComposerStatus.SUBMITTED) {\n throw new Error('Transaction group cannot be resubmitted')\n }\n\n const stxns = await this.sign()\n await this.algorand.client.algod.sendRawTransaction(stxns).do()\n\n this.status = SwapComposerStatus.SUBMITTED\n return this.txIds\n }\n\n /**\n * Execute the swap\n *\n * Signs the transaction group, submits it to the network, and waits for confirmation.\n * This is the primary method for executing swaps and combines sign(), submit(), and\n * waitForConfirmation() into a single call.\n *\n * @param waitRounds - The number of rounds to wait for confirmation (default: 4)\n * @returns Object containing the confirmed round and transaction IDs\n * @throws Error if the transaction group has already been committed\n *\n * @example\n * ```typescript\n * const result = await composer.execute()\n * console.log(`Confirmed in round ${result.confirmedRound}`)\n * console.log('Transaction IDs:', result.txIds)\n * ```\n */\n async execute(waitRounds: number = DEFAULT_CONFIRMATION_ROUNDS): Promise<{\n confirmedRound: bigint\n txIds: string[]\n }> {\n if (this.status === SwapComposerStatus.COMMITTED) {\n throw new Error(\n 'Transaction group has already been executed successfully',\n )\n }\n\n const txIds = await this.submit()\n\n const confirmedTxnInfo = await waitForConfirmation(\n this.algorand.client.algod,\n txIds[0]!,\n waitRounds,\n )\n\n this.status = SwapComposerStatus.COMMITTED\n\n const confirmedRound = confirmedTxnInfo.confirmedRound!\n\n return {\n confirmedRound,\n txIds,\n }\n }\n\n /**\n * Validates an Algorand address\n */\n private validateAddress(address: string): string {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid Algorand address: ${address}`)\n }\n return address\n }\n\n /**\n * Processes app opt-ins and decodes swap transactions from API response\n */\n private async processSwapTransactions(): Promise<SwapTransaction[]> {\n // Process required app opt-ins\n const appOptIns: SwapTransaction[] = await this.processRequiredAppOptIns()\n\n // Decode and process swap transactions from API\n const swapTxns: SwapTransaction[] = []\n for (let i = 0; i < this.deflexTxns.length; i++) {\n const deflexTxn = this.deflexTxns[i]\n if (!deflexTxn) continue\n\n try {\n // Decode transaction from base64 data\n const txnBytes = Buffer.from(deflexTxn.data, 'base64')\n const txn = decodeUnsignedTransaction(txnBytes)\n\n // Remove group ID (will be reassigned later)\n delete txn.group\n\n if (deflexTxn.signature !== false) {\n // Pre-signed transaction - needs re-signing with provided signature\n swapTxns.push({\n txn,\n deflexSignature: deflexTxn.signature,\n })\n } else {\n // User transaction - needs user signature\n swapTxns.push({\n txn,\n })\n }\n } catch (error) {\n throw new Error(\n `Failed to process swap transaction at index ${i}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n return [...appOptIns, ...swapTxns]\n }\n\n /**\n * Creates opt-in transactions for apps the user hasn't opted into yet\n */\n private async processRequiredAppOptIns(): Promise<SwapTransaction[]> {\n // Fetch account information\n const accountInfo = await this.algorand.account.getInformation(this.address)\n\n // Check app opt-ins\n const userApps =\n accountInfo?.appsLocalState?.map((app) => Number(app.id)) || []\n const appsToOptIn = this.requiredAppOptIns.filter(\n (appId) => !userApps.includes(appId),\n )\n\n // Create opt-in transactions if needed\n const appOptInTxns: Transaction[] = []\n if (appsToOptIn.length > 0) {\n const suggestedParams = await this.algorand.client.algod\n .getTransactionParams()\n .do()\n\n for (const appId of appsToOptIn) {\n const optInTxn = makeApplicationOptInTxnFromObject({\n sender: this.address,\n appIndex: appId,\n suggestedParams,\n })\n appOptInTxns.push(optInTxn)\n }\n }\n\n return appOptInTxns.map((txn) => ({ txn }))\n }\n\n /**\n * Finalizes the transaction group by assigning group IDs\n *\n * The composer's status will be at least BUILT after executing this method.\n */\n private buildGroup(): SwapTransaction[] {\n if (this.status === SwapComposerStatus.BUILDING) {\n if (this.transactions.length === 0) {\n throw new Error('Cannot build a group with 0 transactions')\n }\n if (this.transactions.length > 1) {\n assignGroupID(this.transactions.map((t) => t.txn))\n }\n this.status = SwapComposerStatus.BUILT\n }\n return this.transactions\n }\n\n /**\n * Re-signs a Deflex transaction using the provided logic signature or secret key\n */\n private signDeflexTransaction(\n transaction: Transaction,\n signature: DeflexSignature,\n ): Uint8Array {\n try {\n if (signature.type === 'logic_signature') {\n // Decode the signature value to extract the logic signature\n const valueArray = signature.value as Record<string, number>\n const valueBytes = new Uint8Array(Object.values(valueArray))\n const decoded = msgpackRawDecode(valueBytes) as {\n lsig?: { l: Uint8Array; arg?: Uint8Array[] }\n }\n\n if (!decoded.lsig) {\n throw new Error('Logic signature structure missing lsig field')\n }\n\n const lsig = decoded.lsig\n const logicSigAccount = new LogicSigAccount(lsig.l, lsig.arg)\n\n const signedTxn = signLogicSigTransactionObject(\n transaction,\n logicSigAccount,\n )\n return signedTxn.blob\n } else if (signature.type === 'secret_key') {\n // Convert signature.value (Record<string, number>) to Uint8Array\n const valueArray = signature.value as Record<string, number>\n const secretKey = new Uint8Array(Object.values(valueArray))\n const signedTxn = signTransaction(transaction, secretKey)\n return signedTxn.blob\n } else {\n throw new Error(`Unsupported signature type: ${signature.type}`)\n }\n } catch (error) {\n throw new Error(\n `Failed to re-sign transaction: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n","/**\n * HTTP error with status code and response data\n */\nexport class HTTPError extends Error {\n constructor(\n public status: number,\n public statusText: string,\n public data: unknown,\n ) {\n super(`HTTP ${status} ${statusText}`)\n this.name = 'HTTPError'\n }\n}\n\n/**\n * Make an HTTP request and parse JSON response\n *\n * Simple wrapper around native fetch for API calls. Throws HTTPError for\n * non-2xx responses.\n *\n * @param url - The URL to request\n * @param options - Fetch options\n * @returns Parsed JSON response\n * @throws HTTPError if the response status is not ok\n */\nexport async function request<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n const response = await fetch(url, options)\n\n if (!response.ok) {\n let errorData: unknown\n\n try {\n errorData = await response.json()\n } catch {\n try {\n errorData = await response.text()\n } catch {\n errorData = 'Failed to parse error response'\n }\n }\n\n throw new HTTPError(\n response.status,\n response.statusText,\n JSON.stringify(errorData),\n )\n }\n\n return response.json() as Promise<T>\n}\n","import { AlgorandClient } from '@algorandfoundation/algokit-utils'\nimport { isValidAddress } from 'algosdk'\nimport { SwapComposer, type SignerFunction } from './composer'\nimport {\n DEFAULT_ALGOD_PORT,\n DEFAULT_ALGOD_TOKEN,\n DEFAULT_ALGOD_URI,\n DEFAULT_API_BASE_URL,\n DEFAULT_AUTO_OPT_IN,\n DEFAULT_FEE_BPS,\n DEFAULT_MAX_DEPTH,\n DEFAULT_MAX_GROUP_SIZE,\n DEPRECATED_PROTOCOLS,\n MAX_FEE_BPS,\n} from './constants'\nimport { request } from './utils'\nimport type {\n FetchQuoteResponse,\n FetchSwapTxnsResponse,\n DeflexConfig,\n DeflexConfigParams,\n FetchSwapTxnsParams,\n FetchSwapTxnsBody,\n FetchQuoteParams,\n DeflexQuote,\n} from './types'\n\n/**\n * Client for interacting with the Deflex order router API\n *\n * The DeflexClient provides methods to fetch swap quotes and create transaction composers\n * for executing swaps on the Algorand blockchain. It handles API communication, transaction\n * validation, and automatic asset/app opt-in detection.\n *\n * @example\n * ```typescript\n * const deflex = new DeflexClient({\n * apiKey: 'your-api-key',\n * })\n * ```\n *\n * @example\n * ```typescript\n * const deflex = new DeflexClient({\n * apiKey: 'your-api-key',\n * algodUri: 'https://mainnet-api.4160.nodely.dev/',\n * algodToken: '',\n * algodPort: 443,\n * referrerAddress: 'REFERRER_ADDRESS...',\n * feeBps: 15,\n * autoOptIn: false,\n * })\n * ```\n */\nexport class DeflexClient {\n private readonly baseUrl: string = DEFAULT_API_BASE_URL\n private readonly config: DeflexConfig\n private readonly algorand: AlgorandClient\n\n /**\n * Create a new DeflexClient instance\n *\n * @param config - Configuration parameters\n * @param config.apiKey - API key for Deflex API (required)\n * @param config.algodUri - Algod node URI (default: https://mainnet-api.4160.nodely.dev/)\n * @param config.algodToken - Algod node token (default: '')\n * @param config.algodPort - Algod node port (default: 443)\n * @param config.referrerAddress - Referrer address for fee sharing (receives 25% of swap fees)\n * @param config.feeBps - Fee in basis points (default: 15 = 0.15%, max: 300 = 3.00%)\n * @param config.autoOptIn - Automatically detect and add required opt-in transactions (default: false)\n */\n constructor(config: DeflexConfigParams) {\n // Validate and set config\n this.config = {\n apiKey: this.validateApiKey(config.apiKey),\n algodUri: config.algodUri ?? DEFAULT_ALGOD_URI,\n algodToken: config.algodToken ?? DEFAULT_ALGOD_TOKEN,\n algodPort: config.algodPort ?? DEFAULT_ALGOD_PORT,\n referrerAddress: config.referrerAddress\n ? this.validateAddress(config.referrerAddress)\n : undefined,\n feeBps: this.validateFeeBps(config.feeBps ?? DEFAULT_FEE_BPS),\n autoOptIn: config.autoOptIn ?? DEFAULT_AUTO_OPT_IN,\n }\n\n // Create AlgorandClient\n this.algorand = AlgorandClient.fromConfig({\n algodConfig: {\n server: this.config.algodUri,\n port: this.config.algodPort,\n token: this.config.algodToken,\n },\n })\n }\n\n /**\n * Fetch a swap quote from the Deflex API\n *\n * Requests optimal swap routing from the Deflex API. The quote includes routing\n * information, price impact, required opt-ins, and an encrypted transaction payload.\n *\n * @param params - Parameters for the quote request\n * @param params.fromASAID - The ID of the asset to swap from\n * @param params.toASAID - The ID of the asset to swap to\n * @param params.amount - The amount of the asset to swap in base units\n * @param params.type - The type of the quote (default: 'fixed-input')\n * @param params.disabledProtocols - List of protocols to disable (default: [])\n * @param params.maxGroupSize - The maximum group size (default: 16)\n * @param params.maxDepth - The maximum depth (default: 4)\n * @param params.address - The address of the account that will perform the swap (recommended when using `config.autoOptIn` or `params.optIn`)\n * @param params.optIn - Whether to include asset opt-in transaction\n * - If true: API reduces maxGroupSize by 1 and includes opt-in (always included, even if not needed)\n * - If false: No opt-in transaction included\n * - If undefined: Falls back to `config.autoOptIn` behavior with account check (if `params.address` is provided)\n * @returns A FetchQuoteResponse object with routing information\n *\n * @example\n * ```typescript\n * const quote = await deflex.fetchQuote({\n * address: 'ABC...',\n * fromASAID: 0, // ALGO\n * toASAID: 31566704, // USDC\n * amount: 1_000_000, // 1 ALGO\n * })\n * ```\n */\n async fetchQuote(params: FetchQuoteParams): Promise<FetchQuoteResponse> {\n const {\n fromASAID,\n toASAID,\n amount,\n type = 'fixed-input',\n disabledProtocols = [],\n maxGroupSize = DEFAULT_MAX_GROUP_SIZE,\n maxDepth = DEFAULT_MAX_DEPTH,\n optIn,\n address,\n } = params\n\n // Always include deprecated protocols in disabled list\n const allDisabledProtocols = [\n ...new Set([...DEPRECATED_PROTOCOLS, ...disabledProtocols]),\n ]\n\n let includeOptIn = optIn\n if (includeOptIn === undefined && this.config.autoOptIn) {\n if (address) {\n includeOptIn = await this.needsAssetOptIn(\n this.validateAddress(address),\n toASAID,\n )\n } else {\n console.warn(\n 'autoOptIn is enabled but no address provided to fetchQuote(). Asset opt-in check skipped.',\n )\n }\n }\n\n const url = new URL(`${this.baseUrl}/fetchQuote`)\n\n url.searchParams.append('apiKey', this.config.apiKey)\n url.searchParams.append('algodUri', this.config.algodUri)\n url.searchParams.append('algodToken', this.config.algodToken)\n url.searchParams.append('algodPort', String(this.config.algodPort))\n url.searchParams.append('feeBps', this.config.feeBps.toString())\n url.searchParams.append('fromASAID', BigInt(fromASAID).toString())\n url.searchParams.append('toASAID', BigInt(toASAID).toString())\n url.searchParams.append('amount', BigInt(amount).toString())\n url.searchParams.append('type', type)\n url.searchParams.append('disabledProtocols', allDisabledProtocols.join(','))\n url.searchParams.append('maxGroupSize', maxGroupSize.toString())\n url.searchParams.append('maxDepth', maxDepth.toString())\n url.searchParams.append('optIn', String(includeOptIn))\n\n if (this.config.referrerAddress) {\n url.searchParams.append('referrerAddress', this.config.referrerAddress)\n }\n\n return request<FetchQuoteResponse>(url.toString())\n }\n\n /**\n * Check if asset opt-in is required for the output asset\n *\n * Convenience method to determine if an address needs to opt into the output asset\n * of a swap. This is useful when you want to get a quote without requiring wallet\n * connection upfront, but need to know whether to set `optIn: true` in fetchQuote()\n * to ensure proper routing (as opt-ins reduce maxGroupSize by 1).\n *\n * Note: If you enable `config.autoOptIn`, this check is handled automatically when\n * an address is provided to fetchQuote().\n *\n * @param address - The address to check\n * @param assetId - The output asset ID to check\n * @returns True if asset opt-in is required, false otherwise (always false for ALGO)\n *\n * @example\n * ```typescript\n * // Check if opt-in needed for output asset before fetching quote\n * const needsOptIn = await deflex.needsAssetOptIn(userAddress, toAssetId)\n * const quote = await deflex.fetchQuote({\n * fromAssetId,\n * toAssetId,\n * amount,\n * optIn: needsOptIn,\n * })\n * ```\n */\n async needsAssetOptIn(\n address: string,\n assetId: number | bigint,\n ): Promise<boolean> {\n // Fetch account information\n const accountInfo = await this.algorand.account.getInformation(address)\n\n // Check if asset opt-in is required\n return (\n BigInt(assetId) !== 0n &&\n accountInfo?.assets?.find(\n (asset) => asset.assetId === BigInt(assetId),\n ) === undefined\n )\n }\n\n /**\n * Fetch swap transactions from the Deflex API\n *\n * Decrypts the quote payload and generates executable swap transactions for the\n * specified signer address with the given slippage tolerance.\n *\n * @param params - Parameters for the swap transaction request\n * @param params.quote - The quote response from fetchQuote()\n * @param params.address - The address of the signer\n * @param params.slippage - The slippage tolerance as a percentage (e.g., 1 for 1%)\n * @returns A FetchSwapTxnsResponse object with transaction data\n */\n async fetchSwapTransactions(\n params: FetchSwapTxnsParams,\n ): Promise<FetchSwapTxnsResponse> {\n const { quote, address, slippage } = params\n\n // Validate signer address\n this.validateAddress(address)\n\n const url = new URL(`${this.baseUrl}/fetchExecuteSwapTxns`)\n\n const body: FetchSwapTxnsBody = {\n apiKey: this.config.apiKey,\n address,\n txnPayloadJSON: quote.txnPayload,\n slippage,\n }\n\n return request<FetchSwapTxnsResponse>(url.toString(), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n })\n }\n\n /**\n * Fetch a quote and return an enhanced quote result\n *\n * This is the recommended way to fetch quotes. It returns an object that\n * extends the raw API response with additional metadata and type normalization.\n *\n * @param params - Parameters for the quote request\n * @param params.fromASAID - The ID of the asset to swap from\n * @param params.toASAID - The ID of the asset to swap to\n * @param params.amount - The amount of the asset to swap in base units\n * @param params.type - The type of the quote (default: 'fixed-input')\n * @param params.disabledProtocols - List of protocols to disable (default: [])\n * @param params.maxGroupSize - The maximum group size (default: 16)\n * @param params.maxDepth - The maximum depth (default: 4)\n * @param params.address - The address of the account that will perform the swap (recommended when using `config.autoOptIn` or `params.optIn`)\n * @param params.optIn - Whether to include asset opt-in transaction\n * @returns A DeflexQuote enhanced quote result\n *\n * @example\n * ```typescript\n * const quote = await deflex.newQuote({\n * address: 'ABC...',\n * fromASAID: 0,\n * toASAID: 31566704,\n * amount: 1_000_000,\n * })\n *\n * console.log(quote.quote) // bigint - quoted amount\n * console.log(quote.fromASAID) // number - input asset ID\n * console.log(quote.toASAID) // number - output asset ID\n * console.log(quote.amount) // bigint - original request amount\n * console.log(quote.createdAt) // number - timestamp\n * ```\n */\n async newQuote(params: FetchQuoteParams): Promise<DeflexQuote> {\n const response = await this.fetchQuote(params)\n\n return {\n ...response,\n quote: response.quote === '' ? 0n : BigInt(response.quote),\n amount: BigInt(params.amount),\n address: params.address ?? undefined,\n createdAt: Date.now(),\n }\n }\n\n /**\n * Create a SwapComposer instance\n *\n * This factory method creates a composer that allows you to add custom transactions\n * before and after the swap transactions, with automatic handling of pre-signed transactions\n * and opt-ins.\n *\n * @param config.quote - The quote result from newQuote() or raw API response from fetchQuote()\n * @param config.address - The address of the signer\n * @param config.slippage - The slippage tolerance\n * @param config.signer - Transaction signer function\n * @returns A SwapComposer instance ready for building transaction groups\n *\n * @example\n * ```typescript\n * // Basic swap\n * const quote = await deflex.newQuote({ ... })\n * await deflex.newSwap({ quote, address, slippage, signer })\n * .execute()\n * ```\n *\n * @example\n * ```typescript\n * // Advanced swap with custom transactions\n * const quote = await deflex.newQuote({ ... })\n * const swap = await deflex.newSwap({\n * quote,\n * address,\n * slippage,\n * signer,\n * })\n *\n * console.log(swap.getStatus()) // BUILDING\n *\n * const signedTxns = await swap\n * .addTransaction(beforeTxn)\n * .addSwapTransactions() // Adds swap transactions to the group\n * .addTransaction(afterTxn)\n * .sign()\n *\n * console.log(swap.getStatus()) // SIGNED\n *\n * const result = await swap.execute(waitRounds)\n * console.log(result.confirmedRound, result.txIds)\n *\n * console.log(swap.getStatus()) // COMMITTED\n * ```\n */\n async newSwap(config: {\n quote: DeflexQuote | FetchQuoteResponse\n address: string\n slippage: number\n signer: SignerFunction\n }): Promise<SwapComposer> {\n const { quote, address, slippage, signer } = config\n\n const swapResponse = await this.fetchSwapTransactions({\n quote,\n address,\n slippage,\n })\n\n // Create the composer\n const composer = new SwapComposer({\n quote,\n deflexTxns: swapResponse.txns,\n algorand: this.algorand,\n address,\n signer,\n })\n\n return composer\n }\n\n /**\n * Validates the API key\n */\n private validateApiKey(apiKey: string): string {\n if (!apiKey) {\n throw new Error('API key is required')\n }\n return apiKey\n }\n\n /**\n * Validates an Algorand address\n */\n private validateAddress(address: string): string {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid Algorand address: ${address}`)\n }\n return address\n }\n\n /**\n * Validates the fee in basis points (max 300 = 3.00%)\n */\n private validateFeeBps(feeBps: number): number {\n if (feeBps < 0 || feeBps > MAX_FEE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;;;;CAqCJ,MAAM,SAAS,QAAgD;EAC7D,MAAM,WAAW,MAAM,KAAK,WAAW,OAAO;AAE9C,SAAO;GACL,GAAG;GACH,OAAO,SAAS,UAAU,KAAK,KAAK,OAAO,SAAS,MAAM;GAC1D,QAAQ,OAAO,OAAO,OAAO;GAC7B,SAAS,OAAO,WAAW;GAC3B,WAAW,KAAK,KAAK;GACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmDH,MAAM,QAAQ,QAKY;EACxB,MAAM,EAAE,OAAO,SAAS,UAAU,WAAW;AAiB7C,SARiB,IAAI,aAAa;GAChC;GACA,aATmB,MAAM,KAAK,sBAAsB;IACpD;IACA;IACA;IACD,CAAC,EAKyB;GACzB,UAAU,KAAK;GACf;GACA;GACD,CAAC;;;;;CAQJ,AAAQ,eAAe,QAAwB;AAC7C,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,sBAAsB;AAExC,SAAO;;;;;CAMT,AAAQ,gBAAgB,SAAyB;AAC/C,MAAI,CAAC,eAAe,QAAQ,CAC1B,OAAM,IAAI,MAAM,6BAA6B,UAAU;AAEzD,SAAO;;;;;CAMT,AAAQ,eAAe,QAAwB;AAC7C,MAAI,SAAS,KAAK,SAAS,YACzB,OAAM,IAAI,MACR,gBAAgB,OAAO,uCAAuC,YAAY,GAC3E;AAEH,SAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@txnlab/deflex",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.3",
|
|
4
4
|
"description": "TypeScript/JavaScript SDK for Deflex Order Router - smart order routing and DEX aggregation on Algorand",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"algorand",
|
|
@@ -45,18 +45,11 @@
|
|
|
45
45
|
"node": ">=20"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
|
-
"@eslint/js": "9.38.0",
|
|
49
48
|
"@types/node": "24.9.1",
|
|
50
49
|
"@vitest/coverage-v8": "3.2.4",
|
|
51
|
-
"eslint": "9.38.0",
|
|
52
|
-
"eslint-config-prettier": "10.1.8",
|
|
53
|
-
"eslint-plugin-import-x": "4.16.1",
|
|
54
|
-
"np": "10.2.0",
|
|
55
|
-
"prettier": "3.6.2",
|
|
56
50
|
"publint": "0.3.15",
|
|
57
51
|
"tsdown": "0.15.9",
|
|
58
52
|
"typescript": "5.9.3",
|
|
59
|
-
"typescript-eslint": "8.46.2",
|
|
60
53
|
"vitest": "3.2.4"
|
|
61
54
|
},
|
|
62
55
|
"dependencies": {
|
|
@@ -65,14 +58,9 @@
|
|
|
65
58
|
},
|
|
66
59
|
"scripts": {
|
|
67
60
|
"build": "tsdown && publint --strict",
|
|
68
|
-
"ci": "pnpm run build && pnpm run lint && pnpm run format && pnpm run test",
|
|
69
61
|
"test": "vitest run",
|
|
70
62
|
"test:watch": "vitest",
|
|
71
63
|
"test:coverage": "vitest run --coverage",
|
|
72
|
-
"
|
|
73
|
-
"format": "prettier --check .",
|
|
74
|
-
"format:fix": "prettier --write .",
|
|
75
|
-
"typecheck": "tsc --noEmit",
|
|
76
|
-
"release": "np"
|
|
64
|
+
"typecheck": "tsc --noEmit"
|
|
77
65
|
}
|
|
78
66
|
}
|