@rhea-finance/cross-chain-aggregation-dex 1.0.6 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +277 -270
  2. package/dist/executors/aptos.d.mts +19 -0
  3. package/dist/executors/aptos.d.ts +19 -0
  4. package/dist/executors/aptos.js +140 -0
  5. package/dist/executors/aptos.js.map +1 -0
  6. package/dist/executors/aptos.mjs +138 -0
  7. package/dist/executors/aptos.mjs.map +1 -0
  8. package/dist/executors/bitcoin.d.mts +22 -0
  9. package/dist/executors/bitcoin.d.ts +22 -0
  10. package/dist/executors/bitcoin.js +153 -0
  11. package/dist/executors/bitcoin.js.map +1 -0
  12. package/dist/executors/bitcoin.mjs +151 -0
  13. package/dist/executors/bitcoin.mjs.map +1 -0
  14. package/dist/executors/evm.d.mts +18 -0
  15. package/dist/executors/evm.d.ts +18 -0
  16. package/dist/executors/evm.js +233 -0
  17. package/dist/executors/evm.js.map +1 -0
  18. package/dist/executors/evm.mjs +231 -0
  19. package/dist/executors/evm.mjs.map +1 -0
  20. package/dist/executors/near.d.mts +18 -0
  21. package/dist/executors/near.d.ts +18 -0
  22. package/dist/executors/near.js +162 -0
  23. package/dist/executors/near.js.map +1 -0
  24. package/dist/executors/near.mjs +160 -0
  25. package/dist/executors/near.mjs.map +1 -0
  26. package/dist/executors/solana.d.mts +20 -0
  27. package/dist/executors/solana.d.ts +20 -0
  28. package/dist/executors/solana.js +151 -0
  29. package/dist/executors/solana.js.map +1 -0
  30. package/dist/executors/solana.mjs +149 -0
  31. package/dist/executors/solana.mjs.map +1 -0
  32. package/dist/executors/sui.d.mts +19 -0
  33. package/dist/executors/sui.d.ts +19 -0
  34. package/dist/executors/sui.js +154 -0
  35. package/dist/executors/sui.js.map +1 -0
  36. package/dist/executors/sui.mjs +152 -0
  37. package/dist/executors/sui.mjs.map +1 -0
  38. package/dist/executors/tron.d.mts +24 -0
  39. package/dist/executors/tron.d.ts +24 -0
  40. package/dist/executors/tron.js +161 -0
  41. package/dist/executors/tron.js.map +1 -0
  42. package/dist/executors/tron.mjs +159 -0
  43. package/dist/executors/tron.mjs.map +1 -0
  44. package/dist/executors/zcash.d.mts +19 -0
  45. package/dist/executors/zcash.d.ts +19 -0
  46. package/dist/executors/zcash.js +158 -0
  47. package/dist/executors/zcash.js.map +1 -0
  48. package/dist/executors/zcash.mjs +156 -0
  49. package/dist/executors/zcash.mjs.map +1 -0
  50. package/dist/index.d.mts +278 -250
  51. package/dist/index.d.ts +278 -250
  52. package/dist/index.js +2369 -573
  53. package/dist/index.js.map +1 -1
  54. package/dist/index.mjs +2340 -560
  55. package/dist/index.mjs.map +1 -1
  56. package/dist/registry-DRYUqs7T.d.mts +532 -0
  57. package/dist/registry-DRYUqs7T.d.ts +532 -0
  58. package/dist/shared-BdH3hWuP.d.ts +23 -0
  59. package/dist/shared-BqpFeosz.d.mts +23 -0
  60. package/package.json +51 -17
package/README.md CHANGED
@@ -1,355 +1,362 @@
1
1
  # @rhea-finance/cross-chain-aggregation-dex
2
2
 
3
- Cross-chain DEX Aggregation SDK is a TypeScript SDK for multi-chain DEX aggregation and routing. It supports token swaps on Near chain and can integrate with NearIntents bridge protocol to enable cross-chain swaps.
3
+ TypeScript SDK for the unified multi-chain Swap API. It provides raw and normalized quote, build, execution, order status, report, and history interfaces without coupling the core package to a wallet or UI framework.
4
4
 
5
- ## Features
5
+ Supported chain families: EVM, Solana, Aptos, NEAR, Tron, Bitcoin, Zcash, and Sui.
6
6
 
7
- - 🔄 **DEX Aggregation Routing**: Automatically finds optimal swap paths
8
- - 🌉 **Cross-chain Support**: Integrates with NearIntents for cross-chain swaps
9
- - 🔀 **Pre-swap Handling**: Automatically handles conversion from non-bluechip tokens to bluechip tokens
10
- - 📦 **Type Safety**: Complete TypeScript type definitions
11
- - 🔌 **Adapter Pattern**: Abstracts dependencies through adapter interfaces for easy integration
12
-
13
- ## Installation
7
+ ## Install
14
8
 
15
9
  ```bash
16
- npm install @rhea-finance/cross-chain-aggregation-dex
17
- # or
18
10
  pnpm add @rhea-finance/cross-chain-aggregation-dex
19
- # or
20
- yarn add @rhea-finance/cross-chain-aggregation-dex
21
11
  ```
22
12
 
23
- ## Quick Start
13
+ ## Quick start
24
14
 
25
- ### 1. Create Adapters
15
+ All token amounts are base-unit decimal strings. Slippage uses basis points (`50` means 0.5%).
26
16
 
27
- First, you need to implement adapter interfaces to provide necessary dependencies:
17
+ ```ts
18
+ import { SwapClient, type QuoteRequest } from "@rhea-finance/cross-chain-aggregation-dex";
28
19
 
29
- ```typescript
30
- import {
31
- FindPathAdapter,
32
- IntentsQuotationAdapter,
33
- NearChainAdapter,
34
- ConfigAdapter,
35
- } from "@rhea-finance/cross-chain-aggregation-dex";
20
+ const getAccessToken = async () => sessionStorage.getItem("access-token") ?? "";
36
21
 
37
- // FindPath API adapter
38
- const findPathAdapter: FindPathAdapter = {
39
- async findPath(params) {
40
- const response = await fetch(
41
- `https://smartrouter.rhea.finance/findPath?${new URLSearchParams({
42
- amountIn: params.amountIn,
43
- tokenIn: params.tokenIn,
44
- tokenOut: params.tokenOut,
45
- pathDeep: "3",
46
- slippage: String(params.slippage),
47
- })}`
48
- );
49
- return response.json();
50
- },
51
- };
22
+ const client = new SwapClient({
23
+ baseUrl: "https://api.rhea.finance",
24
+ getAccessToken,
25
+ });
52
26
 
53
- // SmartX swapMultiDexPath adapter (optional, used to compare and show the best quote)
54
- const swapMultiDexPathAdapter = {
55
- async swapMultiDexPath(params: any) {
56
- const response = await fetch(
57
- `https://smartx.rhea.finance/swapMultiDexPath?${new URLSearchParams({
58
- amountIn: params.amountIn,
59
- tokenIn: params.tokenIn,
60
- tokenOut: params.tokenOut,
61
- slippage: String(params.slippage),
62
- pathDeep: "2",
63
- chainId: "0",
64
- routerCount: "1",
65
- skipUnwrapNativeToken: "false",
66
- user: params.user,
67
- receiveUser: params.receiveUser,
68
- })}`
69
- );
70
- return response.json();
27
+ const request: QuoteRequest = {
28
+ fromChain: "btc",
29
+ toChain: "near",
30
+ tokenIn: {
31
+ chain: "btc",
32
+ address: "btc",
33
+ symbol: "BTC",
34
+ decimals: 8,
35
+ isNative: true,
71
36
  },
72
- };
73
-
74
- // NearIntents quotation adapter
75
- const intentsQuotationAdapter: IntentsQuotationAdapter = {
76
- async quote(params) {
77
- // Call your NearIntents API
78
- const response = await fetch("https://your-api.com/intents/quote", {
79
- method: "POST",
80
- body: JSON.stringify(params),
81
- });
82
- return response.json();
37
+ tokenOut: {
38
+ chain: "near",
39
+ address: "wrap.near",
40
+ symbol: "wNEAR",
41
+ decimals: 24,
83
42
  },
43
+ amountIn: "100000",
44
+ slippageBps: 50,
45
+ sender: "bc1...",
46
+ recipient: "alice.near",
84
47
  };
85
48
 
86
- // Near chain interaction adapter
87
- const nearChainAdapter: NearChainAdapter = {
88
- async call({ transactions }) {
89
- // Use your Near wallet or RPC to call contracts
90
- // Return { status: "success", txHash: "..." }
91
- },
92
- async view({ contractId, methodName, args }) {
93
- // Use your Near RPC to view contract state
94
- },
95
- };
49
+ const quote = await client.quote(request);
50
+ const build = await client.buildSwap({ quote });
96
51
 
97
- // Configuration adapter
98
- const configAdapter: ConfigAdapter = {
99
- getRefExchangeId: () => "v2.ref-finance.near",
100
- getWrapNearContractId: () => "wrap.near",
101
- getFindPathUrl: () => "https://smartrouter.ref.finance",
102
- getTokenStorageDepositRead: () => "1250000000000000000000",
103
- };
52
+ // build is safe to inspect or send to another process.
53
+ // Register a chain executor before calling executeSwap.
104
54
  ```
105
55
 
106
- ### 2. Create DEX Aggregator Instance
56
+ `buildSwap()` never opens a wallet. To execute a build, inject one or more `ChainExecutor` implementations when creating the client:
107
57
 
108
- ```typescript
109
- import { NearSmartRouter } from "@rhea-finance/cross-chain-aggregation-dex";
58
+ ```ts
59
+ const clientWithExecutor = new SwapClient({
60
+ baseUrl: "https://api.rhea.finance",
61
+ getAccessToken,
62
+ executors: [bitcoinExecutor],
63
+ });
110
64
 
111
- const router = new NearSmartRouter({
112
- findPathAdapter,
113
- swapMultiDexPathAdapter,
114
- nearChainAdapter,
115
- configAdapter,
65
+ const result = await clientWithExecutor.executeSwap({
66
+ build,
67
+ waitFor: "submitted",
116
68
  });
117
69
  ```
118
70
 
119
- ### 3. Get Quote
71
+ ### Executor adapters
120
72
 
121
- ```typescript
122
- import { TokenInfo } from "@rhea-finance/cross-chain-aggregation-dex";
73
+ Each executor is imported from its own subpath and accepts a wallet-neutral adapter. The application decides whether that adapter wraps a browser wallet, server signer, RPC service, or HSM.
123
74
 
124
- const tokenIn: TokenInfo = {
125
- address: "token-a.near",
126
- symbol: "TOKENA",
127
- decimals: 18,
128
- chain: "near",
129
- };
130
-
131
- const tokenOut: TokenInfo = {
132
- address: "token-b.near",
133
- symbol: "TOKENB",
134
- decimals: 18,
135
- chain: "near",
75
+ ```ts
76
+ import { SwapClient } from "@rhea-finance/cross-chain-aggregation-dex";
77
+ import {
78
+ createEvmExecutor,
79
+ type EvmWalletAdapter,
80
+ } from "@rhea-finance/cross-chain-aggregation-dex/executors/evm";
81
+
82
+ const evmWallet: EvmWalletAdapter = {
83
+ getIdentityKey: () => wallet.address,
84
+ signMessage: (message) => wallet.signMessage(message),
85
+ sendTransaction: async (tx) => {
86
+ const response = await wallet.sendTransaction({
87
+ to: tx.to,
88
+ data: tx.data,
89
+ value: tx.value,
90
+ gasLimit: tx.gasLimit,
91
+ });
92
+ return { txHash: response.hash, raw: response };
93
+ },
94
+ signTypedData: async (request) =>
95
+ wallet.signTypedData(
96
+ request.typedData.domain,
97
+ request.typedData.types,
98
+ request.typedData.message
99
+ ),
100
+ waitForTransaction: async (txHash) => provider.waitForTransaction(txHash),
136
101
  };
137
102
 
138
- const quote = await router.quote({
139
- tokenIn,
140
- tokenOut,
141
- amountIn: "1000000000000000000", // 1 token (18 decimals)
142
- slippage: 50, // 0.5% (50 basis points)
143
- swapType: "EXACT_INPUT",
103
+ const client = new SwapClient({
104
+ baseUrl: "https://api.rhea.finance",
105
+ getAccessToken,
106
+ executors: [createEvmExecutor(evmWallet)],
144
107
  });
108
+ ```
145
109
 
146
- if (quote.success) {
147
- console.log("Amount out:", quote.amountOut);
148
- console.log("Min amount out:", quote.minAmountOut);
149
- console.log("Routes:", quote.routes);
150
- } else {
151
- console.error("Quote failed:", quote.error);
152
- }
110
+ Other executor subpaths follow the same pattern:
111
+
112
+ ```ts
113
+ import { createSolanaExecutor } from "@rhea-finance/cross-chain-aggregation-dex/executors/solana";
114
+ import { createAptosExecutor } from "@rhea-finance/cross-chain-aggregation-dex/executors/aptos";
115
+ import { createNearExecutor } from "@rhea-finance/cross-chain-aggregation-dex/executors/near";
116
+ import { createTronExecutor } from "@rhea-finance/cross-chain-aggregation-dex/executors/tron";
117
+ import { createBitcoinExecutor } from "@rhea-finance/cross-chain-aggregation-dex/executors/bitcoin";
118
+ import { createZcashExecutor } from "@rhea-finance/cross-chain-aggregation-dex/executors/zcash";
119
+ import { createSuiExecutor } from "@rhea-finance/cross-chain-aggregation-dex/executors/sui";
153
120
  ```
154
121
 
155
- ### 4. Execute Swap
122
+ Bitcoin requires `feeRate` in the build or a configured fallback:
156
123
 
157
- ```typescript
158
- const result = await router.executeSwap({
159
- quote,
160
- recipient: "user.near",
161
- depositAddress: "deposit.near", // optional
124
+ ```ts
125
+ const bitcoinExecutor = createBitcoinExecutor(bitcoinWallet, {
126
+ defaultFeeRate: 4,
162
127
  });
163
-
164
- if (result.success) {
165
- console.log("Transaction hash:", result.txHash);
166
- } else {
167
- console.error("Swap failed:", result.error);
168
- }
169
128
  ```
170
129
 
171
- ### 5. Complete Quote (DEX Aggregator + NearIntents)
130
+ Zcash adapters may return `{ requiresUserAction: true }` for legacy wallets that complete transfer confirmation in an external interface. The SDK returns `requires-user-action` without creating a fake transaction hash.
131
+
132
+ `swap({ quote })` is the convenience form of `buildSwap({ quote })` followed by `executeSwap({ build })`. It does not request another quote.
133
+
134
+ ## MCA swaps
135
+
136
+ MCA deposit and withdrawal are execution modes of the unified root API. Use the same `client.quote()`, `client.buildSwap()`, `client.swap()`, `client.report()`, and `client.getHistory()` methods as a regular swap. The SDK does not create MCA accounts or query lending positions.
172
137
 
173
- ```typescript
174
- import { completeQuote } from "@rhea-finance/cross-chain-aggregation-dex";
138
+ HTTP endpoint、请求/响应 JSON 和 curl 示例见 [MCA Swap HTTP API 文档](docs/MCA_SWAP_HTTP_API.md)。SDK 调用方式见 [MCA Swap SDK 文档](docs/MCA_SWAP_API.md)。
175
139
 
176
- const bluechipTokens = {
177
- USDT: {
178
- address: "usdt.tether-token.near",
179
- symbol: "USDT",
180
- decimals: 6,
181
- assetId: "nep141:usdt.tether-token.near",
140
+ ### Deposit into an MCA
141
+
142
+ The destination asset address is the Burrow token id expected by the Swap API. Execution reuses the registered source-chain executor.
143
+
144
+ ```ts
145
+ const quote = await client.quote({
146
+ flow: "deposit",
147
+ mcaAccountId: "account.near",
148
+ fromChain: "1",
149
+ toChain: "near",
150
+ tokenIn: ethereumUsdc,
151
+ tokenOut: mcaUsdc,
152
+ amountIn: "1000000",
153
+ slippageBps: 50,
154
+ sender: "0x...",
155
+ recipient: "account.near",
156
+ signerChain: "evm",
157
+ collateral: {
158
+ useAsCollateral: true,
182
159
  },
183
- USDC: {
184
- address: "17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
185
- symbol: "USDC",
186
- decimals: 6,
187
- assetId: "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
160
+ });
161
+
162
+ const result = await client.swap({ quote, waitFor: "completed" });
163
+ ```
164
+
165
+ The report includes `multi_addr`. Its `tx_type` remains `same-chain` or `cross-chain`, matching the unified Swap API.
166
+
167
+ ### Withdraw directly to NEAR
168
+
169
+ Register a NEAR executor and request the NEAR path. The SDK parses `nearMcaWithdrawTx`, builds the MCA `exec` function call, and asks the injected NEAR wallet to send it. This path does not create an additional off-chain MCA message signature.
170
+
171
+ ```ts
172
+ const quote = await client.quote({
173
+ flow: "withdraw",
174
+ mcaAccountId: "account.near",
175
+ fromChain: "near",
176
+ toChain: "near",
177
+ tokenIn: mcaUsdc,
178
+ tokenOut: nearUsdc,
179
+ amountIn: "1000000",
180
+ slippageBps: 50,
181
+ sender: "account.near",
182
+ recipient: "alice.near",
183
+ signerChain: "near",
184
+ collateral: {
185
+ needDecrease: false,
186
+ decreaseAmountBurrow: "0",
188
187
  },
189
- NEAR: {
190
- address: "wrap.near",
191
- symbol: "wNEAR",
192
- decimals: 24,
193
- assetId: "nep141:wrap.near",
188
+ executionPreference: "near",
189
+ boundNearAccountId: "alice.near",
190
+ });
191
+
192
+ await client.swap({ quote, waitFor: "completed" });
193
+ ```
194
+
195
+ With `executionPreference: "auto"`, NEAR direct execution is selected only when the destination chain is NEAR and `recipient` exactly matches `boundNearAccountId`.
196
+
197
+ ### Withdraw through the multichain relayer
198
+
199
+ For other destination chains, expose `getIdentityKey()` and `signMessage()` on the connected wallet adapter used by its registered executor. The SDK signs the exact `messageToSign` returned by the API, then submits `mcaRelayer` through `POST /api/swap/swap`. No source-chain executor broadcasts a transaction for this path.
200
+
201
+ ```ts
202
+ const quote = await client.quote({
203
+ flow: "withdraw",
204
+ mcaAccountId: "account.near",
205
+ fromChain: "near",
206
+ toChain: "1",
207
+ tokenIn: mcaUsdc,
208
+ tokenOut: ethereumUsdc,
209
+ amountIn: "1000000",
210
+ slippageBps: 50,
211
+ sender: "account.near",
212
+ recipient: wallet.address,
213
+ signerChain: "evm",
214
+ collateral: {
215
+ needDecrease: true,
216
+ decreaseAmountBurrow: "1000000",
217
+ withdrawAll: true,
194
218
  },
195
- };
219
+ executionPreference: "relayer",
220
+ });
196
221
 
197
- const completeQuoteResult = await completeQuote(
198
- {
199
- sourceToken: tokenIn,
200
- targetToken: tokenOut,
201
- sourceChain: "near",
202
- targetChain: "bsc",
203
- amountIn: "1000000000000000000",
204
- slippage: 50,
205
- recipient: "0x...", // Target chain address
206
- refundTo: "user.near",
222
+ await client.swap({
223
+ quote,
224
+ waitFor: "completed",
225
+ beforeSign(preview) {
226
+ showMcaSignatureConfirmation(preview);
207
227
  },
208
- {
209
- intentsQuotationAdapter,
210
- dexRouter: router,
211
- bluechipTokens,
212
- configAdapter,
213
- }
214
- );
215
-
216
- console.log("Deposit address:", completeQuoteResult.intents.depositAddress);
217
- console.log("Final amount out:", completeQuoteResult.finalAmountOut);
218
-
219
- if (completeQuoteResult.preSwap) {
220
- console.log("Pre-swap required:", completeQuoteResult.preSwap.quote);
221
- }
228
+ });
222
229
  ```
223
230
 
224
- ## API Documentation
231
+ Supported MCA signer identity formats are EVM, Solana, Bitcoin, NEAR, Aptos, Sui, Zcash, and Tron. Wallet implementations remain application-owned:
225
232
 
226
- ### NearSmartRouter
233
+ ```ts
234
+ import {
235
+ formatMcaWallet,
236
+ selectMcaSigner,
237
+ } from "@rhea-finance/cross-chain-aggregation-dex";
227
238
 
228
- #### `quote(params: QuoteParams): Promise<QuoteResult>`
239
+ formatMcaWallet("evm", "0xAbC"); // { EVM: "AbC" }
229
240
 
230
- Get quote method that returns optimal swap path and output amount.
241
+ const signer = selectMcaSigner(boundMcaWallets, connectedSignerIdentities);
242
+ ```
231
243
 
232
- **Parameters:**
233
- - `tokenIn`: Input token information
234
- - `tokenOut`: Output token information
235
- - `amountIn`: Input amount (string format, considering decimals)
236
- - `slippage`: Slippage tolerance (prefer bps, 50 = 0.5%). Percent/decimal inputs are also accepted.
237
- - `swapType`: Swap type ("EXACT_INPUT" | "EXACT_OUTPUT")
244
+ The executor registered for the selected chain must expose `signMessage` when the relayer preview requests a message signature. The SDK never receives a private key or recovery phrase.
238
245
 
239
- **Returns:**
240
- - `success`: Whether successful
241
- - `amountOut`: Output amount
242
- - `minAmountOut`: Minimum output amount (considering slippage)
243
- - `routes`: Route information
244
- - `error`: Error message (if failed)
246
+ ### Collateral policy
245
247
 
246
- #### `executeSwap(params: ExecuteParams): Promise<ExecuteResult>`
248
+ The SDK does not fetch a lending portfolio. Pass collateral decisions explicitly, or calculate the API fields from data already held by the application:
247
249
 
248
- Execute swap method.
250
+ ```ts
251
+ import { resolveMcaWithdrawPolicy } from "@rhea-finance/cross-chain-aggregation-dex";
249
252
 
250
- **Parameters:**
251
- - `quote`: Quote result
252
- - `recipient`: Recipient address
253
- - `depositAddress`: Deposit address (optional, for cross-chain scenarios)
253
+ const collateral = resolveMcaWithdrawPolicy({
254
+ collateralBalance: "12.5",
255
+ availableBalance: "1000000",
256
+ amountIn: "999999",
257
+ isMax: false,
258
+ });
259
+ ```
260
+
261
+ `withdrawAll` becomes true for max selection, exact available balance, or a ratio of at least `0.999999`. The calculation uses decimal strings and `BigInt`, not floating-point arithmetic.
254
262
 
255
- **Returns:**
256
- - `success`: Whether successful
257
- - `txHash`: Transaction hash
258
- - `txHashArray`: Transaction hash array (if multiple transactions)
259
- - `error`: Error message (if failed)
263
+ MCA history uses the MCA account id as the server-side history search key. The backend matches this value against `sender`, `recipient`, and `multi_addr`:
260
264
 
261
- ### completeQuote
265
+ ```ts
266
+ const history = await client.getHistory({
267
+ sender: "account.near",
268
+ });
269
+ ```
262
270
 
263
- Complete quote function that integrates DEX Aggregator and NearIntents.
271
+ The SDK preserves the server page instead of filtering `record.multi_addr` again. Address fields may be presentation-normalized by the API, so callers should not require exact equality with the MCA account id.
264
272
 
265
- **Parameters:**
266
- - `sourceToken`: Source token
267
- - `targetToken`: Target token
268
- - `sourceChain`: Source chain
269
- - `targetChain`: Target chain
270
- - `amountIn`: Input amount
271
- - `slippage`: Slippage tolerance
272
- - `recipient`: Recipient address
273
- - `refundTo`: Refund address (optional)
273
+ ## API surfaces
274
274
 
275
- **Configuration:**
276
- - `intentsQuotationAdapter`: NearIntents quotation adapter
277
- - `dexRouter`: DEX Router instance
278
- - `bluechipTokens`: Bluechip tokens configuration
279
- - `configAdapter`: Configuration adapter
275
+ Normalized methods:
280
276
 
281
- ## Utility Functions
277
+ - `quote()`
278
+ - `buildSwap()`
279
+ - `executeSwap()` and `swap()`
280
+ - `getOrderStatus()` and `waitForOrder()`
281
+ - `report()` and `retryReport()`
282
+ - `getHistory()`
282
283
 
283
- ### `normalizeTokenId(tokenId: string, wrapNearContractId?: string): string`
284
+ Raw methods preserve the unified API `data` shape:
284
285
 
285
- Normalize token ID, remove `nep141:` prefix, convert `near` to `wrap.near`.
286
+ - `quoteRaw()`
287
+ - `buildRaw()`
288
+ - `submitOrderRaw()`
289
+ - `getOrderStatusRaw()`
290
+ - `reportRaw()`
291
+ - `getHistoryRaw()`
286
292
 
287
- ### `convertSlippageToBasisPoints(slippage: number): number`
293
+ ## Execution kinds
288
294
 
289
- Convert slippage format to basis points (1 basis point = 0.01%).
295
+ Build responses are validated and represented as a discriminated union:
290
296
 
291
- ### `findBestBluechipToken(bluechipTokens: BluechipTokensConfig, wrapNearContractId?: string): TokenInfo`
297
+ - `evm-transaction`
298
+ - `evm-signature`
299
+ - `solana-transaction`
300
+ - `aptos-entry-function`
301
+ - `near-transaction-batch`
302
+ - `tron-transfer`
303
+ - `bitcoin-transfer`
304
+ - `zcash-transfer`
305
+ - `sui-transfer`
292
306
 
293
- Find the best bluechip token to use as intermediate token (priority order: USDT > USDC > wNEAR).
307
+ The SDK core defines the executor contract and registry. Wallet-specific implementations are injected by the application, so importing the package does not access browser wallet globals.
294
308
 
295
- ### Logging
309
+ ## Runtime and credentials
296
310
 
297
- The SDK uses a simple logger with log level control. You can control logging via the `LOG_LEVEL` environment variable:
311
+ - Browsers and Node.js 18+ use the global Fetch API.
312
+ - Node.js 16 requires a compatible `fetch` implementation through `new SwapClient({ fetch })`.
313
+ - Supply credentials with `apiKey` or `getAccessToken`; when both are present, `getAccessToken` takes precedence.
314
+ - The package contains no fixed API credential and never manages private keys or wallet recovery phrases.
315
+ - Use `AbortSignal` on network, build, execute, and polling calls when cancellation is required.
298
316
 
299
- - `LOG_LEVEL=debug` - Show all logs (default in development)
300
- - `LOG_LEVEL=info` - Show info, warn, and error logs
301
- - `LOG_LEVEL=warn` - Show only warnings and errors (default in production)
302
- - `LOG_LEVEL=error` - Show only errors
303
- - `LOG_LEVEL=silent` - Disable all logs
317
+ ## Retry and logging
304
318
 
305
- ```typescript
306
- import { logger } from "@rhea-finance/cross-chain-aggregation-dex";
319
+ Quote, history, and order-status requests retry network errors, timeouts, HTTP 429, and retryable 5xx responses twice by default. Build, report, order submission, and wallet execution are never retried automatically.
307
320
 
308
- // The logger is automatically used internally
309
- // You can also use it in your code if needed
310
- logger.debug("Debug message");
311
- logger.info("Info message");
312
- logger.warn("Warning message");
313
- logger.error("Error message");
321
+ ```ts
322
+ const client = new SwapClient({
323
+ baseUrl: "https://api.rhea.finance",
324
+ retry: {
325
+ maxRetries: 2,
326
+ baseDelayMs: 250,
327
+ maxDelayMs: 2_000,
328
+ jitter: true,
329
+ },
330
+ logger: {
331
+ log(entry) {
332
+ telemetry.emit(entry.event, entry);
333
+ },
334
+ },
335
+ });
314
336
  ```
315
337
 
316
- ## Type Definitions
338
+ Log entries contain only request stage, endpoint path, attempt, response status, timing, and SDK error code. They do not include credentials, query strings, request bodies, signatures, or serialized transactions.
317
339
 
318
- All type definitions can be imported from the package:
340
+ ## Amount conversion
319
341
 
320
- ```typescript
321
- import type {
322
- TokenInfo,
323
- QuoteParams,
324
- QuoteResult,
325
- ExecuteParams,
326
- ExecuteResult,
327
- DexRouter,
328
- BluechipTokensConfig,
329
- } from "@rhea-finance/cross-chain-aggregation-dex";
330
- ```
342
+ `parseUnits` and `formatUnits` use string arithmetic and never pass token values through floating-point numbers:
331
343
 
332
- ## Development
344
+ ```ts
345
+ import {
346
+ formatUnits,
347
+ parseUnits,
348
+ } from "@rhea-finance/cross-chain-aggregation-dex";
333
349
 
334
- ```bash
335
- # Install dependencies
336
- pnpm install
350
+ parseUnits("1.25", 6); // "1250000"
351
+ formatUnits("1250000", 6); // "1.25"
352
+ ```
337
353
 
338
- # Build
339
- pnpm build
354
+ Both functions reject negative values, scientific notation, malformed input, and unsupported precision. Token decimals must be an integer between 0 and 255.
340
355
 
341
- # Type check
342
- pnpm type-check
356
+ ## History filtering
343
357
 
344
- # Development mode (watch file changes)
345
- pnpm dev
346
- ```
358
+ The service handles sender and pagination. `getHistory({ status })` filters the current returned page locally and sets `filteredLocally: true`; server totals remain unchanged.
347
359
 
348
360
  ## License
349
361
 
350
362
  MIT
351
-
352
- ## Related Links
353
-
354
- - [GitHub Repository](https://github.com/rhea-finance/crossChain-aggregation-dex)
355
- - [Rhea Finance](https://rhea.finance)
@@ -0,0 +1,19 @@
1
+ import { C as ChainRef, q as ChainExecutor } from '../registry-DRYUqs7T.mjs';
2
+ import { E as ExecutorErrorAdapter, T as TransactionSubmission } from '../shared-BqpFeosz.mjs';
3
+
4
+ interface AptosWalletAdapter extends ExecutorErrorAdapter {
5
+ getChain(): ChainRef | Promise<ChainRef>;
6
+ signAndSubmitTransaction(payload: {
7
+ function: string;
8
+ typeArguments: string[];
9
+ functionArguments: unknown[];
10
+ }, options: {
11
+ signal?: AbortSignal;
12
+ }): Promise<TransactionSubmission>;
13
+ waitForTransaction?(txHash: string, options: {
14
+ signal?: AbortSignal;
15
+ }): Promise<unknown>;
16
+ }
17
+ declare function createAptosExecutor(adapter: AptosWalletAdapter): ChainExecutor<"aptos-entry-function">;
18
+
19
+ export { type AptosWalletAdapter, createAptosExecutor };
@@ -0,0 +1,19 @@
1
+ import { C as ChainRef, q as ChainExecutor } from '../registry-DRYUqs7T.js';
2
+ import { E as ExecutorErrorAdapter, T as TransactionSubmission } from '../shared-BdH3hWuP.js';
3
+
4
+ interface AptosWalletAdapter extends ExecutorErrorAdapter {
5
+ getChain(): ChainRef | Promise<ChainRef>;
6
+ signAndSubmitTransaction(payload: {
7
+ function: string;
8
+ typeArguments: string[];
9
+ functionArguments: unknown[];
10
+ }, options: {
11
+ signal?: AbortSignal;
12
+ }): Promise<TransactionSubmission>;
13
+ waitForTransaction?(txHash: string, options: {
14
+ signal?: AbortSignal;
15
+ }): Promise<unknown>;
16
+ }
17
+ declare function createAptosExecutor(adapter: AptosWalletAdapter): ChainExecutor<"aptos-entry-function">;
18
+
19
+ export { type AptosWalletAdapter, createAptosExecutor };