@audren-xyz/sdk 1.3.2 → 1.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aggregators.d.ts +7 -0
- package/dist/aggregators.js +248 -75
- package/dist/relayer.js +10 -1
- package/dist/swap.js +48 -3
- package/package.json +1 -1
package/dist/aggregators.d.ts
CHANGED
|
@@ -17,6 +17,10 @@ export type SwapAggregatorSelection = SwapAggregatorId | 'auto' | (string & {});
|
|
|
17
17
|
export declare const SINGLE_HOP_ROUTER_CU_HEADROOM = 350000;
|
|
18
18
|
export declare const MULTI_HOP_ROUTER_CU_HEADROOM = 550000;
|
|
19
19
|
export declare const MAX_AGGREGATOR_TX_CU_LIMIT = 1400000;
|
|
20
|
+
/** On-chain `ExecViaEscrow` (`program/src/lib.rs`) hard ceiling for CPI router account metas. */
|
|
21
|
+
export declare const MAX_EXEC_ROUTER_CPI_ACCOUNTS = 64;
|
|
22
|
+
/** Safe unique router account ceiling leaving headroom for Audren's fixed `ExecViaEscrow` accounts inside Solana Tx v1's 64-key cap. */
|
|
23
|
+
export declare const MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS = 46;
|
|
20
24
|
export interface SwapAggregatorCapabilities {
|
|
21
25
|
supportsPlatformFeeBps: boolean;
|
|
22
26
|
supportsSwapInstructions: boolean;
|
|
@@ -270,9 +274,12 @@ export declare class AudrenSwapRouter {
|
|
|
270
274
|
/** Register or override a custom aggregator adapter at runtime. */
|
|
271
275
|
register(adapter: SwapAggregatorAdapter): this;
|
|
272
276
|
getAdapter(id: string): SwapAggregatorAdapter | undefined;
|
|
277
|
+
getAllowedRouterPrograms(): readonly string[];
|
|
273
278
|
private isEnabled;
|
|
274
279
|
listProviders(): SwapProviderStatus[];
|
|
275
280
|
private resolveActiveAdapters;
|
|
281
|
+
private checkFeeAccountForAdapter;
|
|
282
|
+
private checkPrebuiltRouterAllowlist;
|
|
276
283
|
quote(req: AudrenSwapQuoteRequest): Promise<AudrenSwapQuoteResult>;
|
|
277
284
|
buildSwapInstructions(req: AudrenBuildSwapInstructionsRequest): Promise<NormalizedSwapInstructions>;
|
|
278
285
|
/**
|
package/dist/aggregators.js
CHANGED
|
@@ -5,6 +5,10 @@ import { JUPITER_CPI_EXCLUDED_DEXES, prepareEscrowAccounts, } from './swap.js';
|
|
|
5
5
|
export const SINGLE_HOP_ROUTER_CU_HEADROOM = 350_000;
|
|
6
6
|
export const MULTI_HOP_ROUTER_CU_HEADROOM = 550_000;
|
|
7
7
|
export const MAX_AGGREGATOR_TX_CU_LIMIT = 1_400_000;
|
|
8
|
+
/** On-chain `ExecViaEscrow` (`program/src/lib.rs`) hard ceiling for CPI router account metas. */
|
|
9
|
+
export const MAX_EXEC_ROUTER_CPI_ACCOUNTS = 64;
|
|
10
|
+
/** Safe unique router account ceiling leaving headroom for Audren's fixed `ExecViaEscrow` accounts inside Solana Tx v1's 64-key cap. */
|
|
11
|
+
export const MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS = 46;
|
|
8
12
|
const COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';
|
|
9
13
|
const ATA_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
|
|
10
14
|
const SYSTEM_PROGRAM = '11111111111111111111111111111111';
|
|
@@ -63,8 +67,18 @@ export function findExcludedCpiVenue(quote, excludedDexes = JUPITER_CPI_EXCLUDED
|
|
|
63
67
|
}
|
|
64
68
|
return null;
|
|
65
69
|
}
|
|
70
|
+
const U64_MAX = 0xffffffffffffffffn;
|
|
71
|
+
function isPlainObject(v) {
|
|
72
|
+
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
|
73
|
+
}
|
|
74
|
+
function defaultFetchImpl(input, init) {
|
|
75
|
+
return globalThis.fetch(input, init);
|
|
76
|
+
}
|
|
66
77
|
function validateAggregatorBaseUrl(raw, providerLabel) {
|
|
67
|
-
const trimmed = raw.trim()
|
|
78
|
+
const trimmed = raw.trim();
|
|
79
|
+
if (!trimmed || /[?#@]/.test(trimmed)) {
|
|
80
|
+
throw new Error(`${providerLabel} base URL must not contain credentials, query, or hash`);
|
|
81
|
+
}
|
|
68
82
|
let parsed;
|
|
69
83
|
try {
|
|
70
84
|
parsed = new URL(trimmed);
|
|
@@ -81,7 +95,7 @@ function validateAggregatorBaseUrl(raw, providerLabel) {
|
|
|
81
95
|
if (!isHttps && !isLoopbackHttp) {
|
|
82
96
|
throw new Error(`${providerLabel} base URL must use https:// (or http://localhost for local dev)`);
|
|
83
97
|
}
|
|
84
|
-
return
|
|
98
|
+
return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;
|
|
85
99
|
}
|
|
86
100
|
function buildFetchSignal(signal, timeoutMs = 10_000) {
|
|
87
101
|
if (signal)
|
|
@@ -98,6 +112,7 @@ async function safeAggregatorFetch(fetchImpl, url, init, providerLabel) {
|
|
|
98
112
|
redirect: 'manual',
|
|
99
113
|
});
|
|
100
114
|
if (res.status >= 300 && res.status < 400) {
|
|
115
|
+
await res.body?.cancel?.().catch(() => { });
|
|
101
116
|
throw new Error(`${providerLabel} returned unexpected HTTP ${res.status} redirect`);
|
|
102
117
|
}
|
|
103
118
|
return res;
|
|
@@ -110,15 +125,30 @@ function bytesToBase64(bytes) {
|
|
|
110
125
|
return btoa(bin);
|
|
111
126
|
}
|
|
112
127
|
function parsePositiveUintString(v) {
|
|
113
|
-
|
|
114
|
-
|
|
128
|
+
if (typeof v === 'bigint') {
|
|
129
|
+
return v > 0n && v <= U64_MAX ? v : null;
|
|
130
|
+
}
|
|
131
|
+
if (typeof v === 'number') {
|
|
132
|
+
if (!Number.isSafeInteger(v) || v <= 0)
|
|
133
|
+
return null;
|
|
134
|
+
return BigInt(v);
|
|
135
|
+
}
|
|
136
|
+
if (typeof v !== 'string')
|
|
137
|
+
return null;
|
|
138
|
+
if (!/^\d+$/.test(v) || v.length > 20)
|
|
115
139
|
return null;
|
|
116
|
-
const bi = BigInt(
|
|
117
|
-
return bi > 0n ? bi : null;
|
|
140
|
+
const bi = BigInt(v);
|
|
141
|
+
return bi > 0n && bi <= U64_MAX ? bi : null;
|
|
118
142
|
}
|
|
119
143
|
function validateQuoteParams(req) {
|
|
120
|
-
if (
|
|
121
|
-
throw new RangeError('
|
|
144
|
+
if (typeof req.inputMint !== 'string' || !req.inputMint.trim() || typeof req.outputMint !== 'string' || !req.outputMint.trim()) {
|
|
145
|
+
throw new RangeError('inputMint and outputMint must be non-empty mint pubkey strings');
|
|
146
|
+
}
|
|
147
|
+
if (req.inputMint === req.outputMint) {
|
|
148
|
+
throw new RangeError('inputMint and outputMint must be distinct');
|
|
149
|
+
}
|
|
150
|
+
if (typeof req.amount !== 'string' || parsePositiveUintString(req.amount) === null) {
|
|
151
|
+
throw new RangeError('amount must be a positive base-10 u64 integer string');
|
|
122
152
|
}
|
|
123
153
|
if (!Number.isInteger(req.slippageBps) || req.slippageBps < 0 || req.slippageBps >= 10_000) {
|
|
124
154
|
throw new RangeError('slippageBps must be an integer between 0 and 9999');
|
|
@@ -147,8 +177,50 @@ function isValidRouterInstruction(v) {
|
|
|
147
177
|
typeof a.isSigner === 'boolean' &&
|
|
148
178
|
typeof a.isWritable === 'boolean');
|
|
149
179
|
}
|
|
180
|
+
function validatePrebuiltEscrowInstructionBounds(ixs, escrowPubkey, providerLabel) {
|
|
181
|
+
const nonWrapper = ixs.filter((ix) => !WRAPPER_PROGRAMS.has(ix.programId));
|
|
182
|
+
if (nonWrapper.length !== 1) {
|
|
183
|
+
throw new Error(`${providerLabel} route must expose exactly 1 non-wrapper swap instruction (got ${nonWrapper.length})`);
|
|
184
|
+
}
|
|
185
|
+
const swapIx = nonWrapper[0];
|
|
186
|
+
if (!swapIx.accounts.some((a) => a.pubkey === escrowPubkey)) {
|
|
187
|
+
throw new Error(`${providerLabel} did not include an escrow-signed swap instruction`);
|
|
188
|
+
}
|
|
189
|
+
if (swapIx.accounts.length > MAX_EXEC_ROUTER_CPI_ACCOUNTS) {
|
|
190
|
+
throw new Error(`${providerLabel} route requires ${swapIx.accounts.length} router accounts (exceeds ExecViaEscrow max ${MAX_EXEC_ROUTER_CPI_ACCOUNTS})`);
|
|
191
|
+
}
|
|
192
|
+
const uniquePubkeys = new Set(swapIx.accounts.map((a) => a.pubkey)).size;
|
|
193
|
+
if (uniquePubkeys > MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS) {
|
|
194
|
+
throw new Error(`${providerLabel} route requires ${uniquePubkeys} unique router accounts (exceeds Tx v1 safe budget ${MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS})`);
|
|
195
|
+
}
|
|
196
|
+
return swapIx;
|
|
197
|
+
}
|
|
198
|
+
function extractPrebuiltRouterProgramId(rawQuote) {
|
|
199
|
+
if (typeof rawQuote.routerProgramId === 'string' && rawQuote.routerProgramId.length > 0) {
|
|
200
|
+
return rawQuote.routerProgramId;
|
|
201
|
+
}
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
function sleepAbortable(ms, signal) {
|
|
205
|
+
if (!signal)
|
|
206
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
207
|
+
if (signal.aborted) {
|
|
208
|
+
return Promise.reject(signal.reason instanceof Error ? signal.reason : new Error('Aborted'));
|
|
209
|
+
}
|
|
210
|
+
return new Promise((resolve, reject) => {
|
|
211
|
+
const onAbort = () => {
|
|
212
|
+
clearTimeout(timer);
|
|
213
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error('Aborted'));
|
|
214
|
+
};
|
|
215
|
+
const timer = setTimeout(() => {
|
|
216
|
+
signal.removeEventListener('abort', onAbort);
|
|
217
|
+
resolve();
|
|
218
|
+
}, ms);
|
|
219
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
220
|
+
});
|
|
221
|
+
}
|
|
150
222
|
export function createJupiterSwapAdapter(config = {}) {
|
|
151
|
-
const fetchImpl = config.fetchImpl ??
|
|
223
|
+
const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
|
|
152
224
|
const apiKey = config.apiKey?.trim() ?? '';
|
|
153
225
|
const rawUrl = config.apiUrl?.trim() ?? '';
|
|
154
226
|
const resolveBase = () => {
|
|
@@ -176,11 +248,12 @@ export function createJupiterSwapAdapter(config = {}) {
|
|
|
176
248
|
return res;
|
|
177
249
|
lastRes = res;
|
|
178
250
|
if (attempt < retryDelays.length) {
|
|
251
|
+
await res.body?.cancel?.().catch(() => { });
|
|
179
252
|
const retryAfter = Number(res.headers.get('retry-after') ?? '');
|
|
180
253
|
const delayMs = Number.isFinite(retryAfter) && retryAfter > 0
|
|
181
254
|
? Math.min(Math.max(retryAfter * 1000, 250), 1_500)
|
|
182
255
|
: retryDelays[attempt];
|
|
183
|
-
await
|
|
256
|
+
await sleepAbortable(delayMs, init.signal);
|
|
184
257
|
}
|
|
185
258
|
}
|
|
186
259
|
return lastRes;
|
|
@@ -222,23 +295,27 @@ export function createJupiterSwapAdapter(config = {}) {
|
|
|
222
295
|
signal: req.signal,
|
|
223
296
|
timeoutMs: req.timeoutMs,
|
|
224
297
|
});
|
|
225
|
-
if (!res.ok)
|
|
226
|
-
|
|
227
|
-
|
|
298
|
+
if (!res.ok) {
|
|
299
|
+
await res.body?.cancel?.().catch(() => { });
|
|
300
|
+
return { ok: false, status: res.status };
|
|
301
|
+
}
|
|
302
|
+
const json = await res.json();
|
|
303
|
+
if (!isPlainObject(json))
|
|
304
|
+
throw new Error('Jupiter returned non-object quote JSON');
|
|
305
|
+
return { ok: true, data: json };
|
|
228
306
|
};
|
|
229
|
-
let raw;
|
|
230
307
|
const wantDirect = req.onlyDirectRoutes ?? true;
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
else {
|
|
239
|
-
throw err;
|
|
240
|
-
}
|
|
308
|
+
let first = await doFetch(wantDirect);
|
|
309
|
+
if (!first.ok &&
|
|
310
|
+
wantDirect &&
|
|
311
|
+
req.onlyDirectRoutes === undefined &&
|
|
312
|
+
!req.signal?.aborted &&
|
|
313
|
+
(first.status === 400 || first.status === 404)) {
|
|
314
|
+
first = await doFetch(false);
|
|
241
315
|
}
|
|
316
|
+
if (!first.ok)
|
|
317
|
+
throw new Error(`Jupiter quote HTTP ${first.status}`);
|
|
318
|
+
const raw = first.data;
|
|
242
319
|
const outBi = parsePositiveUintString(raw.outAmount);
|
|
243
320
|
if (outBi === null)
|
|
244
321
|
throw new Error('Jupiter returned invalid or zero outAmount');
|
|
@@ -298,7 +375,10 @@ export function createJupiterSwapAdapter(config = {}) {
|
|
|
298
375
|
});
|
|
299
376
|
if (!res.ok)
|
|
300
377
|
throw new Error(`Jupiter swap-instructions HTTP ${res.status}`);
|
|
301
|
-
const
|
|
378
|
+
const payloadRaw = await res.json();
|
|
379
|
+
if (!isPlainObject(payloadRaw))
|
|
380
|
+
throw new Error('Jupiter returned non-object swap-instructions JSON');
|
|
381
|
+
const payload = payloadRaw;
|
|
302
382
|
if (!isValidRouterInstruction(payload.swapInstruction)) {
|
|
303
383
|
throw new Error('Jupiter did not return a valid swapInstruction');
|
|
304
384
|
}
|
|
@@ -320,7 +400,7 @@ export function createJupiterSwapAdapter(config = {}) {
|
|
|
320
400
|
};
|
|
321
401
|
}
|
|
322
402
|
export function createDFlowSwapAdapter(config = {}) {
|
|
323
|
-
const fetchImpl = config.fetchImpl ??
|
|
403
|
+
const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
|
|
324
404
|
const apiKey = config.apiKey?.trim() ?? '';
|
|
325
405
|
const rawUrl = config.apiUrl?.trim() ?? '';
|
|
326
406
|
const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://quote-api.dflow.net', 'DFlow');
|
|
@@ -366,7 +446,10 @@ export function createDFlowSwapAdapter(config = {}) {
|
|
|
366
446
|
}, 'DFlow');
|
|
367
447
|
if (!res.ok)
|
|
368
448
|
throw new Error(`DFlow quote HTTP ${res.status}`);
|
|
369
|
-
const
|
|
449
|
+
const rawJson = await res.json();
|
|
450
|
+
if (!isPlainObject(rawJson))
|
|
451
|
+
throw new Error('DFlow returned non-object quote JSON');
|
|
452
|
+
const raw = rawJson;
|
|
370
453
|
const outBi = parsePositiveUintString(raw.outAmount);
|
|
371
454
|
if (outBi === null)
|
|
372
455
|
throw new Error('DFlow returned invalid or zero outAmount');
|
|
@@ -432,7 +515,10 @@ export function createDFlowSwapAdapter(config = {}) {
|
|
|
432
515
|
}, 'DFlow');
|
|
433
516
|
if (!res.ok)
|
|
434
517
|
throw new Error(`DFlow swap-instructions HTTP ${res.status}`);
|
|
435
|
-
const
|
|
518
|
+
const payloadRaw = await res.json();
|
|
519
|
+
if (!isPlainObject(payloadRaw))
|
|
520
|
+
throw new Error('DFlow returned non-object swap-instructions JSON');
|
|
521
|
+
const payload = payloadRaw;
|
|
436
522
|
if (!isValidRouterInstruction(payload.swapInstruction)) {
|
|
437
523
|
throw new Error('DFlow did not return a valid swapInstruction');
|
|
438
524
|
}
|
|
@@ -459,7 +545,7 @@ export function createDFlowSwapAdapter(config = {}) {
|
|
|
459
545
|
const OKX_CHAIN_INDEX = '501';
|
|
460
546
|
const OKX_SWAP_IX_PATH = '/api/v6/dex/aggregator/swap-instruction';
|
|
461
547
|
export function createOkxSwapAdapter(config = {}) {
|
|
462
|
-
const fetchImpl = config.fetchImpl ??
|
|
548
|
+
const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
|
|
463
549
|
const apiKey = config.apiKey?.trim() ?? '';
|
|
464
550
|
const secretKey = config.secretKey?.trim() ?? '';
|
|
465
551
|
const passphrase = config.passphrase?.trim() ?? '';
|
|
@@ -525,13 +611,21 @@ export function createOkxSwapAdapter(config = {}) {
|
|
|
525
611
|
}, 'OKX');
|
|
526
612
|
if (!res.ok)
|
|
527
613
|
throw new Error(`OKX swap-instruction HTTP ${res.status}`);
|
|
528
|
-
const
|
|
614
|
+
const bodyRaw = await res.json();
|
|
615
|
+
if (!isPlainObject(bodyRaw))
|
|
616
|
+
throw new Error('OKX returned non-object response JSON');
|
|
617
|
+
const body = bodyRaw;
|
|
529
618
|
const entry = Array.isArray(body.data) ? body.data[0] : body.data;
|
|
530
619
|
const outBi = parsePositiveUintString(entry?.routerResult?.toTokenAmount);
|
|
531
620
|
if (body.code !== '0' || !entry?.routerResult || outBi === null) {
|
|
532
|
-
|
|
621
|
+
const safeCode = typeof body.code === 'string' && body.code.trim() ? body.code.trim().slice(0, 16) : 'unknown';
|
|
622
|
+
throw new Error(`OKX API returned no valid route (code ${safeCode})`);
|
|
533
623
|
}
|
|
534
624
|
const rr = entry.routerResult;
|
|
625
|
+
const prebuiltIxs = Array.isArray(entry.instructionLists)
|
|
626
|
+
? entry.instructionLists.filter(isValidRouterInstruction)
|
|
627
|
+
: [];
|
|
628
|
+
const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'OKX');
|
|
535
629
|
const outAmount = outBi.toString();
|
|
536
630
|
const minOut = ((outBi * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
|
|
537
631
|
const routePlan = [];
|
|
@@ -597,6 +691,7 @@ export function createOkxSwapAdapter(config = {}) {
|
|
|
597
691
|
percent: 100,
|
|
598
692
|
});
|
|
599
693
|
}
|
|
694
|
+
const feeApplied = Boolean(req.platformFeeBps && req.platformFeeBps > 0 && req.feeOwnerWallet);
|
|
600
695
|
return {
|
|
601
696
|
provider: 'okx',
|
|
602
697
|
inputMint: req.inputMint,
|
|
@@ -606,7 +701,7 @@ export function createOkxSwapAdapter(config = {}) {
|
|
|
606
701
|
otherAmountThreshold: minOut,
|
|
607
702
|
slippageBps: req.slippageBps,
|
|
608
703
|
priceImpactPct: rr.priceImpactPercentage ?? null,
|
|
609
|
-
platformFee:
|
|
704
|
+
platformFee: feeApplied
|
|
610
705
|
? {
|
|
611
706
|
amount: ((outBi * BigInt(req.platformFeeBps)) / 10000n).toString(),
|
|
612
707
|
feeBps: req.platformFeeBps,
|
|
@@ -618,9 +713,10 @@ export function createOkxSwapAdapter(config = {}) {
|
|
|
618
713
|
latencyMs: Date.now() - t0,
|
|
619
714
|
rawQuote: {
|
|
620
715
|
escrowPubkey: req.escrowPubkey,
|
|
716
|
+
routerProgramId: swapIx.programId,
|
|
621
717
|
instructionLists: entry.instructionLists ?? [],
|
|
622
718
|
addressLookupTableAccount: entry.addressLookupTableAccount ?? [],
|
|
623
|
-
platformFee:
|
|
719
|
+
platformFee: feeApplied ? { feeBps: req.platformFeeBps } : null,
|
|
624
720
|
},
|
|
625
721
|
};
|
|
626
722
|
},
|
|
@@ -636,11 +732,7 @@ export function createOkxSwapAdapter(config = {}) {
|
|
|
636
732
|
throw new Error('OKX quoteResponse missing instructionLists array');
|
|
637
733
|
}
|
|
638
734
|
const ixs = raw.instructionLists.filter(isValidRouterInstruction);
|
|
639
|
-
const swapIx = ixs.
|
|
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
|
-
}
|
|
735
|
+
const swapIx = validatePrebuiltEscrowInstructionBounds(ixs, req.escrowPubkey, 'OKX');
|
|
644
736
|
return {
|
|
645
737
|
provider: 'okx',
|
|
646
738
|
swapInstruction: swapIx,
|
|
@@ -648,7 +740,7 @@ export function createOkxSwapAdapter(config = {}) {
|
|
|
648
740
|
? raw.addressLookupTableAccount.filter((x) => typeof x === 'string')
|
|
649
741
|
: [],
|
|
650
742
|
computeUnitLimit: computeAggregatorExecCuLimit({ forceMultiHopHeadroom: true }),
|
|
651
|
-
feeAccount: req.feeOwnerWallet ??
|
|
743
|
+
feeAccount: req.feeOwnerWallet ?? null,
|
|
652
744
|
};
|
|
653
745
|
},
|
|
654
746
|
};
|
|
@@ -684,7 +776,7 @@ function normalizeTitanInstruction(ix) {
|
|
|
684
776
|
return { programId, data, accounts };
|
|
685
777
|
}
|
|
686
778
|
export function createTitanSwapAdapter(config = {}) {
|
|
687
|
-
const fetchImpl = config.fetchImpl ??
|
|
779
|
+
const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
|
|
688
780
|
const apiKey = config.apiKey?.trim() ?? '';
|
|
689
781
|
const rawUrl = config.apiUrl?.trim() ?? '';
|
|
690
782
|
const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://api.titan.exchange/api/v1', 'Titan');
|
|
@@ -731,7 +823,10 @@ export function createTitanSwapAdapter(config = {}) {
|
|
|
731
823
|
}, 'Titan');
|
|
732
824
|
if (!res.ok)
|
|
733
825
|
throw new Error(`Titan quote HTTP ${res.status}`);
|
|
734
|
-
const
|
|
826
|
+
const decodedRaw = await res.json();
|
|
827
|
+
if (!isPlainObject(decodedRaw))
|
|
828
|
+
throw new Error('Titan returned non-object quote JSON');
|
|
829
|
+
const decoded = decodedRaw;
|
|
735
830
|
const quotesMap = decoded.quotes && typeof decoded.quotes === 'object' && !Array.isArray(decoded.quotes)
|
|
736
831
|
? decoded.quotes
|
|
737
832
|
: {};
|
|
@@ -763,6 +858,12 @@ export function createTitanSwapAdapter(config = {}) {
|
|
|
763
858
|
if (!route || routeOut === null) {
|
|
764
859
|
throw new Error('Titan returned no valid quotes');
|
|
765
860
|
}
|
|
861
|
+
const prebuiltIxs = Array.isArray(route.instructions)
|
|
862
|
+
? route.instructions
|
|
863
|
+
.map(normalizeTitanInstruction)
|
|
864
|
+
.filter((x) => x !== null)
|
|
865
|
+
: [];
|
|
866
|
+
const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'Titan');
|
|
766
867
|
const outAmount = routeOut.toString();
|
|
767
868
|
const minOut = ((routeOut * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
|
|
768
869
|
const steps = Array.isArray(route.steps)
|
|
@@ -794,6 +895,7 @@ export function createTitanSwapAdapter(config = {}) {
|
|
|
794
895
|
percent: 100,
|
|
795
896
|
},
|
|
796
897
|
];
|
|
898
|
+
const feeApplied = Boolean(req.platformFeeBps && req.platformFeeBps > 0 && req.feeAccountAta);
|
|
797
899
|
return {
|
|
798
900
|
provider: 'titan',
|
|
799
901
|
inputMint: decoded.inputMint ?? req.inputMint,
|
|
@@ -802,7 +904,7 @@ export function createTitanSwapAdapter(config = {}) {
|
|
|
802
904
|
outAmount,
|
|
803
905
|
otherAmountThreshold: minOut,
|
|
804
906
|
slippageBps: route.slippageBps ?? req.slippageBps,
|
|
805
|
-
platformFee:
|
|
907
|
+
platformFee: feeApplied
|
|
806
908
|
? {
|
|
807
909
|
amount: ((routeOut * BigInt(req.platformFeeBps)) / 10000n).toString(),
|
|
808
910
|
feeBps: req.platformFeeBps,
|
|
@@ -815,8 +917,9 @@ export function createTitanSwapAdapter(config = {}) {
|
|
|
815
917
|
rawQuote: {
|
|
816
918
|
winner: winnerKey,
|
|
817
919
|
escrowPubkey: req.escrowPubkey,
|
|
920
|
+
routerProgramId: swapIx.programId,
|
|
818
921
|
route,
|
|
819
|
-
platformFee:
|
|
922
|
+
platformFee: feeApplied ? { feeBps: req.platformFeeBps } : null,
|
|
820
923
|
},
|
|
821
924
|
};
|
|
822
925
|
},
|
|
@@ -834,11 +937,7 @@ export function createTitanSwapAdapter(config = {}) {
|
|
|
834
937
|
const ixs = raw.route.instructions
|
|
835
938
|
.map(normalizeTitanInstruction)
|
|
836
939
|
.filter((x) => x !== null);
|
|
837
|
-
const swapIx = ixs.
|
|
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
|
-
}
|
|
940
|
+
const swapIx = validatePrebuiltEscrowInstructionBounds(ixs, req.escrowPubkey, 'Titan');
|
|
842
941
|
const routeHopCount = Array.isArray(raw.route.steps) && raw.route.steps.length > 0 ? raw.route.steps.length : null;
|
|
843
942
|
return {
|
|
844
943
|
provider: 'titan',
|
|
@@ -856,7 +955,7 @@ export function createTitanSwapAdapter(config = {}) {
|
|
|
856
955
|
};
|
|
857
956
|
}
|
|
858
957
|
export function createBedrockSwapAdapter(config = {}) {
|
|
859
|
-
const fetchImpl = config.fetchImpl ??
|
|
958
|
+
const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
|
|
860
959
|
const apiKey = config.apiKey?.trim() ?? '';
|
|
861
960
|
const rawUrl = config.apiUrl?.trim() ?? '';
|
|
862
961
|
const resolveBase = () => {
|
|
@@ -906,7 +1005,10 @@ export function createBedrockSwapAdapter(config = {}) {
|
|
|
906
1005
|
}, 'Bedrock');
|
|
907
1006
|
if (!res.ok)
|
|
908
1007
|
throw new Error(`Bedrock quote HTTP ${res.status}`);
|
|
909
|
-
const
|
|
1008
|
+
const rawJson = await res.json();
|
|
1009
|
+
if (!isPlainObject(rawJson))
|
|
1010
|
+
throw new Error('Bedrock returned non-object quote JSON');
|
|
1011
|
+
const raw = rawJson;
|
|
910
1012
|
const outBi = parsePositiveUintString(raw.outAmount);
|
|
911
1013
|
if (outBi === null)
|
|
912
1014
|
throw new Error('Bedrock returned invalid or zero outAmount');
|
|
@@ -928,6 +1030,7 @@ export function createBedrockSwapAdapter(config = {}) {
|
|
|
928
1030
|
};
|
|
929
1031
|
});
|
|
930
1032
|
const feeObj = raw.fee ?? raw.platformFee;
|
|
1033
|
+
const parsedSlippage = Number(raw.slippageBps);
|
|
931
1034
|
return {
|
|
932
1035
|
provider: 'bedrock',
|
|
933
1036
|
inputMint: raw.inputMint ?? req.inputMint,
|
|
@@ -935,7 +1038,7 @@ export function createBedrockSwapAdapter(config = {}) {
|
|
|
935
1038
|
inAmount: raw.inAmount ?? req.amount,
|
|
936
1039
|
outAmount: outBi.toString(),
|
|
937
1040
|
otherAmountThreshold: raw.otherAmountThreshold ?? outBi.toString(),
|
|
938
|
-
slippageBps: Number(
|
|
1041
|
+
slippageBps: Number.isFinite(parsedSlippage) && parsedSlippage >= 0 ? parsedSlippage : req.slippageBps,
|
|
939
1042
|
priceImpactPct: raw.priceImpactPct ?? null,
|
|
940
1043
|
platformFee: feeObj?.amount
|
|
941
1044
|
? {
|
|
@@ -966,7 +1069,10 @@ export function createBedrockSwapAdapter(config = {}) {
|
|
|
966
1069
|
}, 'Bedrock');
|
|
967
1070
|
if (!res.ok)
|
|
968
1071
|
throw new Error(`Bedrock swap-instructions HTTP ${res.status}`);
|
|
969
|
-
const
|
|
1072
|
+
const payloadRaw = await res.json();
|
|
1073
|
+
if (!isPlainObject(payloadRaw))
|
|
1074
|
+
throw new Error('Bedrock returned non-object swap-instructions JSON');
|
|
1075
|
+
const payload = payloadRaw;
|
|
970
1076
|
if (!isValidRouterInstruction(payload.swapInstruction)) {
|
|
971
1077
|
throw new Error('Bedrock did not return a valid swapInstruction');
|
|
972
1078
|
}
|
|
@@ -982,7 +1088,7 @@ export function createBedrockSwapAdapter(config = {}) {
|
|
|
982
1088
|
reportedRouterCu: payload.transactionConfig?.computeUnitLimit,
|
|
983
1089
|
routeHopCount,
|
|
984
1090
|
}),
|
|
985
|
-
feeAccount: req.feeOwnerWallet ??
|
|
1091
|
+
feeAccount: req.feeOwnerWallet ?? null,
|
|
986
1092
|
};
|
|
987
1093
|
},
|
|
988
1094
|
};
|
|
@@ -1004,15 +1110,15 @@ export class AudrenSwapRouter {
|
|
|
1004
1110
|
createBedrockSwapAdapter({ ...config.bedrock, fetchImpl: config.bedrock?.fetchImpl ?? sharedFetch }),
|
|
1005
1111
|
];
|
|
1006
1112
|
for (const adapter of builtins) {
|
|
1007
|
-
this.
|
|
1113
|
+
this.register(adapter);
|
|
1008
1114
|
}
|
|
1009
1115
|
for (const custom of config.customAdapters ?? []) {
|
|
1010
|
-
this.
|
|
1116
|
+
this.register(custom);
|
|
1011
1117
|
}
|
|
1012
1118
|
this.enabledProviders = config.enabledProviders
|
|
1013
1119
|
? new Set(config.enabledProviders.map((s) => s.trim().toLowerCase()).filter(Boolean))
|
|
1014
1120
|
: null;
|
|
1015
|
-
this.defaultProvider = config.defaultProvider ?? 'auto';
|
|
1121
|
+
this.defaultProvider = (config.defaultProvider ?? 'auto').trim().toLowerCase();
|
|
1016
1122
|
this.defaultTimeoutMs = config.timeoutMs ?? 10_000;
|
|
1017
1123
|
this.allowedRouterPrograms = config.allowedRouterPrograms ?? AUDREN_AUDITED_SWAP_ROUTERS;
|
|
1018
1124
|
this.allowUnverifiedRouter = config.allowUnverifiedRouter ?? false;
|
|
@@ -1053,27 +1159,59 @@ export class AudrenSwapRouter {
|
|
|
1053
1159
|
}
|
|
1054
1160
|
/** Register or override a custom aggregator adapter at runtime. */
|
|
1055
1161
|
register(adapter) {
|
|
1056
|
-
|
|
1162
|
+
const key = adapter.id.trim().toLowerCase();
|
|
1163
|
+
if (!key || key === 'auto') {
|
|
1164
|
+
throw new RangeError(`Invalid swap aggregator id "${adapter.id}" (must be non-empty and not "auto")`);
|
|
1165
|
+
}
|
|
1166
|
+
this.adapters.set(key, adapter);
|
|
1057
1167
|
return this;
|
|
1058
1168
|
}
|
|
1059
1169
|
getAdapter(id) {
|
|
1060
1170
|
return this.adapters.get(id.trim().toLowerCase());
|
|
1061
1171
|
}
|
|
1172
|
+
getAllowedRouterPrograms() {
|
|
1173
|
+
return [...this.allowedRouterPrograms];
|
|
1174
|
+
}
|
|
1062
1175
|
isEnabled(id) {
|
|
1063
|
-
return this.enabledProviders === null || this.enabledProviders.has(id.toLowerCase());
|
|
1176
|
+
return this.enabledProviders === null || this.enabledProviders.has(id.trim().toLowerCase());
|
|
1064
1177
|
}
|
|
1065
1178
|
listProviders() {
|
|
1066
|
-
return Array.from(this.adapters.
|
|
1067
|
-
id:
|
|
1179
|
+
return Array.from(this.adapters.entries()).map(([key, a]) => ({
|
|
1180
|
+
id: key,
|
|
1068
1181
|
name: a.name,
|
|
1069
|
-
enabled: this.isEnabled(
|
|
1182
|
+
enabled: this.isEnabled(key) && a.isConfigured(),
|
|
1070
1183
|
configured: a.isConfigured(),
|
|
1071
|
-
isDefault:
|
|
1184
|
+
isDefault: key === this.defaultProvider,
|
|
1072
1185
|
capabilities: a.capabilities,
|
|
1073
1186
|
}));
|
|
1074
1187
|
}
|
|
1075
1188
|
resolveActiveAdapters() {
|
|
1076
|
-
return Array.from(this.adapters.
|
|
1189
|
+
return Array.from(this.adapters.entries())
|
|
1190
|
+
.filter(([key, a]) => this.isEnabled(key) && a.isConfigured())
|
|
1191
|
+
.map(([key, adapter]) => ({ key, adapter }));
|
|
1192
|
+
}
|
|
1193
|
+
checkFeeAccountForAdapter(adapter, req) {
|
|
1194
|
+
if (!req.platformFeeBps || req.platformFeeBps <= 0)
|
|
1195
|
+
return null;
|
|
1196
|
+
if (!adapter.capabilities.supportsPlatformFeeBps) {
|
|
1197
|
+
return `Aggregator "${adapter.id}" does not support platformFeeBps`;
|
|
1198
|
+
}
|
|
1199
|
+
if (adapter.capabilities.feeAccountStyle === 'ata' && !req.feeAccountAta) {
|
|
1200
|
+
return `Aggregator "${adapter.id}" requires feeAccountAta when platformFeeBps > 0`;
|
|
1201
|
+
}
|
|
1202
|
+
if (adapter.capabilities.feeAccountStyle === 'owner_wallet' && !req.feeOwnerWallet) {
|
|
1203
|
+
return `Aggregator "${adapter.id}" requires feeOwnerWallet when platformFeeBps > 0`;
|
|
1204
|
+
}
|
|
1205
|
+
return null;
|
|
1206
|
+
}
|
|
1207
|
+
checkPrebuiltRouterAllowlist(quote) {
|
|
1208
|
+
if (this.allowUnverifiedRouter)
|
|
1209
|
+
return null;
|
|
1210
|
+
const prebuiltRouter = extractPrebuiltRouterProgramId(quote.rawQuote);
|
|
1211
|
+
if (prebuiltRouter && !this.allowedRouterPrograms.includes(prebuiltRouter)) {
|
|
1212
|
+
return `Aggregator "${quote.provider}" returned unapproved swap router program ${prebuiltRouter}`;
|
|
1213
|
+
}
|
|
1214
|
+
return null;
|
|
1077
1215
|
}
|
|
1078
1216
|
async quote(req) {
|
|
1079
1217
|
validateQuoteParams(req);
|
|
@@ -1091,20 +1229,26 @@ export class AudrenSwapRouter {
|
|
|
1091
1229
|
const adapter = this.adapters.get(chosen);
|
|
1092
1230
|
if (!adapter)
|
|
1093
1231
|
throw new Error(`Unknown swap aggregator "${chosen}"`);
|
|
1094
|
-
if (!this.isEnabled(
|
|
1095
|
-
throw new Error(`Swap aggregator "${
|
|
1232
|
+
if (!this.isEnabled(chosen)) {
|
|
1233
|
+
throw new Error(`Swap aggregator "${chosen}" is disabled by router configuration`);
|
|
1096
1234
|
}
|
|
1097
1235
|
if (!adapter.isConfigured()) {
|
|
1098
|
-
throw new Error(`Swap aggregator "${
|
|
1236
|
+
throw new Error(`Swap aggregator "${chosen}" is not configured`);
|
|
1099
1237
|
}
|
|
1238
|
+
const feeErr = this.checkFeeAccountForAdapter(adapter, adapterReq);
|
|
1239
|
+
if (feeErr)
|
|
1240
|
+
throw new Error(feeErr);
|
|
1100
1241
|
const quote = await adapter.quote(adapterReq);
|
|
1101
1242
|
const badVenue = findExcludedCpiVenue(quote, excluded);
|
|
1102
1243
|
if (badVenue) {
|
|
1103
|
-
throw new Error(`Aggregator "${
|
|
1244
|
+
throw new Error(`Aggregator "${chosen}" routed via PDA-CPI-excluded venue "${badVenue}"`);
|
|
1104
1245
|
}
|
|
1246
|
+
const routerErr = this.checkPrebuiltRouterAllowlist(quote);
|
|
1247
|
+
if (routerErr)
|
|
1248
|
+
throw new Error(routerErr);
|
|
1105
1249
|
return {
|
|
1106
1250
|
winner: quote,
|
|
1107
|
-
candidates: [{ provider:
|
|
1251
|
+
candidates: [{ provider: chosen, outAmount: quote.outAmount, latencyMs: quote.latencyMs }],
|
|
1108
1252
|
escrowPubkey,
|
|
1109
1253
|
};
|
|
1110
1254
|
}
|
|
@@ -1112,11 +1256,21 @@ export class AudrenSwapRouter {
|
|
|
1112
1256
|
if (active.length === 0) {
|
|
1113
1257
|
throw new Error('No swap aggregators are configured on this AudrenSwapRouter');
|
|
1114
1258
|
}
|
|
1115
|
-
const
|
|
1116
|
-
const quotes = [];
|
|
1259
|
+
const eligible = [];
|
|
1117
1260
|
const candidates = [];
|
|
1261
|
+
for (const entry of active) {
|
|
1262
|
+
const feeErr = this.checkFeeAccountForAdapter(entry.adapter, adapterReq);
|
|
1263
|
+
if (feeErr) {
|
|
1264
|
+
candidates.push({ provider: entry.key, error: feeErr });
|
|
1265
|
+
}
|
|
1266
|
+
else {
|
|
1267
|
+
eligible.push(entry);
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const settled = await Promise.allSettled(eligible.map((e) => e.adapter.quote(adapterReq)));
|
|
1271
|
+
const quotes = [];
|
|
1118
1272
|
settled.forEach((res, idx) => {
|
|
1119
|
-
const id =
|
|
1273
|
+
const id = eligible[idx].key;
|
|
1120
1274
|
if (res.status === 'fulfilled') {
|
|
1121
1275
|
const badVenue = findExcludedCpiVenue(res.value, excluded);
|
|
1122
1276
|
if (badVenue) {
|
|
@@ -1127,6 +1281,15 @@ export class AudrenSwapRouter {
|
|
|
1127
1281
|
});
|
|
1128
1282
|
return;
|
|
1129
1283
|
}
|
|
1284
|
+
const routerErr = this.checkPrebuiltRouterAllowlist(res.value);
|
|
1285
|
+
if (routerErr) {
|
|
1286
|
+
candidates.push({
|
|
1287
|
+
provider: id,
|
|
1288
|
+
latencyMs: res.value.latencyMs,
|
|
1289
|
+
error: routerErr,
|
|
1290
|
+
});
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1130
1293
|
quotes.push(res.value);
|
|
1131
1294
|
candidates.push({
|
|
1132
1295
|
provider: id,
|
|
@@ -1157,11 +1320,11 @@ export class AudrenSwapRouter {
|
|
|
1157
1320
|
const adapter = this.adapters.get(providerId);
|
|
1158
1321
|
if (!adapter)
|
|
1159
1322
|
throw new Error(`Unknown swap aggregator "${providerId}"`);
|
|
1160
|
-
if (!this.isEnabled(
|
|
1161
|
-
throw new Error(`Swap aggregator "${
|
|
1323
|
+
if (!this.isEnabled(providerId)) {
|
|
1324
|
+
throw new Error(`Swap aggregator "${providerId}" is disabled by router configuration`);
|
|
1162
1325
|
}
|
|
1163
1326
|
if (!adapter.isConfigured()) {
|
|
1164
|
-
throw new Error(`Swap aggregator "${
|
|
1327
|
+
throw new Error(`Swap aggregator "${providerId}" is not configured`);
|
|
1165
1328
|
}
|
|
1166
1329
|
const built = await adapter.swapInstructions({
|
|
1167
1330
|
quoteResponse: req.quoteResponse,
|
|
@@ -1174,12 +1337,22 @@ export class AudrenSwapRouter {
|
|
|
1174
1337
|
timeoutMs: req.timeoutMs ?? this.defaultTimeoutMs,
|
|
1175
1338
|
signal: req.signal,
|
|
1176
1339
|
});
|
|
1340
|
+
if (!built.swapInstruction.accounts.some((a) => a.pubkey === req.escrowPubkey)) {
|
|
1341
|
+
throw new Error(`Aggregator "${providerId}" swapInstruction does not reference escrow PDA ${req.escrowPubkey}`);
|
|
1342
|
+
}
|
|
1343
|
+
if (built.swapInstruction.accounts.length > MAX_EXEC_ROUTER_CPI_ACCOUNTS) {
|
|
1344
|
+
throw new Error(`Aggregator "${providerId}" returned ${built.swapInstruction.accounts.length} router accounts (exceeds ExecViaEscrow max ${MAX_EXEC_ROUTER_CPI_ACCOUNTS})`);
|
|
1345
|
+
}
|
|
1346
|
+
const uniquePubkeys = new Set(built.swapInstruction.accounts.map((a) => a.pubkey)).size;
|
|
1347
|
+
if (uniquePubkeys > MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS) {
|
|
1348
|
+
throw new Error(`Aggregator "${providerId}" returned ${uniquePubkeys} unique router accounts (exceeds Tx v1 safe budget ${MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS})`);
|
|
1349
|
+
}
|
|
1177
1350
|
const allowUnverified = req.allowUnverifiedRouter ?? this.allowUnverifiedRouter;
|
|
1178
1351
|
if (!allowUnverified) {
|
|
1179
1352
|
const allowed = req.allowedRouterPrograms ?? this.allowedRouterPrograms;
|
|
1180
1353
|
const routerProg = built.swapInstruction.programId;
|
|
1181
1354
|
if (!allowed.includes(routerProg)) {
|
|
1182
|
-
throw new Error(`Aggregator "${
|
|
1355
|
+
throw new Error(`Aggregator "${providerId}" returned unapproved swap router program ${routerProg}`);
|
|
1183
1356
|
}
|
|
1184
1357
|
}
|
|
1185
1358
|
return built;
|
package/dist/relayer.js
CHANGED
|
@@ -15,8 +15,9 @@ export const AUDREN_DEFAULT_RELAY_TIMEOUT_MS = 45_000;
|
|
|
15
15
|
export const AUDREN_AUDITED_SWAP_ROUTERS = [
|
|
16
16
|
'JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4', // Jupiter Swap v1
|
|
17
17
|
'DF1ow4tspfHX9JwWJsAb9epbkA8hmpSEAtxXy1V27QBH', // DFlow Trading API
|
|
18
|
-
'6m2CDdhRgxpH4WjvdzxAYbGxwdGUz5MziiL5jek2kBma', // OKX DEX
|
|
18
|
+
'6m2CDdhRgxpH4WjvdzxAYbGxwdGUz5MziiL5jek2kBma', // OKX DEX Router (v1)
|
|
19
19
|
'T1TANpTeScyeqVzzgNViGDNrkQ6qHz9KrSBS4aNXvGT', // Titan Meta-Aggregator
|
|
20
|
+
'proVF4pMXVaYqmy4NjniPh4pqKNfMmsihgd4wdkCX3u', // OKX DEX Aggregation Router V2/V6
|
|
20
21
|
];
|
|
21
22
|
export class AudrenRelayError extends Error {
|
|
22
23
|
status;
|
|
@@ -108,8 +109,16 @@ export class AudrenRelayClient {
|
|
|
108
109
|
res = await fetchFn(`${this.baseUrl}${path}`, {
|
|
109
110
|
...init,
|
|
110
111
|
...(headers ? { headers } : {}),
|
|
112
|
+
redirect: 'manual',
|
|
111
113
|
signal: controller.signal,
|
|
112
114
|
});
|
|
115
|
+
if (res.status >= 300 && res.status < 400) {
|
|
116
|
+
await res.body?.cancel?.().catch(() => { });
|
|
117
|
+
throw new AudrenRelayError(`Relay returned unexpected HTTP ${res.status} redirect`, {
|
|
118
|
+
status: res.status,
|
|
119
|
+
code: 'UNEXPECTED_REDIRECT',
|
|
120
|
+
});
|
|
121
|
+
}
|
|
113
122
|
text = await res.text();
|
|
114
123
|
}
|
|
115
124
|
finally {
|
package/dist/swap.js
CHANGED
|
@@ -32,7 +32,24 @@ export const JUPITER_CPI_EXCLUDED_DEXES = [
|
|
|
32
32
|
* or a custom `allowedRouterPrograms` list is provided.
|
|
33
33
|
*/
|
|
34
34
|
export async function fetchAggregatorPrivateSwapRoute(aggregatorBaseUrl, quoteParams, escrowAddress, options) {
|
|
35
|
-
const
|
|
35
|
+
const trimmed = aggregatorBaseUrl.trim();
|
|
36
|
+
if (!trimmed || /[?#@]/.test(trimmed)) {
|
|
37
|
+
throw new Error('aggregatorBaseUrl must not contain credentials, query, or hash');
|
|
38
|
+
}
|
|
39
|
+
let parsedUrl;
|
|
40
|
+
try {
|
|
41
|
+
parsedUrl = new URL(trimmed);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new Error('aggregatorBaseUrl is not a valid URL');
|
|
45
|
+
}
|
|
46
|
+
const isHttps = parsedUrl.protocol === 'https:';
|
|
47
|
+
const isLoopbackHttp = parsedUrl.protocol === 'http:' &&
|
|
48
|
+
(parsedUrl.hostname === 'localhost' || parsedUrl.hostname === '127.0.0.1');
|
|
49
|
+
if (!isHttps && !isLoopbackHttp) {
|
|
50
|
+
throw new Error('aggregatorBaseUrl must use https:// (or http://localhost for local dev)');
|
|
51
|
+
}
|
|
52
|
+
const base = `${parsedUrl.origin}${parsedUrl.pathname.replace(/\/+$/, '')}`;
|
|
36
53
|
const excluded = quoteParams.excludeDexes ?? JUPITER_CPI_EXCLUDED_DEXES;
|
|
37
54
|
const timeoutMs = options?.timeoutMs ?? 30_000;
|
|
38
55
|
const makeSignal = () => {
|
|
@@ -57,6 +74,7 @@ export async function fetchAggregatorPrivateSwapRoute(aggregatorBaseUrl, quotePa
|
|
|
57
74
|
redirect: 'manual',
|
|
58
75
|
});
|
|
59
76
|
if (quoteRes.status >= 300 && quoteRes.status < 400) {
|
|
77
|
+
await quoteRes.body?.cancel?.().catch(() => { });
|
|
60
78
|
throw new Error(`Aggregator /quote returned unexpected HTTP ${quoteRes.status} redirect`);
|
|
61
79
|
}
|
|
62
80
|
if (!quoteRes.ok) {
|
|
@@ -78,16 +96,43 @@ export async function fetchAggregatorPrivateSwapRoute(aggregatorBaseUrl, quotePa
|
|
|
78
96
|
}),
|
|
79
97
|
});
|
|
80
98
|
if (swapRes.status >= 300 && swapRes.status < 400) {
|
|
99
|
+
await swapRes.body?.cancel?.().catch(() => { });
|
|
81
100
|
throw new Error(`Aggregator /swap-instructions returned unexpected HTTP ${swapRes.status} redirect`);
|
|
82
101
|
}
|
|
83
102
|
if (!swapRes.ok) {
|
|
84
103
|
throw new Error(`Aggregator /swap-instructions failed: HTTP ${swapRes.status}`);
|
|
85
104
|
}
|
|
86
105
|
const swap = (await swapRes.json());
|
|
106
|
+
const ix = swap?.swapInstruction;
|
|
107
|
+
if (!ix ||
|
|
108
|
+
typeof ix !== 'object' ||
|
|
109
|
+
typeof ix.programId !== 'string' ||
|
|
110
|
+
ix.programId.length === 0 ||
|
|
111
|
+
typeof ix.data !== 'string' ||
|
|
112
|
+
ix.data.length === 0 ||
|
|
113
|
+
!Array.isArray(ix.accounts) ||
|
|
114
|
+
!ix.accounts.every((a) => Boolean(a) &&
|
|
115
|
+
typeof a === 'object' &&
|
|
116
|
+
typeof a.pubkey === 'string' &&
|
|
117
|
+
a.pubkey.length > 0 &&
|
|
118
|
+
typeof a.isSigner === 'boolean' &&
|
|
119
|
+
typeof a.isWritable === 'boolean')) {
|
|
120
|
+
throw new Error('Aggregator /swap-instructions returned an invalid swapInstruction');
|
|
121
|
+
}
|
|
122
|
+
if (ix.accounts.length > 64) {
|
|
123
|
+
throw new Error(`Aggregator returned ${ix.accounts.length} router accounts (exceeds ExecViaEscrow max 64)`);
|
|
124
|
+
}
|
|
125
|
+
const uniquePubkeys = new Set(ix.accounts.map((a) => a.pubkey)).size;
|
|
126
|
+
if (uniquePubkeys > 46) {
|
|
127
|
+
throw new Error(`Aggregator returned ${uniquePubkeys} unique router accounts (exceeds Tx v1 safe budget 46)`);
|
|
128
|
+
}
|
|
129
|
+
if (!ix.accounts.some((a) => a.pubkey === escrowAddress)) {
|
|
130
|
+
throw new Error(`Aggregator swapInstruction does not reference escrow PDA ${escrowAddress}`);
|
|
131
|
+
}
|
|
87
132
|
if (!options?.allowUnverifiedRouter) {
|
|
88
133
|
const allowed = options?.allowedRouterPrograms ?? AUDREN_AUDITED_SWAP_ROUTERS;
|
|
89
|
-
const routerProg =
|
|
90
|
-
if (
|
|
134
|
+
const routerProg = ix.programId;
|
|
135
|
+
if (!allowed.includes(routerProg)) {
|
|
91
136
|
throw new Error(`Aggregator returned unapproved swap router program: ${String(routerProg)}`);
|
|
92
137
|
}
|
|
93
138
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@audren-xyz/sdk",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "TypeScript SDK for Audren — zero-indexer BN254 Groth16 global MASP core (PDAs, Poseidon, layouts, CompactWalletStore, gateway/relayer client, tx v1) plus WASM Groth16 prover (@audren-xyz/sdk/prover) and IDLs (@audren-xyz/sdk/idl)",
|