@swapdk/wdk-protocol-swidge-swapdk 1.0.0-alpha.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 (50) hide show
  1. package/README.md +140 -0
  2. package/dist/SwapDKSwidge.d.ts +94 -0
  3. package/dist/SwapDKSwidge.d.ts.map +1 -0
  4. package/dist/SwapDKSwidge.js +405 -0
  5. package/dist/SwapDKSwidge.js.map +1 -0
  6. package/dist/adapters/btc.d.ts +23 -0
  7. package/dist/adapters/btc.d.ts.map +1 -0
  8. package/dist/adapters/btc.js +159 -0
  9. package/dist/adapters/btc.js.map +1 -0
  10. package/dist/adapters/cosmos.d.ts +31 -0
  11. package/dist/adapters/cosmos.d.ts.map +1 -0
  12. package/dist/adapters/cosmos.js +103 -0
  13. package/dist/adapters/cosmos.js.map +1 -0
  14. package/dist/adapters/evm.d.ts +21 -0
  15. package/dist/adapters/evm.d.ts.map +1 -0
  16. package/dist/adapters/evm.js +72 -0
  17. package/dist/adapters/evm.js.map +1 -0
  18. package/dist/adapters/index.d.ts +18 -0
  19. package/dist/adapters/index.d.ts.map +1 -0
  20. package/dist/adapters/index.js +45 -0
  21. package/dist/adapters/index.js.map +1 -0
  22. package/dist/adapters/solana.d.ts +32 -0
  23. package/dist/adapters/solana.d.ts.map +1 -0
  24. package/dist/adapters/solana.js +96 -0
  25. package/dist/adapters/solana.js.map +1 -0
  26. package/dist/adapters/tron.d.ts +18 -0
  27. package/dist/adapters/tron.d.ts.map +1 -0
  28. package/dist/adapters/tron.js +119 -0
  29. package/dist/adapters/tron.js.map +1 -0
  30. package/dist/adapters/types.d.ts +69 -0
  31. package/dist/adapters/types.d.ts.map +1 -0
  32. package/dist/adapters/types.js +16 -0
  33. package/dist/adapters/types.js.map +1 -0
  34. package/dist/asset-encode.d.ts +34 -0
  35. package/dist/asset-encode.d.ts.map +1 -0
  36. package/dist/asset-encode.js +95 -0
  37. package/dist/asset-encode.js.map +1 -0
  38. package/dist/chain-map.d.ts +23 -0
  39. package/dist/chain-map.d.ts.map +1 -0
  40. package/dist/chain-map.js +85 -0
  41. package/dist/chain-map.js.map +1 -0
  42. package/dist/index.d.ts +8 -0
  43. package/dist/index.d.ts.map +1 -0
  44. package/dist/index.js +10 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/types.d.ts +163 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/dist/types.js +12 -0
  49. package/dist/types.js.map +1 -0
  50. package/package.json +64 -0
package/README.md ADDED
@@ -0,0 +1,140 @@
1
+ # @swapdk/wdk-protocol-swidge-swapdk
2
+
3
+ WDK swidge protocol module for arbitrary-asset cross-chain swaps and bridges via the [SwapDK swap-engine](https://swapdk.com) (routing through THORChain, MAYAChain, and Chainflip). Single class covering Bitcoin, EVM, Cosmos-family, Solana, and TRON source chains.
4
+
5
+ > **Version 1.0.0-alpha.0.** API surface is stable enough for early integration, but breaking changes are still possible before 1.0.0.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @swapdk/wdk-protocol-swidge-swapdk
11
+ ```
12
+
13
+ You also need the WDK wallet module for your source chain family:
14
+
15
+ | Source chain | Peer wallet |
16
+ |---|---|
17
+ | Ethereum / Arbitrum / Base / BSC / Avalanche | `@tetherto/wdk-wallet-evm` |
18
+ | Bitcoin | `@swapdk/wdk-wallet-btc` (until the upstream `memo` PR lands in `@tetherto/wdk-wallet-btc`) |
19
+ | TRON (TRX / TRC-20) | `@tetherto/wdk-wallet-tron` + `tronweb` |
20
+ | THORChain (RUNE) / MAYAChain (CACAO) | `@base58-io/wdk-wallet-cosmos` or the SwapDK fork with `deposit()` |
21
+ | Solana (native SOL) | `@tetherto/wdk-wallet-solana` |
22
+
23
+ The base `@tetherto/wdk-wallet` is a peer dep pinned to exact `1.0.0-beta.11` (matches the [Rhino.fi swidge module](https://www.npmjs.com/package/@rhino.fi/wdk-protocol-swidge-rhinofi) pin; upstream `beta.12+` regressed the `SwidgeProtocol` re-export from `/protocols/index.js`).
24
+
25
+ ## Quick start
26
+
27
+ ```ts
28
+ import WalletManagerEvm from "@tetherto/wdk-wallet-evm";
29
+ import { SwapDKSwidge } from "@swapdk/wdk-protocol-swidge-swapdk";
30
+
31
+ const wallet = new WalletManagerEvm(seedPhrase, { provider: process.env.RPC_URL_ETHEREUM });
32
+ const account = await wallet.getAccount(0);
33
+
34
+ const swidge = new SwapDKSwidge(account, {
35
+ apiUrl: "https://api.swapdk.com",
36
+ apiKey: process.env.SWAPDK_API_KEY!,
37
+ defaultFromChain: "ethereum",
38
+ });
39
+
40
+ // 1. Discovery — no wallet needed
41
+ const chains = await swidge.getSupportedChains();
42
+ const tokens = await swidge.getSupportedTokens({ fromChain: "ethereum" });
43
+
44
+ // 2. Non-binding quote
45
+ const quote = await swidge.quoteSwidge({
46
+ fromToken: "ETH",
47
+ fromChain: "ethereum",
48
+ toToken: "BTC",
49
+ toChain: "bitcoin",
50
+ fromTokenAmount: 10_000_000_000_000_000n, // 0.01 ETH
51
+ recipient: "bc1qexampleRecipient…",
52
+ slippage: 0.01,
53
+ });
54
+ console.log("expected BTC out:", quote.toTokenAmount);
55
+
56
+ // 3. Execute (broadcasts the source-chain transaction)
57
+ const result = await swidge.swidge({
58
+ fromToken: "ETH",
59
+ fromChain: "ethereum",
60
+ toToken: "BTC",
61
+ toChain: "bitcoin",
62
+ fromTokenAmount: 10_000_000_000_000_000n,
63
+ recipient: "bc1qexampleRecipient…",
64
+ });
65
+ console.log("source tx:", result.hash);
66
+
67
+ // 4. Poll the destination leg
68
+ const status = await swidge.getSwidgeStatus(result.id, { fromChain: "ethereum" });
69
+ if (status.status === "completed") { /* … */ }
70
+ ```
71
+
72
+ ## API
73
+
74
+ Implements the [`ISwidgeProtocol`](https://docs.wdk.tether.io/sdk/swidge-modules/) interface from `@tetherto/wdk-wallet/protocols`:
75
+
76
+ | Method | Purpose |
77
+ |---|---|
78
+ | `getSupportedChains()` | Live list of routable source + destination chains (halt-filtered server-side). |
79
+ | `getSupportedTokens(options?)` | Discoverable tokens with optional `fromChain` / `toChain` filter. |
80
+ | `quoteSwidge(options)` | Non-binding quote. Reads only; safe without a wallet. |
81
+ | `swidge(options, config?)` | Execute — signs and broadcasts the source-chain deposit. |
82
+ | `getSwidgeStatus(id, options?)` | Look up the swidge status for a broadcast source-tx hash. |
83
+
84
+ Because the base `SwidgeProtocol` implements `bridge/quoteBridge/swap/quoteSwap` by delegating to `swidge/quoteSwidge`, downstream consumers still on the legacy `IBridgeProtocol` / `ISwapProtocol` API get compatibility for free.
85
+
86
+ ## Options
87
+
88
+ ### `SwapDKSwidgeConfig`
89
+
90
+ | Field | Type | Notes |
91
+ |---|---|---|
92
+ | `apiUrl` | `string` | SwapDK swap-engine base URL. Required. |
93
+ | `apiKey` | `string` | SwapDK API key. Sent as `x-api-key`. Required. |
94
+ | `defaultFromChain` | `string` | Falls back for options that omit `fromChain`. |
95
+ | `defaultSlippage` | `number` | Decimal (0.03 = 3%). Default: 0.03. |
96
+ | `timeoutMs` | `number` | HTTP timeout. Default: 10 000. |
97
+ | `retries` | `number` | Retry count on network errors / 5xx (for idempotent endpoints). Default: 2. |
98
+ | `feeRate` | `number \| bigint` | Bitcoin miner-fee (sats/vB). BTC adapter only; ignored elsewhere. |
99
+ | `chainflip` | `object` | Chainflip broker-channel defaults (`refundMinPrice`, `refundRetryDuration`, `dcaChunks`, `dcaChunkInterval`, `maxBoostFeeBps`). BTC adapter only. |
100
+ | `tronWeb` | `TronWebLike` | TronWeb instance. Required for TRON sources; ignored elsewhere. |
101
+
102
+ ### `SwapDKSwidgeOptions`
103
+
104
+ Extends the base `SwidgeOptions` with `fromChain` (required for multi-family source support). Fields:
105
+
106
+ - `fromToken`, `toToken` — provider-specific identifiers (native ticker for gas coins, contract address for fungibles — matches `getSupportedTokens()` output).
107
+ - `fromChain`, `toChain` — swidge chain ids (`"ethereum"`, `"bitcoin"`, `"tron"`, etc.).
108
+ - `recipient`, `refundAddress` — destination + refund addresses.
109
+ - `slippage` — decimal, mutually exclusive with `minAmountOut`.
110
+ - `fromTokenAmount` — exact-in amount in base units. Mutually exclusive with `toTokenAmount`.
111
+ - `toTokenAmount` — exact-out. **Not yet supported by the swap-engine**; adapter throws `SwapDKUserError` if passed.
112
+
113
+ ## Known limits (v1.0.0-alpha)
114
+
115
+ - **`SwidgeProtocolConfig.maxNetworkFeeBps` / `maxProtocolFeeBps` are accepted but currently no-op.** The module returns fee data on `SwidgeResult.fees` so callers can enforce caps client-side. Server-side enforcement lands in a subsequent release.
116
+ - **`minAmountOut` is accepted but not forwarded to `/quote`.** Use `slippage` to control slippage tolerance until this ships.
117
+ - **Solana source: native SOL only.** SPL tokens require a separate SPL-Token instruction path (roadmap).
118
+ - **`getSupportedTokens.fromToken` filter is accepted but not applied server-side** — the backend returns the full token list scoped to `fromChain`.
119
+
120
+ ## Chain-family adapters
121
+
122
+ The `swidge()` execution path dispatches to a per-source-chain adapter internally. Each adapter is a small module that translates the swap-engine response into the concrete tx shape the paired wallet expects:
123
+
124
+ | Source | Adapter | Provider paths |
125
+ |---|---|---|
126
+ | EVM | `evmAdapter` | Router-contract call (+ optional ERC-20 approve leg) via `wallet.sendTransaction({to, data, value, gas})` |
127
+ | Bitcoin | `btcAdapter` | THORChain: `sendTransaction({to: vault, value, memo})` (memo → OP_RETURN). Chainflip: broker-channel + plain BTC transfer to allocated address. |
128
+ | TRON | `tronAdapter` | Router: `tronWeb.transactionBuilder.triggerSmartContract(...)` → prebuilt tx → `wallet.sendTransaction(prebuiltTx)`. Direct-vault: `sendTrx + addUpdateData` (memo in `raw_data.data`). |
129
+ | Cosmos | `cosmosAdapter` | THORChain / MAYAChain protocol-native: `wallet.deposit({asset, amount, memo})`. Cross-protocol: `wallet.transfer({token, recipient, amount, memo})`. |
130
+ | Solana | `solanaAdapter` | Native-SOL transfer + Memo Program instruction; single `wallet.sendTransaction(transactionMessage)`. |
131
+
132
+ ## Source
133
+
134
+ - Monorepo: https://github.com/Swap-DK/wdk-protocol-bridges-swapdk
135
+ - Package: `packages/swidge/`
136
+ - Adjacent legacy per-source-chain packages (still supported for existing consumers): `packages/{btc,cosmos,evm,solana,tron}/`
137
+
138
+ ## License
139
+
140
+ MIT
@@ -0,0 +1,94 @@
1
+ import type { SwidgeChainsResponse, SwidgeTokensQuery, SwidgeTokensResponse } from "@swapdk/swap-engine-client";
2
+ import { SwidgeProtocol } from "@tetherto/wdk-wallet/protocols";
3
+ import type { SwapDKSwidgeConfig, SwapDKSwidgeOptions, SwidgeWalletAccount } from "./types.js";
4
+ /** Swidge status vocabulary from the base protocol. */
5
+ export type SwidgeStatus = "pending" | "action-required" | "completed" | "failed" | "refund-pending" | "refunded" | "cancelled" | "expired" | "partial";
6
+ export type SwidgeFeeType = "network" | "protocol" | "affiliate" | "other";
7
+ export interface SwidgeFee {
8
+ type: SwidgeFeeType;
9
+ amount: bigint;
10
+ token: string;
11
+ chain?: string | number;
12
+ included?: boolean;
13
+ description?: string;
14
+ }
15
+ export interface SwidgeTransaction {
16
+ hash: string;
17
+ chain?: string | number;
18
+ type?: "source" | "destination" | "approval" | "refund" | "other";
19
+ }
20
+ export interface SwidgeQuote {
21
+ fromTokenAmount: bigint;
22
+ toTokenAmount: bigint;
23
+ toTokenAmountMin: bigint;
24
+ fees: SwidgeFee[];
25
+ estimatedDuration?: number;
26
+ expiry?: number;
27
+ priceImpact?: number;
28
+ }
29
+ export interface SwidgeResult {
30
+ id: string;
31
+ hash?: string;
32
+ fees: SwidgeFee[];
33
+ transactions?: SwidgeTransaction[];
34
+ fromTokenAmount: bigint;
35
+ toTokenAmount: bigint;
36
+ toTokenAmountMin?: bigint;
37
+ }
38
+ export interface SwidgeStatusOptions {
39
+ fromChain?: string | number;
40
+ toChain?: string | number;
41
+ }
42
+ export interface SwidgeStatusResult {
43
+ status: SwidgeStatus;
44
+ transactions?: SwidgeTransaction[];
45
+ }
46
+ /**
47
+ * SwapDK's swidge protocol module.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * import { SwapDKSwidge } from "@swapdk/wdk-protocol-swidge-swapdk";
52
+ *
53
+ * const swidge = new SwapDKSwidge(walletAccount, {
54
+ * apiUrl: "https://api.swapdk.com",
55
+ * apiKey: process.env.SWAPDK_API_KEY!,
56
+ * defaultFromChain: "ethereum",
57
+ * });
58
+ *
59
+ * const chains = await swidge.getSupportedChains();
60
+ * const tokens = await swidge.getSupportedTokens({ fromChain: "ethereum" });
61
+ *
62
+ * const quote = await swidge.quoteSwidge({
63
+ * fromToken: "ETH",
64
+ * fromChain: "ethereum",
65
+ * toToken: "BTC",
66
+ * toChain: "bitcoin",
67
+ * fromTokenAmount: 10_000_000_000_000_000n,
68
+ * recipient: "bc1q…",
69
+ * });
70
+ * ```
71
+ */
72
+ export declare class SwapDKSwidge extends SwidgeProtocol {
73
+ private readonly client;
74
+ protected readonly swidgeConfig: SwapDKSwidgeConfig;
75
+ constructor(account: SwidgeWalletAccount | undefined, config: SwapDKSwidgeConfig);
76
+ /**
77
+ * Convenience accessor for subclasses / tests. Bound to the same
78
+ * object the base class stores as `this._account`.
79
+ */
80
+ protected get account(): SwidgeWalletAccount | undefined;
81
+ getSupportedChains(): Promise<SwidgeChainsResponse>;
82
+ getSupportedTokens(options?: SwidgeTokensQuery): Promise<SwidgeTokensResponse>;
83
+ quoteSwidge(options: SwapDKSwidgeOptions): Promise<SwidgeQuote>;
84
+ swidge(options: SwapDKSwidgeOptions): Promise<SwidgeResult>;
85
+ private assertFeeCaps;
86
+ getSwidgeStatus(id: string, options?: SwidgeStatusOptions): Promise<SwidgeStatusResult>;
87
+ private prepareRoute;
88
+ private resolveSlippagePct;
89
+ private decimalsForToken;
90
+ private mapRouteToQuote;
91
+ private decimalsForFeeAsset;
92
+ private mapTrackToStatus;
93
+ }
94
+ //# sourceMappingURL=SwapDKSwidge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SwapDKSwidge.d.ts","sourceRoot":"","sources":["../src/SwapDKSwidge.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK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AC,eAAe;IAoCvB,OAAO,CAAC,mBAAmB;IAkB3B,OAAO,CAAC,gBAAgB;CAUzB"}
@@ -0,0 +1,405 @@
1
+ // ---------------------------------------------------------------------------
2
+ // SwapDKSwidge — WDK swidge protocol module for SwapDK.
3
+ //
4
+ // One class covering every source-chain family the SwapDK swap-engine can
5
+ // route (Bitcoin, EVM, Cosmos, Solana, TRON). Discovery, quoting, and
6
+ // tracking are shared implementations that delegate to the swap-engine's
7
+ // `/chains`, `/tokens?shape=swidge`, `/quote`, and `/track` endpoints;
8
+ // execution (`swidge()`) dispatches to a per-source-chain adapter that
9
+ // knows how to build the outbound tx for the given wallet-account shape.
10
+ //
11
+ // Because SwidgeProtocol's base class already implements `bridge()`,
12
+ // `quoteBridge()`, `swap()`, and `quoteSwap()` by delegating to
13
+ // `swidge()` / `quoteSwidge()`, downstream consumers of the legacy
14
+ // BridgeProtocol / SwapProtocol interfaces get compatibility for free.
15
+ // ---------------------------------------------------------------------------
16
+ import { SwapDKClient, SwapDKApiError, SwapDKUserError, pickBestRoute, } from "@swapdk/swap-engine-client";
17
+ import { SwidgeProtocol } from "@tetherto/wdk-wallet/protocols";
18
+ import { adapterFor } from "./adapters/index.js";
19
+ import { encodeSwapKitAsset, fromHumanAmount, toHumanAmount, } from "./asset-encode.js";
20
+ import { chainFamilyFor, nativeMetaFor } from "./chain-map.js";
21
+ // ---------------------------------------------------------------------------
22
+ /**
23
+ * SwapDK's swidge protocol module.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * import { SwapDKSwidge } from "@swapdk/wdk-protocol-swidge-swapdk";
28
+ *
29
+ * const swidge = new SwapDKSwidge(walletAccount, {
30
+ * apiUrl: "https://api.swapdk.com",
31
+ * apiKey: process.env.SWAPDK_API_KEY!,
32
+ * defaultFromChain: "ethereum",
33
+ * });
34
+ *
35
+ * const chains = await swidge.getSupportedChains();
36
+ * const tokens = await swidge.getSupportedTokens({ fromChain: "ethereum" });
37
+ *
38
+ * const quote = await swidge.quoteSwidge({
39
+ * fromToken: "ETH",
40
+ * fromChain: "ethereum",
41
+ * toToken: "BTC",
42
+ * toChain: "bitcoin",
43
+ * fromTokenAmount: 10_000_000_000_000_000n,
44
+ * recipient: "bc1q…",
45
+ * });
46
+ * ```
47
+ */
48
+ export class SwapDKSwidge extends SwidgeProtocol {
49
+ client;
50
+ swidgeConfig;
51
+ constructor(account, config) {
52
+ // Base class stores `account` on `this._account` and `config` on `this._config`.
53
+ // Cast around the JSDoc-typed base signature (types shipped by @tetherto/wdk-wallet
54
+ // widen the account parameter more than TypeScript would accept from a
55
+ // structurally-typed SwidgeWalletAccount).
56
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
57
+ super(account, config);
58
+ this.swidgeConfig = config;
59
+ this.client = new SwapDKClient(config.apiUrl, config.apiKey, {
60
+ timeoutMs: config.timeoutMs,
61
+ retries: config.retries,
62
+ });
63
+ }
64
+ /**
65
+ * Convenience accessor for subclasses / tests. Bound to the same
66
+ * object the base class stores as `this._account`.
67
+ */
68
+ get account() {
69
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
70
+ return this._account;
71
+ }
72
+ // -------------------------------------------------------------------
73
+ // Discovery
74
+ // -------------------------------------------------------------------
75
+ async getSupportedChains() {
76
+ return this.client.getSwidgeChains();
77
+ }
78
+ async getSupportedTokens(options) {
79
+ return this.client.getSwidgeTokens(options ?? {});
80
+ }
81
+ // -------------------------------------------------------------------
82
+ // Quote
83
+ // -------------------------------------------------------------------
84
+ async quoteSwidge(options) {
85
+ const { fromChain, toChain, sourceAsset, destinationAsset, fromAmount } = this.prepareRoute(options);
86
+ const quoteRes = await this.client.quote({
87
+ sellAsset: sourceAsset,
88
+ buyAsset: destinationAsset,
89
+ sellAmount: fromAmount,
90
+ slippage: this.resolveSlippagePct(options),
91
+ sourceAddress: options.refundAddress,
92
+ destinationAddress: options.recipient,
93
+ includeTx: false,
94
+ });
95
+ const route = pickBestRoute(quoteRes.routes);
96
+ if (!route) {
97
+ const providerErrs = quoteRes.providerErrors ?? [];
98
+ const summary = providerErrs.length > 0
99
+ ? providerErrs.map((e) => `${e.provider}: ${e.errorCode}`).join(", ")
100
+ : "no route";
101
+ throw new SwapDKUserError(`SwapDKSwidge: swap-engine returned no route for ${fromChain} → ${toChain} (${summary})`);
102
+ }
103
+ return this.mapRouteToQuote(route, options, fromChain);
104
+ }
105
+ // -------------------------------------------------------------------
106
+ // Execute — dispatch to per-source-chain adapter.
107
+ // -------------------------------------------------------------------
108
+ async swidge(options) {
109
+ const account = this.account;
110
+ if (!account) {
111
+ throw new SwapDKUserError("SwapDKSwidge.swidge(): requires a writable wallet account. " +
112
+ "Construct with `new SwapDKSwidge(account, config)` rather than `undefined`.");
113
+ }
114
+ const { fromChain, toChain, sourceAsset, destinationAsset, fromAmount } = this.prepareRoute(options);
115
+ // Resolve the adapter early — an unsupported source chain surfaces
116
+ // its "install X" error before any network round-trip is spent.
117
+ const adapter = adapterFor(fromChain);
118
+ const sourceAddress = await account.getAddress();
119
+ // 1. Quote (with calldata) — retry once on stale-route.
120
+ let route = pickBestRoute((await this.client.quote({
121
+ sellAsset: sourceAsset,
122
+ buyAsset: destinationAsset,
123
+ sellAmount: fromAmount,
124
+ slippage: this.resolveSlippagePct(options),
125
+ sourceAddress,
126
+ destinationAddress: options.recipient,
127
+ includeTx: true,
128
+ })).routes);
129
+ if (!route) {
130
+ throw new SwapDKUserError(`SwapDKSwidge: swap-engine returned no route for ${fromChain} → ${toChain}`);
131
+ }
132
+ // 2. /swap for finalized calldata — but only for adapters that need
133
+ // it. Bitcoin's THORChain path builds its tx from /quote data
134
+ // alone (inboundAddress + memo + sellAmount), so skipping the
135
+ // /swap round-trip saves latency AND avoids the swap-engine
136
+ // returning a no-op response for BTC routes.
137
+ const needsSwap = adapter.needsSwapResponse !== false;
138
+ let swapRes;
139
+ if (needsSwap) {
140
+ try {
141
+ swapRes = await this.client.swap({
142
+ routeId: route.routeId,
143
+ sourceAddress,
144
+ destinationAddress: options.recipient ?? sourceAddress,
145
+ });
146
+ }
147
+ catch (err) {
148
+ if (err instanceof SwapDKApiError && err.isStaleRoute) {
149
+ route = pickBestRoute((await this.client.quote({
150
+ sellAsset: sourceAsset,
151
+ buyAsset: destinationAsset,
152
+ sellAmount: fromAmount,
153
+ slippage: this.resolveSlippagePct(options),
154
+ sourceAddress,
155
+ destinationAddress: options.recipient,
156
+ includeTx: true,
157
+ })).routes);
158
+ if (!route) {
159
+ throw new SwapDKUserError(`SwapDKSwidge: re-quote returned no route for ${fromChain} → ${toChain}`);
160
+ }
161
+ swapRes = await this.client.swap({
162
+ routeId: route.routeId,
163
+ sourceAddress,
164
+ destinationAddress: options.recipient ?? sourceAddress,
165
+ });
166
+ }
167
+ else {
168
+ throw err;
169
+ }
170
+ }
171
+ }
172
+ // 3. Enforce per-call fee caps against the finalized route.
173
+ this.assertFeeCaps(swapRes, options);
174
+ // 4. Dispatch through the source-chain adapter.
175
+ const { hash, transactions } = await adapter.execute(account, {
176
+ route,
177
+ swapRes,
178
+ client: this.client,
179
+ options,
180
+ config: this.swidgeConfig,
181
+ fromChain,
182
+ sourceAddress,
183
+ });
184
+ // 5. Assemble SwidgeResult. Fees + amount fields come from swapRes
185
+ // when available, falling back to the /quote route for adapters
186
+ // that skipped /swap.
187
+ const fromDecimals = this.decimalsForToken(fromChain, options.fromToken);
188
+ const toDecimals = this.decimalsForToken(toChain, options.toToken);
189
+ const feesRaw = swapRes?.fees ?? route.fees ?? [];
190
+ const sellHuman = swapRes?.sellAmount ?? route.sellAmount;
191
+ const buyHuman = swapRes?.buyAmount ?? route.expectedBuyAmount;
192
+ return {
193
+ id: hash,
194
+ hash,
195
+ fees: feesRaw.map((fee) => ({
196
+ type: mapFeeType(fee.type),
197
+ amount: fromHumanAmount(fee.amount, this.decimalsForFeeAsset(fee.asset)),
198
+ token: fee.asset,
199
+ })),
200
+ transactions,
201
+ fromTokenAmount: fromHumanAmount(sellHuman, fromDecimals),
202
+ toTokenAmount: fromHumanAmount(buyHuman, toDecimals),
203
+ };
204
+ }
205
+ assertFeeCaps(
206
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
207
+ _swapRes, _options) {
208
+ // maxNetworkFeeBps / maxProtocolFeeBps on config are honoured here.
209
+ // The base `SwidgeProtocolConfig` documents them as caps against
210
+ // input-amount basis points; implementation lands with the first
211
+ // provider we run into where a real limit case surfaces.
212
+ // No-op for now — network + protocol fees are inspected downstream
213
+ // via the returned SwidgeResult.fees.
214
+ }
215
+ // -------------------------------------------------------------------
216
+ // Status
217
+ // -------------------------------------------------------------------
218
+ async getSwidgeStatus(id, options) {
219
+ if (!id || typeof id !== "string") {
220
+ throw new SwapDKUserError("SwapDKSwidge.getSwidgeStatus: id is required");
221
+ }
222
+ const fromChain = typeof options?.fromChain === "string"
223
+ ? options.fromChain
224
+ : options?.fromChain !== undefined
225
+ ? String(options.fromChain)
226
+ : this.swidgeConfig.defaultFromChain;
227
+ try {
228
+ const track = await this.client.track({
229
+ chainId: fromChain ?? "",
230
+ hash: id,
231
+ });
232
+ return this.mapTrackToStatus(track);
233
+ }
234
+ catch (err) {
235
+ if (err instanceof SwapDKApiError && err.isNotFound) {
236
+ return { status: "pending" };
237
+ }
238
+ throw err;
239
+ }
240
+ }
241
+ // -------------------------------------------------------------------
242
+ // Internals
243
+ // -------------------------------------------------------------------
244
+ prepareRoute(options) {
245
+ const fromChainRaw = options.fromChain ?? this.swidgeConfig.defaultFromChain ?? "";
246
+ const fromChain = normalizeChainId(fromChainRaw);
247
+ if (fromChain === "") {
248
+ throw new SwapDKUserError("SwapDKSwidge: options.fromChain is required (or set config.defaultFromChain on the instance)");
249
+ }
250
+ const toChain = normalizeChainId(options.toChain ?? fromChain);
251
+ const family = chainFamilyFor(fromChain);
252
+ if (family === "") {
253
+ throw new SwapDKUserError(`SwapDKSwidge: unknown source chain "${fromChain}" — see getSupportedChains()`);
254
+ }
255
+ if (options.fromTokenAmount === undefined && options.toTokenAmount === undefined) {
256
+ throw new SwapDKUserError("SwapDKSwidge: one of options.fromTokenAmount or options.toTokenAmount is required");
257
+ }
258
+ if (options.fromTokenAmount !== undefined && options.toTokenAmount !== undefined) {
259
+ throw new SwapDKUserError("SwapDKSwidge: options.fromTokenAmount and options.toTokenAmount are mutually exclusive");
260
+ }
261
+ // exact-out (`toTokenAmount`) is not yet supported by the swap-engine's
262
+ // /quote surface. Surface a clear error rather than silently rerouting.
263
+ if (options.toTokenAmount !== undefined) {
264
+ throw new SwapDKUserError("SwapDKSwidge: exact-out routes (toTokenAmount) are not yet supported by the SwapDK swap-engine — pass fromTokenAmount instead");
265
+ }
266
+ const sourceAsset = encodeSwapKitAsset(fromChain, options.fromToken);
267
+ const destinationAsset = encodeSwapKitAsset(toChain, options.toToken);
268
+ const sourceDecimals = this.decimalsForToken(fromChain, options.fromToken);
269
+ const fromAmount = toHumanAmount(typeof options.fromTokenAmount === "number"
270
+ ? BigInt(options.fromTokenAmount)
271
+ : options.fromTokenAmount ?? 0n, sourceDecimals);
272
+ return { fromChain, toChain, sourceAsset, destinationAsset, fromAmount };
273
+ }
274
+ resolveSlippagePct(options) {
275
+ // /quote takes slippage as a fraction of 1 (0.03 = 3%). Matches the
276
+ // swidge `slippage` field convention, so pass through when set.
277
+ if (typeof options.slippage === "number")
278
+ return options.slippage;
279
+ return this.swidgeConfig.defaultSlippage ?? 0.03;
280
+ }
281
+ decimalsForToken(swidgeChain, token) {
282
+ const native = nativeMetaFor(swidgeChain);
283
+ if (native && token.trim().toUpperCase() === native.symbol.toUpperCase()) {
284
+ return native.decimals;
285
+ }
286
+ // Fungibles default to 18 (EVM) / 6 (TRC-20, USDT/USDC across all chains,
287
+ // SPL USDC). We can't disambiguate without a token lookup — the
288
+ // swap-engine returns the actual base-unit amount on the /quote
289
+ // response, so the decimal only affects the wire encoding of the
290
+ // input amount. When a token doesn't have 18 decimals, callers
291
+ // should fetch the correct value from getSupportedTokens() and use
292
+ // toHumanAmount()/fromHumanAmount() directly rather than relying on
293
+ // this fallback.
294
+ const family = chainFamilyFor(swidgeChain);
295
+ if (family === "evm")
296
+ return 18;
297
+ return 6;
298
+ }
299
+ mapRouteToQuote(route, options, fromChain) {
300
+ const toChain = normalizeChainId(options.toChain ?? fromChain);
301
+ const fromDecimals = this.decimalsForToken(fromChain, options.fromToken);
302
+ const toDecimals = this.decimalsForToken(toChain, options.toToken);
303
+ const fromTokenAmount = fromHumanAmount(route.sellAmount, fromDecimals);
304
+ const toTokenAmount = fromHumanAmount(route.expectedBuyAmount, toDecimals);
305
+ const toTokenAmountMin = route.expectedBuyAmountMaxSlippage
306
+ ? fromHumanAmount(route.expectedBuyAmountMaxSlippage, toDecimals)
307
+ : toTokenAmount;
308
+ const fees = (route.fees ?? []).map((fee) => ({
309
+ type: mapFeeType(fee.type),
310
+ amount: fromHumanAmount(fee.amount, this.decimalsForFeeAsset(fee.asset)),
311
+ token: fee.asset,
312
+ }));
313
+ const estimatedDuration = typeof route.estimatedTime?.total === "number"
314
+ ? route.estimatedTime.total
315
+ : undefined;
316
+ return {
317
+ fromTokenAmount,
318
+ toTokenAmount,
319
+ toTokenAmountMin,
320
+ fees,
321
+ estimatedDuration,
322
+ };
323
+ }
324
+ decimalsForFeeAsset(asset) {
325
+ // Fees come back in SwapKit asset format (`"THOR.RUNE"`, `"ETH.ETH"`).
326
+ // Best effort: split off the chain prefix, look up native decimals.
327
+ const dot = asset.indexOf(".");
328
+ if (dot < 0)
329
+ return 8;
330
+ const chainCode = asset.slice(0, dot);
331
+ // Reverse the CHAIN_TABLE lookup.
332
+ const rows = [
333
+ { code: "BTC", d: 8 }, { code: "ETH", d: 18 }, { code: "ARB", d: 18 },
334
+ { code: "BASE", d: 18 }, { code: "BSC", d: 18 }, { code: "AVAX", d: 18 },
335
+ { code: "TRON", d: 6 }, { code: "SOL", d: 9 }, { code: "THOR", d: 8 },
336
+ { code: "MAYA", d: 10 }, { code: "GAIA", d: 6 }, { code: "DOGE", d: 8 },
337
+ { code: "BCH", d: 8 }, { code: "LTC", d: 8 },
338
+ ];
339
+ for (const r of rows)
340
+ if (r.code === chainCode.toUpperCase())
341
+ return r.d;
342
+ return 8;
343
+ }
344
+ mapTrackToStatus(track) {
345
+ return {
346
+ status: mapTrackStatus(track.status),
347
+ transactions: track.legs?.map((leg) => ({
348
+ hash: leg.hash,
349
+ chain: String(leg.chainId ?? ""),
350
+ type: legTypeFor(leg),
351
+ })),
352
+ };
353
+ }
354
+ }
355
+ // ---------------------------------------------------------------------------
356
+ // Fee / status / leg mappers.
357
+ // ---------------------------------------------------------------------------
358
+ function normalizeChainId(v) {
359
+ return typeof v === "number" ? String(v) : v.trim();
360
+ }
361
+ function mapFeeType(type) {
362
+ switch (type.toLowerCase()) {
363
+ case "liquidity":
364
+ case "protocol":
365
+ return "protocol";
366
+ case "outbound":
367
+ case "network":
368
+ case "affiliate_gas":
369
+ return "network";
370
+ case "affiliate":
371
+ return "affiliate";
372
+ default:
373
+ return "other";
374
+ }
375
+ }
376
+ function mapTrackStatus(status) {
377
+ switch (status) {
378
+ case "completed":
379
+ return "completed";
380
+ case "failed":
381
+ return "failed";
382
+ case "refunded":
383
+ return "refunded";
384
+ case "pending":
385
+ case "swapping":
386
+ case "not_started":
387
+ return "pending";
388
+ default:
389
+ return "pending";
390
+ }
391
+ }
392
+ function legTypeFor(leg) {
393
+ switch ((leg.type ?? "").toLowerCase()) {
394
+ case "swap":
395
+ return "source";
396
+ case "receive":
397
+ case "outbound":
398
+ return "destination";
399
+ case "refund":
400
+ return "refund";
401
+ default:
402
+ return "other";
403
+ }
404
+ }
405
+ //# sourceMappingURL=SwapDKSwidge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SwapDKSwidge.js","sourceRoot":"","sources":["../src/SwapDKSwidge.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,wDAAwD;AACxD,EAAE;AACF,0EAA0E;AAC1E,sEAAsE;AACtE,yEAAyE;AACzE,uEAAuE;AACvE,uEAAuE;AACvE,yEAAyE;AACzE,EAAE;AACF,qEAAqE;A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