@audren-xyz/sdk 1.3.0 → 1.3.2

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.
@@ -0,0 +1,1245 @@
1
+ import { AUDREN_PROGRAM_ID, CLASSIC_TOKEN_PROGRAM_ID, CU_LIMIT_EXEC_VIA_ESCROW_BASE, TOKEN_2022_PROGRAM_ID, } from './constants.js';
2
+ import { deriveEscrowPda } from './pda.js';
3
+ import { AUDREN_AUDITED_SWAP_ROUTERS } from './relayer.js';
4
+ import { JUPITER_CPI_EXCLUDED_DEXES, prepareEscrowAccounts, } from './swap.js';
5
+ export const SINGLE_HOP_ROUTER_CU_HEADROOM = 350_000;
6
+ export const MULTI_HOP_ROUTER_CU_HEADROOM = 550_000;
7
+ export const MAX_AGGREGATOR_TX_CU_LIMIT = 1_400_000;
8
+ const COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';
9
+ const ATA_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
10
+ const SYSTEM_PROGRAM = '11111111111111111111111111111111';
11
+ const WRAPPER_PROGRAMS = new Set([
12
+ COMPUTE_BUDGET_PROGRAM,
13
+ ATA_PROGRAM,
14
+ SYSTEM_PROGRAM,
15
+ CLASSIC_TOKEN_PROGRAM_ID,
16
+ TOKEN_2022_PROGRAM_ID,
17
+ ]);
18
+ export function computeAggregatorExecCuLimit(params) {
19
+ const reported = typeof params.reportedRouterCu === 'number' &&
20
+ Number.isFinite(params.reportedRouterCu) &&
21
+ params.reportedRouterCu > 0
22
+ ? Math.trunc(params.reportedRouterCu)
23
+ : null;
24
+ const hopCount = typeof params.routeHopCount === 'number' &&
25
+ Number.isFinite(params.routeHopCount) &&
26
+ params.routeHopCount > 0
27
+ ? Math.trunc(params.routeHopCount)
28
+ : null;
29
+ const isSingleHopDirect = !params.forceMultiHopHeadroom && hopCount === 1;
30
+ const useMultiHopFloor = params.forceMultiHopHeadroom === true ||
31
+ (hopCount !== null && hopCount > 1) ||
32
+ (!isSingleHopDirect && reported === null);
33
+ const minHeadroom = useMultiHopFloor ? MULTI_HOP_ROUTER_CU_HEADROOM : SINGLE_HOP_ROUTER_CU_HEADROOM;
34
+ const routerCu = Math.max(reported ?? minHeadroom, minHeadroom);
35
+ return Math.min(CU_LIMIT_EXEC_VIA_ESCROW_BASE + routerCu, MAX_AGGREGATOR_TX_CU_LIMIT);
36
+ }
37
+ function normalizeVenueName(raw) {
38
+ return raw.toLowerCase().replace(/[^a-z0-9]/g, '');
39
+ }
40
+ /**
41
+ * Returns the first PDA-CPI-hostile venue label present in `quote.routePlan`, or `null`
42
+ * if every leg is safe to execute through Audren's `ExecViaEscrow` (`Tag 6`) PDA CPI.
43
+ */
44
+ export function findExcludedCpiVenue(quote, excludedDexes = JUPITER_CPI_EXCLUDED_DEXES) {
45
+ const normalizedExcluded = excludedDexes
46
+ .map((name) => ({ name, norm: normalizeVenueName(name) }))
47
+ .filter((entry) => entry.norm.length > 0);
48
+ if (normalizedExcluded.length === 0)
49
+ return null;
50
+ for (const leg of quote.routePlan ?? []) {
51
+ const rawLabel = leg?.swapInfo?.label;
52
+ const label = typeof rawLabel === 'string' ? rawLabel.trim() : '';
53
+ if (!label)
54
+ continue;
55
+ const norm = normalizeVenueName(label);
56
+ if (!norm)
57
+ continue;
58
+ for (const ex of normalizedExcluded) {
59
+ if (norm === ex.norm || norm.includes(ex.norm)) {
60
+ return label;
61
+ }
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+ function validateAggregatorBaseUrl(raw, providerLabel) {
67
+ const trimmed = raw.trim().replace(/\/+$/, '');
68
+ let parsed;
69
+ try {
70
+ parsed = new URL(trimmed);
71
+ }
72
+ catch {
73
+ throw new Error(`${providerLabel} base URL is not a valid URL`);
74
+ }
75
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) {
76
+ throw new Error(`${providerLabel} base URL must not contain credentials, query, or hash`);
77
+ }
78
+ const isHttps = parsed.protocol === 'https:';
79
+ const isLoopbackHttp = parsed.protocol === 'http:' &&
80
+ (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1');
81
+ if (!isHttps && !isLoopbackHttp) {
82
+ throw new Error(`${providerLabel} base URL must use https:// (or http://localhost for local dev)`);
83
+ }
84
+ return trimmed;
85
+ }
86
+ function buildFetchSignal(signal, timeoutMs = 10_000) {
87
+ if (signal)
88
+ return signal;
89
+ if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function' && timeoutMs > 0) {
90
+ return AbortSignal.timeout(timeoutMs);
91
+ }
92
+ return undefined;
93
+ }
94
+ async function safeAggregatorFetch(fetchImpl, url, init, providerLabel) {
95
+ const res = await fetchImpl(url, {
96
+ ...init,
97
+ // Cloudflare Workers (`workerd`) throws on `redirect: 'error'`; use `'manual'` and reject 3xx explicitly
98
+ redirect: 'manual',
99
+ });
100
+ if (res.status >= 300 && res.status < 400) {
101
+ throw new Error(`${providerLabel} returned unexpected HTTP ${res.status} redirect`);
102
+ }
103
+ return res;
104
+ }
105
+ function bytesToBase64(bytes) {
106
+ let bin = '';
107
+ for (let i = 0; i < bytes.byteLength; i++) {
108
+ bin += String.fromCharCode(bytes[i]);
109
+ }
110
+ return btoa(bin);
111
+ }
112
+ function parsePositiveUintString(v) {
113
+ const s = String(v ?? '').trim();
114
+ if (!/^\d+$/.test(s))
115
+ return null;
116
+ const bi = BigInt(s);
117
+ return bi > 0n ? bi : null;
118
+ }
119
+ function validateQuoteParams(req) {
120
+ if (parsePositiveUintString(req.amount) === null) {
121
+ throw new RangeError('amount must be a positive base-10 integer string');
122
+ }
123
+ if (!Number.isInteger(req.slippageBps) || req.slippageBps < 0 || req.slippageBps >= 10_000) {
124
+ throw new RangeError('slippageBps must be an integer between 0 and 9999');
125
+ }
126
+ if (req.platformFeeBps !== undefined &&
127
+ (!Number.isInteger(req.platformFeeBps) || req.platformFeeBps < 0 || req.platformFeeBps > 1_000)) {
128
+ throw new RangeError('platformFeeBps must be an integer between 0 and 1000');
129
+ }
130
+ }
131
+ function isValidRouterInstruction(v) {
132
+ if (!v || typeof v !== 'object' || Array.isArray(v))
133
+ return false;
134
+ const ix = v;
135
+ if (typeof ix.programId !== 'string' ||
136
+ ix.programId.length === 0 ||
137
+ typeof ix.data !== 'string' ||
138
+ ix.data.length === 0 ||
139
+ !Array.isArray(ix.accounts)) {
140
+ return false;
141
+ }
142
+ return ix.accounts.every((a) => Boolean(a) &&
143
+ typeof a === 'object' &&
144
+ !Array.isArray(a) &&
145
+ typeof a.pubkey === 'string' &&
146
+ a.pubkey.length > 0 &&
147
+ typeof a.isSigner === 'boolean' &&
148
+ typeof a.isWritable === 'boolean');
149
+ }
150
+ export function createJupiterSwapAdapter(config = {}) {
151
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
152
+ const apiKey = config.apiKey?.trim() ?? '';
153
+ const rawUrl = config.apiUrl?.trim() ?? '';
154
+ const resolveBase = () => {
155
+ const base = validateAggregatorBaseUrl(rawUrl || 'https://api.jup.ag', 'Jupiter');
156
+ return base.endsWith('/swap/v1') ? base : `${base}/swap/v1`;
157
+ };
158
+ const makeHeaders = () => ({
159
+ accept: 'application/json',
160
+ 'content-type': 'application/json',
161
+ ...(apiKey ? { 'x-api-key': apiKey } : {}),
162
+ });
163
+ const fetchWithRetry = async (pathAndQuery, init) => {
164
+ const base = resolveBase();
165
+ const headers = makeHeaders();
166
+ const retryDelays = [300, 750];
167
+ let lastRes = null;
168
+ for (let attempt = 0; attempt <= retryDelays.length; attempt++) {
169
+ const res = await safeAggregatorFetch(fetchImpl, `${base}${pathAndQuery}`, {
170
+ method: init.method ?? 'GET',
171
+ headers,
172
+ body: init.body,
173
+ signal: buildFetchSignal(init.signal, init.timeoutMs ?? 10_000),
174
+ }, 'Jupiter');
175
+ if (res.ok || (res.status !== 429 && res.status < 500))
176
+ return res;
177
+ lastRes = res;
178
+ if (attempt < retryDelays.length) {
179
+ const retryAfter = Number(res.headers.get('retry-after') ?? '');
180
+ const delayMs = Number.isFinite(retryAfter) && retryAfter > 0
181
+ ? Math.min(Math.max(retryAfter * 1000, 250), 1_500)
182
+ : retryDelays[attempt];
183
+ await new Promise((r) => setTimeout(r, delayMs));
184
+ }
185
+ }
186
+ return lastRes;
187
+ };
188
+ return {
189
+ id: 'jupiter',
190
+ name: 'Jupiter Swap v1',
191
+ capabilities: {
192
+ supportsPlatformFeeBps: true,
193
+ supportsSwapInstructions: true,
194
+ quoteRequiresUserPubkey: false,
195
+ feeSide: 'output',
196
+ feeAccountStyle: 'ata',
197
+ },
198
+ isConfigured() {
199
+ return Boolean(apiKey || rawUrl);
200
+ },
201
+ async quote(req) {
202
+ validateQuoteParams(req);
203
+ if (!this.isConfigured()) {
204
+ throw new Error('Jupiter adapter not configured (set apiKey or apiUrl)');
205
+ }
206
+ const t0 = Date.now();
207
+ const excluded = req.excludeDexes ?? JUPITER_CPI_EXCLUDED_DEXES;
208
+ const doFetch = async (directOnly) => {
209
+ const qs = new URLSearchParams({
210
+ inputMint: req.inputMint,
211
+ outputMint: req.outputMint,
212
+ amount: req.amount,
213
+ slippageBps: String(req.slippageBps),
214
+ maxAccounts: String(req.maxAccounts ?? (directOnly ? 24 : 28)),
215
+ ...(excluded.length > 0 ? { excludeDexes: excluded.join(',') } : {}),
216
+ ...(directOnly ? { onlyDirectRoutes: 'true' } : {}),
217
+ ...(req.platformFeeBps && req.platformFeeBps > 0
218
+ ? { platformFeeBps: String(req.platformFeeBps) }
219
+ : {}),
220
+ });
221
+ const res = await fetchWithRetry(`/quote?${qs.toString()}`, {
222
+ signal: req.signal,
223
+ timeoutMs: req.timeoutMs,
224
+ });
225
+ if (!res.ok)
226
+ throw new Error(`Jupiter quote HTTP ${res.status}`);
227
+ return (await res.json());
228
+ };
229
+ let raw;
230
+ const wantDirect = req.onlyDirectRoutes ?? true;
231
+ try {
232
+ raw = await doFetch(wantDirect);
233
+ }
234
+ catch (err) {
235
+ if (wantDirect && req.onlyDirectRoutes === undefined) {
236
+ raw = await doFetch(false);
237
+ }
238
+ else {
239
+ throw err;
240
+ }
241
+ }
242
+ const outBi = parsePositiveUintString(raw.outAmount);
243
+ if (outBi === null)
244
+ throw new Error('Jupiter returned invalid or zero outAmount');
245
+ const routePlan = (Array.isArray(raw.routePlan) ? raw.routePlan : [])
246
+ .filter((item) => Boolean(item && typeof item === 'object'))
247
+ .map((item) => {
248
+ const si = item.swapInfo && typeof item.swapInfo === 'object' ? item.swapInfo : {};
249
+ const leg = {
250
+ label: typeof si.label === 'string' && si.label.trim() ? si.label.trim() : 'Jupiter',
251
+ ammKey: si.ammKey,
252
+ inputMint: si.inputMint ?? req.inputMint,
253
+ outputMint: si.outputMint ?? req.outputMint,
254
+ inAmount: si.inAmount ?? req.amount,
255
+ outAmount: si.outAmount ?? outBi.toString(),
256
+ percent: item.percent,
257
+ };
258
+ return { swapInfo: leg, percent: item.percent };
259
+ });
260
+ return {
261
+ provider: 'jupiter',
262
+ inputMint: raw.inputMint ?? req.inputMint,
263
+ outputMint: raw.outputMint ?? req.outputMint,
264
+ inAmount: raw.inAmount ?? req.amount,
265
+ outAmount: outBi.toString(),
266
+ otherAmountThreshold: raw.otherAmountThreshold ?? outBi.toString(),
267
+ slippageBps: raw.slippageBps ?? req.slippageBps,
268
+ priceImpactPct: raw.priceImpactPct ?? null,
269
+ platformFee: raw.platformFee?.amount
270
+ ? {
271
+ amount: raw.platformFee.amount,
272
+ feeBps: raw.platformFee.feeBps ?? req.platformFeeBps ?? 0,
273
+ mint: req.outputMint,
274
+ }
275
+ : null,
276
+ routePlan,
277
+ contextSlot: raw.contextSlot ?? null,
278
+ latencyMs: Date.now() - t0,
279
+ rawQuote: raw,
280
+ };
281
+ },
282
+ async swapInstructions(req) {
283
+ const body = {
284
+ quoteResponse: req.quoteResponse,
285
+ userPublicKey: req.escrowPubkey,
286
+ wrapAndUnwrapSol: false,
287
+ useSharedAccounts: false,
288
+ skipUserAccountsRpcCalls: true,
289
+ dynamicComputeUnitLimit: false,
290
+ };
291
+ if (req.feeAccountAta)
292
+ body.feeAccount = req.feeAccountAta;
293
+ const res = await fetchWithRetry('/swap-instructions', {
294
+ method: 'POST',
295
+ body: JSON.stringify(body),
296
+ signal: req.signal,
297
+ timeoutMs: req.timeoutMs,
298
+ });
299
+ if (!res.ok)
300
+ throw new Error(`Jupiter swap-instructions HTTP ${res.status}`);
301
+ const payload = (await res.json());
302
+ if (!isValidRouterInstruction(payload.swapInstruction)) {
303
+ throw new Error('Jupiter did not return a valid swapInstruction');
304
+ }
305
+ const rawRoutePlan = req.quoteResponse?.routePlan;
306
+ const routeHopCount = Array.isArray(rawRoutePlan) && rawRoutePlan.length > 0 ? rawRoutePlan.length : null;
307
+ return {
308
+ provider: 'jupiter',
309
+ swapInstruction: payload.swapInstruction,
310
+ addressLookupTableAddresses: Array.isArray(payload.addressLookupTableAddresses)
311
+ ? payload.addressLookupTableAddresses.filter((x) => typeof x === 'string')
312
+ : [],
313
+ computeUnitLimit: computeAggregatorExecCuLimit({
314
+ reportedRouterCu: payload.computeUnitLimit,
315
+ routeHopCount,
316
+ }),
317
+ feeAccount: req.feeAccountAta ?? null,
318
+ };
319
+ },
320
+ };
321
+ }
322
+ export function createDFlowSwapAdapter(config = {}) {
323
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
324
+ const apiKey = config.apiKey?.trim() ?? '';
325
+ const rawUrl = config.apiUrl?.trim() ?? '';
326
+ const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://quote-api.dflow.net', 'DFlow');
327
+ const makeHeaders = () => ({
328
+ accept: 'application/json',
329
+ 'content-type': 'application/json',
330
+ ...(apiKey ? { 'x-api-key': apiKey } : {}),
331
+ });
332
+ return {
333
+ id: 'dflow',
334
+ name: 'DFlow Trading API',
335
+ capabilities: {
336
+ supportsPlatformFeeBps: true,
337
+ supportsSwapInstructions: true,
338
+ quoteRequiresUserPubkey: false,
339
+ feeSide: 'output',
340
+ feeAccountStyle: 'ata',
341
+ },
342
+ isConfigured() {
343
+ return Boolean(apiKey || rawUrl);
344
+ },
345
+ async quote(req) {
346
+ validateQuoteParams(req);
347
+ if (!this.isConfigured()) {
348
+ throw new Error('DFlow adapter not configured (set apiKey or apiUrl)');
349
+ }
350
+ const base = resolveBase();
351
+ const t0 = Date.now();
352
+ const qs = new URLSearchParams({
353
+ inputMint: req.inputMint,
354
+ outputMint: req.outputMint,
355
+ amount: req.amount,
356
+ slippageBps: String(req.slippageBps),
357
+ transactionVersion: 'v1',
358
+ ...(req.onlyDirectRoutes ? { onlyDirectRoutes: 'true' } : {}),
359
+ ...(req.platformFeeBps && req.platformFeeBps > 0
360
+ ? { platformFeeBps: String(req.platformFeeBps) }
361
+ : {}),
362
+ });
363
+ const res = await safeAggregatorFetch(fetchImpl, `${base}/quote?${qs.toString()}`, {
364
+ headers: makeHeaders(),
365
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
366
+ }, 'DFlow');
367
+ if (!res.ok)
368
+ throw new Error(`DFlow quote HTTP ${res.status}`);
369
+ const raw = (await res.json());
370
+ const outBi = parsePositiveUintString(raw.outAmount);
371
+ if (outBi === null)
372
+ throw new Error('DFlow returned invalid or zero outAmount');
373
+ const legs = Array.isArray(raw.routePlan)
374
+ ? raw.routePlan.filter((l) => Boolean(l && typeof l === 'object'))
375
+ : [];
376
+ const flowByMint = new Map();
377
+ for (const leg of legs) {
378
+ const m = leg.inputMint ?? req.inputMint;
379
+ flowByMint.set(m, (flowByMint.get(m) ?? 0n) + (parsePositiveUintString(leg.inAmount) ?? 0n));
380
+ }
381
+ const routePlan = legs.map((leg) => {
382
+ const m = leg.inputMint ?? req.inputMint;
383
+ const total = flowByMint.get(m) ?? 0n;
384
+ const legIn = parsePositiveUintString(leg.inAmount) ?? 0n;
385
+ const pct = total > 0n ? Number((legIn * 10000n) / total) / 100 : 100;
386
+ const info = {
387
+ label: typeof leg.venue === 'string' && leg.venue.trim() ? leg.venue.trim() : 'DFlow',
388
+ ammKey: leg.marketKey,
389
+ inputMint: m,
390
+ outputMint: leg.outputMint ?? req.outputMint,
391
+ inAmount: String(leg.inAmount ?? req.amount),
392
+ outAmount: String(leg.outAmount ?? outBi.toString()),
393
+ percent: pct,
394
+ };
395
+ return { swapInfo: info, percent: pct };
396
+ });
397
+ return {
398
+ provider: 'dflow',
399
+ inputMint: raw.inputMint ?? req.inputMint,
400
+ outputMint: raw.outputMint ?? req.outputMint,
401
+ inAmount: String(raw.inAmount ?? req.amount),
402
+ outAmount: outBi.toString(),
403
+ otherAmountThreshold: String(raw.minOutAmount ?? raw.otherAmountThreshold ?? outBi.toString()),
404
+ slippageBps: raw.slippageBps ?? req.slippageBps,
405
+ priceImpactPct: raw.priceImpactPct ?? null,
406
+ platformFee: raw.platformFee?.amount
407
+ ? {
408
+ amount: String(raw.platformFee.amount),
409
+ feeBps: raw.platformFee.feeBps ?? req.platformFeeBps ?? 0,
410
+ mint: req.outputMint,
411
+ }
412
+ : null,
413
+ routePlan,
414
+ contextSlot: raw.contextSlot ?? null,
415
+ latencyMs: Date.now() - t0,
416
+ rawQuote: raw,
417
+ };
418
+ },
419
+ async swapInstructions(req) {
420
+ const base = resolveBase();
421
+ const res = await safeAggregatorFetch(fetchImpl, `${base}/swap-instructions`, {
422
+ method: 'POST',
423
+ headers: makeHeaders(),
424
+ body: JSON.stringify({
425
+ userPublicKey: req.escrowPubkey,
426
+ quoteResponse: req.quoteResponse,
427
+ wrapAndUnwrapSol: false,
428
+ transactionVersion: 'v1',
429
+ ...(req.feeAccountAta ? { feeAccount: req.feeAccountAta } : {}),
430
+ }),
431
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
432
+ }, 'DFlow');
433
+ if (!res.ok)
434
+ throw new Error(`DFlow swap-instructions HTTP ${res.status}`);
435
+ const payload = (await res.json());
436
+ if (!isValidRouterInstruction(payload.swapInstruction)) {
437
+ throw new Error('DFlow did not return a valid swapInstruction');
438
+ }
439
+ const rawRoutePlan = req.quoteResponse?.routePlan;
440
+ const routeHopCount = Array.isArray(rawRoutePlan) && rawRoutePlan.length > 0 ? rawRoutePlan.length : null;
441
+ return {
442
+ provider: 'dflow',
443
+ swapInstruction: payload.swapInstruction,
444
+ addressLookupTableAddresses: Array.isArray(payload.addressLookupTableAddresses)
445
+ ? payload.addressLookupTableAddresses.filter((x) => typeof x === 'string')
446
+ : [],
447
+ computeUnitLimit: computeAggregatorExecCuLimit({
448
+ reportedRouterCu: payload.computeUnitLimit,
449
+ routeHopCount,
450
+ }),
451
+ feeAccount: req.feeAccountAta ?? null,
452
+ };
453
+ },
454
+ };
455
+ }
456
+ // ---------------------------------------------------------------------------
457
+ // 3. OKX DEX Aggregator Adapter (Solana chainIndex=501, WebCrypto HMAC-SHA256)
458
+ // ---------------------------------------------------------------------------
459
+ const OKX_CHAIN_INDEX = '501';
460
+ const OKX_SWAP_IX_PATH = '/api/v6/dex/aggregator/swap-instruction';
461
+ export function createOkxSwapAdapter(config = {}) {
462
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
463
+ const apiKey = config.apiKey?.trim() ?? '';
464
+ const secretKey = config.secretKey?.trim() ?? '';
465
+ const passphrase = config.passphrase?.trim() ?? '';
466
+ const rawUrl = config.apiUrl?.trim() ?? '';
467
+ const encoder = new TextEncoder();
468
+ const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://web3.okx.com', 'OKX');
469
+ const signHeaders = async (method, requestPath, queryString) => {
470
+ const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, '.000Z');
471
+ const prehash = `${timestamp}${method.toUpperCase()}${requestPath}${queryString}`;
472
+ const key = await crypto.subtle.importKey('raw', encoder.encode(secretKey), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
473
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(prehash)));
474
+ return {
475
+ 'OK-ACCESS-KEY': apiKey,
476
+ 'OK-ACCESS-SIGN': bytesToBase64(sig),
477
+ 'OK-ACCESS-TIMESTAMP': timestamp,
478
+ 'OK-ACCESS-PASSPHRASE': passphrase,
479
+ accept: 'application/json',
480
+ };
481
+ };
482
+ return {
483
+ id: 'okx',
484
+ name: 'OKX DEX Aggregator',
485
+ capabilities: {
486
+ supportsPlatformFeeBps: true,
487
+ supportsSwapInstructions: true,
488
+ quoteRequiresUserPubkey: true,
489
+ feeSide: 'output',
490
+ feeAccountStyle: 'owner_wallet',
491
+ },
492
+ isConfigured() {
493
+ return Boolean(apiKey && secretKey && passphrase);
494
+ },
495
+ async quote(req) {
496
+ validateQuoteParams(req);
497
+ if (!this.isConfigured()) {
498
+ throw new Error('OKX adapter not configured (set apiKey, secretKey, and passphrase)');
499
+ }
500
+ if (!req.escrowPubkey) {
501
+ throw new Error('OKX requires escrowPubkey at quote time');
502
+ }
503
+ const base = resolveBase();
504
+ const t0 = Date.now();
505
+ const qs = new URLSearchParams({
506
+ chainIndex: OKX_CHAIN_INDEX,
507
+ amount: req.amount,
508
+ fromTokenAddress: req.inputMint,
509
+ toTokenAddress: req.outputMint,
510
+ slippagePercent: (req.slippageBps / 100).toString(),
511
+ userWalletAddress: req.escrowPubkey,
512
+ swapMode: 'exactIn',
513
+ ...(req.platformFeeBps && req.platformFeeBps > 0 && req.feeOwnerWallet
514
+ ? {
515
+ feePercent: (req.platformFeeBps / 100).toFixed(4).replace(/\.?0+$/, ''),
516
+ toTokenReferrerWalletAddress: req.feeOwnerWallet,
517
+ }
518
+ : {}),
519
+ });
520
+ const queryString = `?${qs.toString()}`;
521
+ const headers = await signHeaders('GET', OKX_SWAP_IX_PATH, queryString);
522
+ const res = await safeAggregatorFetch(fetchImpl, `${base}${OKX_SWAP_IX_PATH}${queryString}`, {
523
+ headers,
524
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
525
+ }, 'OKX');
526
+ if (!res.ok)
527
+ throw new Error(`OKX swap-instruction HTTP ${res.status}`);
528
+ const body = (await res.json());
529
+ const entry = Array.isArray(body.data) ? body.data[0] : body.data;
530
+ const outBi = parsePositiveUintString(entry?.routerResult?.toTokenAmount);
531
+ if (body.code !== '0' || !entry?.routerResult || outBi === null) {
532
+ throw new Error(`OKX API returned no valid route${body.msg ? `: ${body.msg}` : ''}`);
533
+ }
534
+ const rr = entry.routerResult;
535
+ const outAmount = outBi.toString();
536
+ const minOut = ((outBi * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
537
+ const routePlan = [];
538
+ const pushDexProtocols = (dexProtocol, fromMint, toMint) => {
539
+ const protos = Array.isArray(dexProtocol)
540
+ ? dexProtocol
541
+ : dexProtocol && typeof dexProtocol === 'object'
542
+ ? [dexProtocol]
543
+ : [];
544
+ for (const p of protos) {
545
+ if (!p || typeof p !== 'object')
546
+ continue;
547
+ const rec = p;
548
+ const label = typeof rec.dexName === 'string' && rec.dexName.trim() ? rec.dexName.trim() : 'OKX';
549
+ const pct = Number(rec.percent ?? 100);
550
+ routePlan.push({
551
+ swapInfo: {
552
+ label,
553
+ inputMint: fromMint,
554
+ outputMint: toMint,
555
+ inAmount: req.amount,
556
+ outAmount,
557
+ percent: Number.isFinite(pct) ? pct : 100,
558
+ },
559
+ percent: Number.isFinite(pct) ? pct : 100,
560
+ });
561
+ }
562
+ };
563
+ for (const h of Array.isArray(rr.dexRouterList) ? rr.dexRouterList : []) {
564
+ if (!h || typeof h !== 'object')
565
+ continue;
566
+ const subList = Array.isArray(h.subRouterList)
567
+ ? h.subRouterList
568
+ : null;
569
+ if (subList && subList.length > 0) {
570
+ for (const sub of subList) {
571
+ if (!sub || typeof sub !== 'object')
572
+ continue;
573
+ const fromMint = sub.fromToken?.tokenContractAddress ??
574
+ req.inputMint;
575
+ const toMint = sub.toToken?.tokenContractAddress ??
576
+ req.outputMint;
577
+ pushDexProtocols(sub.dexProtocol, fromMint, toMint);
578
+ }
579
+ }
580
+ else {
581
+ const fromMint = h.fromToken?.tokenContractAddress ??
582
+ req.inputMint;
583
+ const toMint = h.toToken?.tokenContractAddress ??
584
+ req.outputMint;
585
+ pushDexProtocols(h.dexProtocol, fromMint, toMint);
586
+ }
587
+ }
588
+ if (routePlan.length === 0) {
589
+ routePlan.push({
590
+ swapInfo: {
591
+ label: 'OKX Aggregator',
592
+ inputMint: req.inputMint,
593
+ outputMint: req.outputMint,
594
+ inAmount: req.amount,
595
+ outAmount,
596
+ },
597
+ percent: 100,
598
+ });
599
+ }
600
+ return {
601
+ provider: 'okx',
602
+ inputMint: req.inputMint,
603
+ outputMint: req.outputMint,
604
+ inAmount: req.amount,
605
+ outAmount,
606
+ otherAmountThreshold: minOut,
607
+ slippageBps: req.slippageBps,
608
+ priceImpactPct: rr.priceImpactPercentage ?? null,
609
+ platformFee: req.platformFeeBps && req.platformFeeBps > 0
610
+ ? {
611
+ amount: ((outBi * BigInt(req.platformFeeBps)) / 10000n).toString(),
612
+ feeBps: req.platformFeeBps,
613
+ mint: req.outputMint,
614
+ }
615
+ : null,
616
+ routePlan,
617
+ contextSlot: null,
618
+ latencyMs: Date.now() - t0,
619
+ rawQuote: {
620
+ escrowPubkey: req.escrowPubkey,
621
+ instructionLists: entry.instructionLists ?? [],
622
+ addressLookupTableAccount: entry.addressLookupTableAccount ?? [],
623
+ platformFee: req.platformFeeBps && req.platformFeeBps > 0 ? { feeBps: req.platformFeeBps } : null,
624
+ },
625
+ };
626
+ },
627
+ async swapInstructions(req) {
628
+ if (!req.quoteResponse || typeof req.quoteResponse !== 'object' || Array.isArray(req.quoteResponse)) {
629
+ throw new Error('Invalid OKX quoteResponse object');
630
+ }
631
+ const raw = req.quoteResponse;
632
+ if (raw.escrowPubkey !== undefined && raw.escrowPubkey !== req.escrowPubkey) {
633
+ throw new Error(`OKX quote was built for ${String(raw.escrowPubkey)}, not ${req.escrowPubkey}`);
634
+ }
635
+ if (!Array.isArray(raw.instructionLists)) {
636
+ throw new Error('OKX quoteResponse missing instructionLists array');
637
+ }
638
+ const ixs = raw.instructionLists.filter(isValidRouterInstruction);
639
+ const swapIx = ixs.find((ix) => !WRAPPER_PROGRAMS.has(ix.programId) &&
640
+ ix.accounts.some((a) => a.pubkey === req.escrowPubkey));
641
+ if (!swapIx) {
642
+ throw new Error('OKX response did not include an escrow-signed swap instruction');
643
+ }
644
+ return {
645
+ provider: 'okx',
646
+ swapInstruction: swapIx,
647
+ addressLookupTableAddresses: Array.isArray(raw.addressLookupTableAccount)
648
+ ? raw.addressLookupTableAccount.filter((x) => typeof x === 'string')
649
+ : [],
650
+ computeUnitLimit: computeAggregatorExecCuLimit({ forceMultiHopHeadroom: true }),
651
+ feeAccount: req.feeOwnerWallet ?? req.feeAccountAta ?? null,
652
+ };
653
+ },
654
+ };
655
+ }
656
+ function normalizeTitanInstruction(ix) {
657
+ if (!ix || typeof ix !== 'object' || Array.isArray(ix))
658
+ return null;
659
+ const rec = ix;
660
+ const programId = rec.programId ?? rec.p;
661
+ const data = rec.data ?? rec.d;
662
+ const rawAccs = rec.accounts ?? rec.a;
663
+ if (typeof programId !== 'string' ||
664
+ programId.length === 0 ||
665
+ typeof data !== 'string' ||
666
+ data.length === 0 ||
667
+ !Array.isArray(rawAccs)) {
668
+ return null;
669
+ }
670
+ const accounts = [];
671
+ for (const rawAcc of rawAccs) {
672
+ if (!rawAcc || typeof rawAcc !== 'object' || Array.isArray(rawAcc))
673
+ return null;
674
+ const a = rawAcc;
675
+ const pubkey = a.pubkey ?? a.p;
676
+ if (typeof pubkey !== 'string' || pubkey.length === 0)
677
+ return null;
678
+ accounts.push({
679
+ pubkey,
680
+ isSigner: Boolean(a.isSigner ?? a.s),
681
+ isWritable: Boolean(a.isWritable ?? a.w),
682
+ });
683
+ }
684
+ return { programId, data, accounts };
685
+ }
686
+ export function createTitanSwapAdapter(config = {}) {
687
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
688
+ const apiKey = config.apiKey?.trim() ?? '';
689
+ const rawUrl = config.apiUrl?.trim() ?? '';
690
+ const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://api.titan.exchange/api/v1', 'Titan');
691
+ return {
692
+ id: 'titan',
693
+ name: 'Titan Meta-Aggregator',
694
+ capabilities: {
695
+ supportsPlatformFeeBps: true,
696
+ supportsSwapInstructions: true,
697
+ quoteRequiresUserPubkey: true,
698
+ feeSide: 'output',
699
+ feeAccountStyle: 'ata',
700
+ },
701
+ isConfigured() {
702
+ return Boolean(rawUrl || apiKey);
703
+ },
704
+ async quote(req) {
705
+ validateQuoteParams(req);
706
+ if (!this.isConfigured()) {
707
+ throw new Error('Titan adapter not configured (set apiUrl or apiKey)');
708
+ }
709
+ if (!req.escrowPubkey) {
710
+ throw new Error('Titan requires escrowPubkey at quote time');
711
+ }
712
+ const base = resolveBase();
713
+ const t0 = Date.now();
714
+ const qs = new URLSearchParams({
715
+ inputMint: req.inputMint,
716
+ outputMint: req.outputMint,
717
+ amount: req.amount,
718
+ slippageBps: String(req.slippageBps),
719
+ userPublicKey: req.escrowPubkey,
720
+ ...(req.onlyDirectRoutes ? { onlyDirectRoutes: 'true' } : {}),
721
+ ...(req.platformFeeBps && req.platformFeeBps > 0 && req.feeAccountAta
722
+ ? { feeBps: String(req.platformFeeBps), feeAccount: req.feeAccountAta }
723
+ : {}),
724
+ });
725
+ const res = await safeAggregatorFetch(fetchImpl, `${base}/quote/swap?${qs.toString()}`, {
726
+ headers: {
727
+ accept: 'application/json',
728
+ ...(apiKey ? { authorization: `Bearer ${apiKey}`, 'x-api-key': apiKey } : {}),
729
+ },
730
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
731
+ }, 'Titan');
732
+ if (!res.ok)
733
+ throw new Error(`Titan quote HTTP ${res.status}`);
734
+ const decoded = (await res.json());
735
+ const quotesMap = decoded.quotes && typeof decoded.quotes === 'object' && !Array.isArray(decoded.quotes)
736
+ ? decoded.quotes
737
+ : {};
738
+ const winnerId = decoded.metadata?.ExpectedWinner;
739
+ let winnerKey = '';
740
+ let route;
741
+ let routeOut = null;
742
+ if (typeof winnerId === 'string' && Object.prototype.hasOwnProperty.call(quotesMap, winnerId)) {
743
+ const candidate = quotesMap[winnerId];
744
+ const candidateOut = parsePositiveUintString(candidate?.outAmount);
745
+ if (candidate && candidateOut !== null) {
746
+ winnerKey = winnerId;
747
+ route = candidate;
748
+ routeOut = candidateOut;
749
+ }
750
+ }
751
+ if (!route || routeOut === null) {
752
+ let bestOut = 0n;
753
+ for (const [k, r] of Object.entries(quotesMap)) {
754
+ const out = parsePositiveUintString(r?.outAmount);
755
+ if (out !== null && out > bestOut) {
756
+ bestOut = out;
757
+ winnerKey = k;
758
+ route = r;
759
+ routeOut = out;
760
+ }
761
+ }
762
+ }
763
+ if (!route || routeOut === null) {
764
+ throw new Error('Titan returned no valid quotes');
765
+ }
766
+ const outAmount = routeOut.toString();
767
+ const minOut = ((routeOut * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
768
+ const steps = Array.isArray(route.steps)
769
+ ? route.steps.filter((s) => Boolean(s && typeof s === 'object'))
770
+ : [];
771
+ const routePlan = steps.length > 0
772
+ ? steps.map((s) => ({
773
+ swapInfo: {
774
+ label: typeof s.label === 'string' && s.label.trim()
775
+ ? s.label.trim()
776
+ : winnerKey || 'Titan',
777
+ ammKey: s.ammKey,
778
+ inputMint: s.inputMint ?? req.inputMint,
779
+ outputMint: s.outputMint ?? req.outputMint,
780
+ inAmount: String(s.inAmount ?? req.amount),
781
+ outAmount: String(s.outAmount ?? outAmount),
782
+ },
783
+ percent: 100,
784
+ }))
785
+ : [
786
+ {
787
+ swapInfo: {
788
+ label: winnerKey || 'Titan',
789
+ inputMint: req.inputMint,
790
+ outputMint: req.outputMint,
791
+ inAmount: req.amount,
792
+ outAmount,
793
+ },
794
+ percent: 100,
795
+ },
796
+ ];
797
+ return {
798
+ provider: 'titan',
799
+ inputMint: decoded.inputMint ?? req.inputMint,
800
+ outputMint: decoded.outputMint ?? req.outputMint,
801
+ inAmount: String(route.inAmount ?? req.amount),
802
+ outAmount,
803
+ otherAmountThreshold: minOut,
804
+ slippageBps: route.slippageBps ?? req.slippageBps,
805
+ platformFee: req.platformFeeBps && req.platformFeeBps > 0
806
+ ? {
807
+ amount: ((routeOut * BigInt(req.platformFeeBps)) / 10000n).toString(),
808
+ feeBps: req.platformFeeBps,
809
+ mint: req.outputMint,
810
+ }
811
+ : null,
812
+ routePlan,
813
+ contextSlot: route.contextSlot ?? null,
814
+ latencyMs: Date.now() - t0,
815
+ rawQuote: {
816
+ winner: winnerKey,
817
+ escrowPubkey: req.escrowPubkey,
818
+ route,
819
+ platformFee: req.platformFeeBps && req.platformFeeBps > 0 ? { feeBps: req.platformFeeBps } : null,
820
+ },
821
+ };
822
+ },
823
+ async swapInstructions(req) {
824
+ if (!req.quoteResponse || typeof req.quoteResponse !== 'object' || Array.isArray(req.quoteResponse)) {
825
+ throw new Error('Invalid Titan quoteResponse object');
826
+ }
827
+ const raw = req.quoteResponse;
828
+ if (raw.escrowPubkey !== undefined && raw.escrowPubkey !== req.escrowPubkey) {
829
+ throw new Error(`Titan quote was built for ${String(raw.escrowPubkey)}, not ${req.escrowPubkey}`);
830
+ }
831
+ if (!raw.route || typeof raw.route !== 'object' || !Array.isArray(raw.route.instructions)) {
832
+ throw new Error('Titan quoteResponse missing route.instructions array');
833
+ }
834
+ const ixs = raw.route.instructions
835
+ .map(normalizeTitanInstruction)
836
+ .filter((x) => x !== null);
837
+ const swapIx = ixs.find((ix) => !WRAPPER_PROGRAMS.has(ix.programId) &&
838
+ ix.accounts.some((a) => a.pubkey === req.escrowPubkey));
839
+ if (!swapIx) {
840
+ throw new Error('Titan route did not expose a single escrow-signed swapInstruction');
841
+ }
842
+ const routeHopCount = Array.isArray(raw.route.steps) && raw.route.steps.length > 0 ? raw.route.steps.length : null;
843
+ return {
844
+ provider: 'titan',
845
+ swapInstruction: swapIx,
846
+ addressLookupTableAddresses: Array.isArray(raw.route.addressLookupTables)
847
+ ? raw.route.addressLookupTables.filter((x) => typeof x === 'string')
848
+ : [],
849
+ computeUnitLimit: computeAggregatorExecCuLimit({
850
+ reportedRouterCu: raw.route.computeUnits,
851
+ routeHopCount,
852
+ }),
853
+ feeAccount: req.feeAccountAta ?? null,
854
+ };
855
+ },
856
+ };
857
+ }
858
+ export function createBedrockSwapAdapter(config = {}) {
859
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
860
+ const apiKey = config.apiKey?.trim() ?? '';
861
+ const rawUrl = config.apiUrl?.trim() ?? '';
862
+ const resolveBase = () => {
863
+ if (!rawUrl)
864
+ throw new Error('Bedrock adapter not configured (set apiUrl)');
865
+ return validateAggregatorBaseUrl(rawUrl, 'Bedrock');
866
+ };
867
+ const makeHeaders = () => ({
868
+ accept: 'application/json',
869
+ 'content-type': 'application/json',
870
+ ...(apiKey ? { authorization: `Bearer ${apiKey}`, 'x-api-key': apiKey } : {}),
871
+ });
872
+ return {
873
+ id: 'bedrock',
874
+ name: 'Bedrock',
875
+ capabilities: {
876
+ supportsPlatformFeeBps: true,
877
+ supportsSwapInstructions: true,
878
+ quoteRequiresUserPubkey: false,
879
+ feeSide: 'either',
880
+ feeAccountStyle: 'owner_wallet',
881
+ },
882
+ isConfigured() {
883
+ return Boolean(rawUrl);
884
+ },
885
+ async quote(req) {
886
+ validateQuoteParams(req);
887
+ const base = resolveBase();
888
+ const t0 = Date.now();
889
+ const qs = new URLSearchParams({
890
+ inputMint: req.inputMint,
891
+ outputMint: req.outputMint,
892
+ amount: req.amount,
893
+ swapMode: 'ExactIn',
894
+ slippageBps: String(req.slippageBps),
895
+ programAuthority: 'true',
896
+ wrapAndUnwrapSol: 'false',
897
+ maxAccounts: String(req.maxAccounts ?? 28),
898
+ ...(req.onlyDirectRoutes ? { onlyDirectRoutes: 'true' } : {}),
899
+ ...(req.platformFeeBps && req.platformFeeBps > 0 && req.feeOwnerWallet
900
+ ? { platformFeeBps: String(req.platformFeeBps), feeAccount: req.feeOwnerWallet }
901
+ : { platformFeeBps: '0' }),
902
+ });
903
+ const res = await safeAggregatorFetch(fetchImpl, `${base}/quote?${qs.toString()}`, {
904
+ headers: makeHeaders(),
905
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
906
+ }, 'Bedrock');
907
+ if (!res.ok)
908
+ throw new Error(`Bedrock quote HTTP ${res.status}`);
909
+ const raw = (await res.json());
910
+ const outBi = parsePositiveUintString(raw.outAmount);
911
+ if (outBi === null)
912
+ throw new Error('Bedrock returned invalid or zero outAmount');
913
+ const routePlan = (Array.isArray(raw.routePlan) ? raw.routePlan : [])
914
+ .filter((item) => Boolean(item && typeof item === 'object'))
915
+ .map((item) => {
916
+ const si = item.swapInfo && typeof item.swapInfo === 'object' ? item.swapInfo : {};
917
+ return {
918
+ swapInfo: {
919
+ label: typeof si.label === 'string' && si.label.trim() ? si.label.trim() : 'Bedrock',
920
+ ammKey: si.ammKey,
921
+ inputMint: si.inputMint ?? req.inputMint,
922
+ outputMint: si.outputMint ?? req.outputMint,
923
+ inAmount: si.inAmount ?? req.amount,
924
+ outAmount: si.outAmount ?? outBi.toString(),
925
+ percent: item.percent,
926
+ },
927
+ percent: item.percent,
928
+ };
929
+ });
930
+ const feeObj = raw.fee ?? raw.platformFee;
931
+ return {
932
+ provider: 'bedrock',
933
+ inputMint: raw.inputMint ?? req.inputMint,
934
+ outputMint: raw.outputMint ?? req.outputMint,
935
+ inAmount: raw.inAmount ?? req.amount,
936
+ outAmount: outBi.toString(),
937
+ otherAmountThreshold: raw.otherAmountThreshold ?? outBi.toString(),
938
+ slippageBps: Number(raw.slippageBps ?? req.slippageBps),
939
+ priceImpactPct: raw.priceImpactPct ?? null,
940
+ platformFee: feeObj?.amount
941
+ ? {
942
+ amount: feeObj.amount,
943
+ feeBps: feeObj.feeBps ?? req.platformFeeBps ?? 0,
944
+ mint: raw.fee?.mint ?? req.outputMint,
945
+ }
946
+ : null,
947
+ routePlan,
948
+ contextSlot: raw.contextSlot ?? null,
949
+ latencyMs: Date.now() - t0,
950
+ rawQuote: raw,
951
+ };
952
+ },
953
+ async swapInstructions(req) {
954
+ const base = resolveBase();
955
+ const res = await safeAggregatorFetch(fetchImpl, `${base}/swap-instructions`, {
956
+ method: 'POST',
957
+ headers: makeHeaders(),
958
+ body: JSON.stringify({
959
+ userPublicKey: req.escrowPubkey,
960
+ quoteResponse: req.quoteResponse,
961
+ programAuthority: true,
962
+ wrapAndUnwrapSol: false,
963
+ skipUserAccountsRpcCalls: true,
964
+ }),
965
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
966
+ }, 'Bedrock');
967
+ if (!res.ok)
968
+ throw new Error(`Bedrock swap-instructions HTTP ${res.status}`);
969
+ const payload = (await res.json());
970
+ if (!isValidRouterInstruction(payload.swapInstruction)) {
971
+ throw new Error('Bedrock did not return a valid swapInstruction');
972
+ }
973
+ const rawRoutePlan = req.quoteResponse?.routePlan;
974
+ const routeHopCount = Array.isArray(rawRoutePlan) && rawRoutePlan.length > 0 ? rawRoutePlan.length : null;
975
+ return {
976
+ provider: 'bedrock',
977
+ swapInstruction: payload.swapInstruction,
978
+ addressLookupTableAddresses: Array.isArray(payload.addressLookupTableAddresses)
979
+ ? payload.addressLookupTableAddresses.filter((x) => typeof x === 'string')
980
+ : [],
981
+ computeUnitLimit: computeAggregatorExecCuLimit({
982
+ reportedRouterCu: payload.transactionConfig?.computeUnitLimit,
983
+ routeHopCount,
984
+ }),
985
+ feeAccount: req.feeOwnerWallet ?? req.feeAccountAta ?? null,
986
+ };
987
+ },
988
+ };
989
+ }
990
+ export class AudrenSwapRouter {
991
+ adapters = new Map();
992
+ enabledProviders;
993
+ defaultProvider;
994
+ defaultTimeoutMs;
995
+ allowedRouterPrograms;
996
+ allowUnverifiedRouter;
997
+ constructor(config = {}) {
998
+ const sharedFetch = config.fetchImpl;
999
+ const builtins = [
1000
+ createJupiterSwapAdapter({ ...config.jupiter, fetchImpl: config.jupiter?.fetchImpl ?? sharedFetch }),
1001
+ createDFlowSwapAdapter({ ...config.dflow, fetchImpl: config.dflow?.fetchImpl ?? sharedFetch }),
1002
+ createOkxSwapAdapter({ ...config.okx, fetchImpl: config.okx?.fetchImpl ?? sharedFetch }),
1003
+ createTitanSwapAdapter({ ...config.titan, fetchImpl: config.titan?.fetchImpl ?? sharedFetch }),
1004
+ createBedrockSwapAdapter({ ...config.bedrock, fetchImpl: config.bedrock?.fetchImpl ?? sharedFetch }),
1005
+ ];
1006
+ for (const adapter of builtins) {
1007
+ this.adapters.set(adapter.id, adapter);
1008
+ }
1009
+ for (const custom of config.customAdapters ?? []) {
1010
+ this.adapters.set(custom.id, custom);
1011
+ }
1012
+ this.enabledProviders = config.enabledProviders
1013
+ ? new Set(config.enabledProviders.map((s) => s.trim().toLowerCase()).filter(Boolean))
1014
+ : null;
1015
+ this.defaultProvider = config.defaultProvider ?? 'auto';
1016
+ this.defaultTimeoutMs = config.timeoutMs ?? 10_000;
1017
+ this.allowedRouterPrograms = config.allowedRouterPrograms ?? AUDREN_AUDITED_SWAP_ROUTERS;
1018
+ this.allowUnverifiedRouter = config.allowUnverifiedRouter ?? false;
1019
+ }
1020
+ /** Construct a router directly from Worker/Node environment variables. */
1021
+ static fromEnv(env, overrides = {}) {
1022
+ const enabledRaw = env.ENABLED_AGGREGATORS?.trim();
1023
+ const enabledProviders = enabledRaw
1024
+ ? enabledRaw
1025
+ .split(',')
1026
+ .map((s) => s.trim().toLowerCase())
1027
+ .filter(Boolean)
1028
+ : undefined;
1029
+ const defaultRaw = env.DEFAULT_AGGREGATOR?.trim().toLowerCase();
1030
+ const routersRaw = env.AUDITED_SWAP_ROUTER_PROGRAMS?.trim();
1031
+ const allowedRouterPrograms = routersRaw
1032
+ ? routersRaw
1033
+ .split(',')
1034
+ .map((s) => s.trim())
1035
+ .filter(Boolean)
1036
+ : undefined;
1037
+ return new AudrenSwapRouter({
1038
+ jupiter: { apiKey: env.JUPITER_API_KEY, apiUrl: env.JUPITER_API_URL },
1039
+ dflow: { apiKey: env.DFLOW_API_KEY, apiUrl: env.DFLOW_API_URL },
1040
+ okx: {
1041
+ apiKey: env.OKX_API_KEY,
1042
+ secretKey: env.OKX_SECRET_KEY,
1043
+ passphrase: env.OKX_PASSPHRASE,
1044
+ apiUrl: env.OKX_API_URL,
1045
+ },
1046
+ titan: { apiKey: env.TITAN_API_KEY, apiUrl: env.TITAN_API_URL },
1047
+ bedrock: { apiUrl: env.BEDROCK_API_URL, apiKey: env.BEDROCK_API_KEY },
1048
+ ...(enabledProviders && enabledProviders.length > 0 ? { enabledProviders } : {}),
1049
+ ...(defaultRaw ? { defaultProvider: defaultRaw } : {}),
1050
+ ...(allowedRouterPrograms && allowedRouterPrograms.length > 0 ? { allowedRouterPrograms } : {}),
1051
+ ...overrides,
1052
+ });
1053
+ }
1054
+ /** Register or override a custom aggregator adapter at runtime. */
1055
+ register(adapter) {
1056
+ this.adapters.set(adapter.id, adapter);
1057
+ return this;
1058
+ }
1059
+ getAdapter(id) {
1060
+ return this.adapters.get(id.trim().toLowerCase());
1061
+ }
1062
+ isEnabled(id) {
1063
+ return this.enabledProviders === null || this.enabledProviders.has(id.toLowerCase());
1064
+ }
1065
+ listProviders() {
1066
+ return Array.from(this.adapters.values()).map((a) => ({
1067
+ id: a.id,
1068
+ name: a.name,
1069
+ enabled: this.isEnabled(a.id) && a.isConfigured(),
1070
+ configured: a.isConfigured(),
1071
+ isDefault: a.id === this.defaultProvider,
1072
+ capabilities: a.capabilities,
1073
+ }));
1074
+ }
1075
+ resolveActiveAdapters() {
1076
+ return Array.from(this.adapters.values()).filter((a) => this.isEnabled(a.id) && a.isConfigured());
1077
+ }
1078
+ async quote(req) {
1079
+ validateQuoteParams(req);
1080
+ const escrowPubkey = req.escrowPubkey ??
1081
+ (await deriveEscrowPda(req.poolId ?? 0, req.shardId ?? 0, req.programId ?? AUDREN_PROGRAM_ID))
1082
+ .address;
1083
+ const adapterReq = {
1084
+ ...req,
1085
+ escrowPubkey,
1086
+ timeoutMs: req.timeoutMs ?? this.defaultTimeoutMs,
1087
+ };
1088
+ const excluded = req.excludeDexes ?? JUPITER_CPI_EXCLUDED_DEXES;
1089
+ const chosen = (req.provider ?? this.defaultProvider).trim().toLowerCase();
1090
+ if (chosen !== 'auto') {
1091
+ const adapter = this.adapters.get(chosen);
1092
+ if (!adapter)
1093
+ throw new Error(`Unknown swap aggregator "${chosen}"`);
1094
+ if (!this.isEnabled(adapter.id)) {
1095
+ throw new Error(`Swap aggregator "${adapter.id}" is disabled by router configuration`);
1096
+ }
1097
+ if (!adapter.isConfigured()) {
1098
+ throw new Error(`Swap aggregator "${adapter.id}" is not configured`);
1099
+ }
1100
+ const quote = await adapter.quote(adapterReq);
1101
+ const badVenue = findExcludedCpiVenue(quote, excluded);
1102
+ if (badVenue) {
1103
+ throw new Error(`Aggregator "${adapter.id}" routed via PDA-CPI-excluded venue "${badVenue}"`);
1104
+ }
1105
+ return {
1106
+ winner: quote,
1107
+ candidates: [{ provider: adapter.id, outAmount: quote.outAmount, latencyMs: quote.latencyMs }],
1108
+ escrowPubkey,
1109
+ };
1110
+ }
1111
+ const active = this.resolveActiveAdapters();
1112
+ if (active.length === 0) {
1113
+ throw new Error('No swap aggregators are configured on this AudrenSwapRouter');
1114
+ }
1115
+ const settled = await Promise.allSettled(active.map((a) => a.quote(adapterReq)));
1116
+ const quotes = [];
1117
+ const candidates = [];
1118
+ settled.forEach((res, idx) => {
1119
+ const id = active[idx].id;
1120
+ if (res.status === 'fulfilled') {
1121
+ const badVenue = findExcludedCpiVenue(res.value, excluded);
1122
+ if (badVenue) {
1123
+ candidates.push({
1124
+ provider: id,
1125
+ latencyMs: res.value.latencyMs,
1126
+ error: `Rejected PDA-CPI-excluded venue "${badVenue}"`,
1127
+ });
1128
+ return;
1129
+ }
1130
+ quotes.push(res.value);
1131
+ candidates.push({
1132
+ provider: id,
1133
+ outAmount: res.value.outAmount,
1134
+ latencyMs: res.value.latencyMs,
1135
+ });
1136
+ }
1137
+ else {
1138
+ candidates.push({
1139
+ provider: id,
1140
+ error: res.reason instanceof Error ? res.reason.message : String(res.reason),
1141
+ });
1142
+ }
1143
+ });
1144
+ if (quotes.length === 0) {
1145
+ throw new Error(`All configured swap aggregators failed: ${candidates.map((c) => `${c.provider}: ${c.error}`).join('; ')}`);
1146
+ }
1147
+ quotes.sort((a, b) => {
1148
+ const diff = BigInt(b.outAmount) - BigInt(a.outAmount);
1149
+ if (diff !== 0n)
1150
+ return diff > 0n ? 1 : -1;
1151
+ return a.latencyMs - b.latencyMs;
1152
+ });
1153
+ return { winner: quotes[0], candidates, escrowPubkey };
1154
+ }
1155
+ async buildSwapInstructions(req) {
1156
+ const providerId = req.provider.trim().toLowerCase();
1157
+ const adapter = this.adapters.get(providerId);
1158
+ if (!adapter)
1159
+ throw new Error(`Unknown swap aggregator "${providerId}"`);
1160
+ if (!this.isEnabled(adapter.id)) {
1161
+ throw new Error(`Swap aggregator "${adapter.id}" is disabled by router configuration`);
1162
+ }
1163
+ if (!adapter.isConfigured()) {
1164
+ throw new Error(`Swap aggregator "${adapter.id}" is not configured`);
1165
+ }
1166
+ const built = await adapter.swapInstructions({
1167
+ quoteResponse: req.quoteResponse,
1168
+ escrowPubkey: req.escrowPubkey,
1169
+ inputMint: req.inputMint,
1170
+ outputMint: req.outputMint,
1171
+ feeAccountAta: req.feeAccountAta,
1172
+ feeOwnerWallet: req.feeOwnerWallet,
1173
+ platformFeeBps: req.platformFeeBps,
1174
+ timeoutMs: req.timeoutMs ?? this.defaultTimeoutMs,
1175
+ signal: req.signal,
1176
+ });
1177
+ const allowUnverified = req.allowUnverifiedRouter ?? this.allowUnverifiedRouter;
1178
+ if (!allowUnverified) {
1179
+ const allowed = req.allowedRouterPrograms ?? this.allowedRouterPrograms;
1180
+ const routerProg = built.swapInstruction.programId;
1181
+ if (!allowed.includes(routerProg)) {
1182
+ throw new Error(`Aggregator "${adapter.id}" returned unapproved swap router program ${routerProg}`);
1183
+ }
1184
+ }
1185
+ return built;
1186
+ }
1187
+ /**
1188
+ * 1-call turnkey planner: derives the sharded `escrow` PDA, quotes (single or `'auto'` race),
1189
+ * builds normalized instructions, verifies router allowlist, strips the external `escrow` signer
1190
+ * bit, and promotes Solana transaction-wide writability for `ExecViaEscrow` (`Tag 6`).
1191
+ */
1192
+ async planPrivateSwap(req) {
1193
+ const programId = req.programId ?? AUDREN_PROGRAM_ID;
1194
+ const { winner, candidates, escrowPubkey } = await this.quote({
1195
+ provider: req.provider,
1196
+ poolId: req.poolId,
1197
+ shardId: req.shardId,
1198
+ programId,
1199
+ inputMint: req.inputMint,
1200
+ outputMint: req.outputMint,
1201
+ amount: req.amount,
1202
+ slippageBps: req.slippageBps,
1203
+ onlyDirectRoutes: req.onlyDirectRoutes,
1204
+ maxAccounts: req.maxAccounts,
1205
+ excludeDexes: req.excludeDexes,
1206
+ platformFeeBps: req.platformFeeBps,
1207
+ feeAccountAta: req.feeAccountAta,
1208
+ feeOwnerWallet: req.feeOwnerWallet,
1209
+ timeoutMs: req.timeoutMs,
1210
+ signal: req.signal,
1211
+ });
1212
+ const instructions = await this.buildSwapInstructions({
1213
+ provider: winner.provider,
1214
+ quoteResponse: winner.rawQuote,
1215
+ escrowPubkey,
1216
+ inputMint: req.inputMint,
1217
+ outputMint: req.outputMint,
1218
+ feeAccountAta: req.feeAccountAta,
1219
+ feeOwnerWallet: req.feeOwnerWallet,
1220
+ platformFeeBps: req.platformFeeBps,
1221
+ allowedRouterPrograms: req.allowedRouterPrograms,
1222
+ allowUnverifiedRouter: req.allowUnverifiedRouter,
1223
+ timeoutMs: req.timeoutMs,
1224
+ signal: req.signal,
1225
+ });
1226
+ const prepared = await prepareEscrowAccounts({
1227
+ poolId: req.poolId,
1228
+ shardId: req.shardId,
1229
+ inputMint: req.inputMint,
1230
+ outputMint: req.outputMint,
1231
+ inputTokenProgram: req.inputTokenProgram,
1232
+ outputTokenProgram: req.outputTokenProgram,
1233
+ actionAccounts: instructions.swapInstruction.accounts,
1234
+ extraWritablePubkeys: req.extraWritablePubkeys,
1235
+ programId,
1236
+ });
1237
+ return {
1238
+ provider: winner.provider,
1239
+ quote: winner,
1240
+ candidates,
1241
+ instructions,
1242
+ prepared,
1243
+ };
1244
+ }
1245
+ }