@audren-xyz/sdk 1.3.3 → 1.3.5

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.
@@ -274,9 +274,12 @@ export declare class AudrenSwapRouter {
274
274
  /** Register or override a custom aggregator adapter at runtime. */
275
275
  register(adapter: SwapAggregatorAdapter): this;
276
276
  getAdapter(id: string): SwapAggregatorAdapter | undefined;
277
+ getAllowedRouterPrograms(): readonly string[];
277
278
  private isEnabled;
278
279
  listProviders(): SwapProviderStatus[];
279
280
  private resolveActiveAdapters;
281
+ private checkFeeAccountForAdapter;
282
+ private checkPrebuiltRouterAllowlist;
280
283
  quote(req: AudrenSwapQuoteRequest): Promise<AudrenSwapQuoteResult>;
281
284
  buildSwapInstructions(req: AudrenBuildSwapInstructionsRequest): Promise<NormalizedSwapInstructions>;
282
285
  /**
@@ -67,8 +67,18 @@ export function findExcludedCpiVenue(quote, excludedDexes = JUPITER_CPI_EXCLUDED
67
67
  }
68
68
  return null;
69
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
+ }
70
77
  function validateAggregatorBaseUrl(raw, providerLabel) {
71
- const trimmed = raw.trim().replace(/\/+$/, '');
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
+ }
72
82
  let parsed;
73
83
  try {
74
84
  parsed = new URL(trimmed);
@@ -85,7 +95,7 @@ function validateAggregatorBaseUrl(raw, providerLabel) {
85
95
  if (!isHttps && !isLoopbackHttp) {
86
96
  throw new Error(`${providerLabel} base URL must use https:// (or http://localhost for local dev)`);
87
97
  }
88
- return trimmed;
98
+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;
89
99
  }
90
100
  function buildFetchSignal(signal, timeoutMs = 10_000) {
91
101
  if (signal)
@@ -102,6 +112,7 @@ async function safeAggregatorFetch(fetchImpl, url, init, providerLabel) {
102
112
  redirect: 'manual',
103
113
  });
104
114
  if (res.status >= 300 && res.status < 400) {
115
+ await res.body?.cancel?.().catch(() => { });
105
116
  throw new Error(`${providerLabel} returned unexpected HTTP ${res.status} redirect`);
106
117
  }
107
118
  return res;
@@ -114,15 +125,30 @@ function bytesToBase64(bytes) {
114
125
  return btoa(bin);
115
126
  }
116
127
  function parsePositiveUintString(v) {
117
- const s = String(v ?? '').trim();
118
- if (!/^\d+$/.test(s))
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)
119
139
  return null;
120
- const bi = BigInt(s);
121
- return bi > 0n ? bi : null;
140
+ const bi = BigInt(v);
141
+ return bi > 0n && bi <= U64_MAX ? bi : null;
122
142
  }
123
143
  function validateQuoteParams(req) {
124
- if (parsePositiveUintString(req.amount) === null) {
125
- throw new RangeError('amount must be a positive base-10 integer string');
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');
126
152
  }
127
153
  if (!Number.isInteger(req.slippageBps) || req.slippageBps < 0 || req.slippageBps >= 10_000) {
128
154
  throw new RangeError('slippageBps must be an integer between 0 and 9999');
@@ -152,9 +178,12 @@ function isValidRouterInstruction(v) {
152
178
  typeof a.isWritable === 'boolean');
153
179
  }
154
180
  function validatePrebuiltEscrowInstructionBounds(ixs, escrowPubkey, providerLabel) {
155
- const swapIx = ixs.find((ix) => !WRAPPER_PROGRAMS.has(ix.programId) &&
156
- ix.accounts.some((a) => a.pubkey === escrowPubkey));
157
- if (!swapIx) {
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)) {
158
187
  throw new Error(`${providerLabel} did not include an escrow-signed swap instruction`);
159
188
  }
160
189
  if (swapIx.accounts.length > MAX_EXEC_ROUTER_CPI_ACCOUNTS) {
@@ -164,9 +193,34 @@ function validatePrebuiltEscrowInstructionBounds(ixs, escrowPubkey, providerLabe
164
193
  if (uniquePubkeys > MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS) {
165
194
  throw new Error(`${providerLabel} route requires ${uniquePubkeys} unique router accounts (exceeds Tx v1 safe budget ${MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS})`);
166
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
+ });
167
221
  }
168
222
  export function createJupiterSwapAdapter(config = {}) {
169
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
223
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
170
224
  const apiKey = config.apiKey?.trim() ?? '';
171
225
  const rawUrl = config.apiUrl?.trim() ?? '';
172
226
  const resolveBase = () => {
@@ -194,11 +248,12 @@ export function createJupiterSwapAdapter(config = {}) {
194
248
  return res;
195
249
  lastRes = res;
196
250
  if (attempt < retryDelays.length) {
251
+ await res.body?.cancel?.().catch(() => { });
197
252
  const retryAfter = Number(res.headers.get('retry-after') ?? '');
198
253
  const delayMs = Number.isFinite(retryAfter) && retryAfter > 0
199
254
  ? Math.min(Math.max(retryAfter * 1000, 250), 1_500)
200
255
  : retryDelays[attempt];
201
- await new Promise((r) => setTimeout(r, delayMs));
256
+ await sleepAbortable(delayMs, init.signal);
202
257
  }
203
258
  }
204
259
  return lastRes;
@@ -240,23 +295,27 @@ export function createJupiterSwapAdapter(config = {}) {
240
295
  signal: req.signal,
241
296
  timeoutMs: req.timeoutMs,
242
297
  });
243
- if (!res.ok)
244
- throw new Error(`Jupiter quote HTTP ${res.status}`);
245
- return (await res.json());
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 };
246
306
  };
247
- let raw;
248
307
  const wantDirect = req.onlyDirectRoutes ?? true;
249
- try {
250
- raw = await doFetch(wantDirect);
251
- }
252
- catch (err) {
253
- if (wantDirect && req.onlyDirectRoutes === undefined) {
254
- raw = await doFetch(false);
255
- }
256
- else {
257
- throw err;
258
- }
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);
259
315
  }
316
+ if (!first.ok)
317
+ throw new Error(`Jupiter quote HTTP ${first.status}`);
318
+ const raw = first.data;
260
319
  const outBi = parsePositiveUintString(raw.outAmount);
261
320
  if (outBi === null)
262
321
  throw new Error('Jupiter returned invalid or zero outAmount');
@@ -316,7 +375,10 @@ export function createJupiterSwapAdapter(config = {}) {
316
375
  });
317
376
  if (!res.ok)
318
377
  throw new Error(`Jupiter swap-instructions HTTP ${res.status}`);
319
- const payload = (await res.json());
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;
320
382
  if (!isValidRouterInstruction(payload.swapInstruction)) {
321
383
  throw new Error('Jupiter did not return a valid swapInstruction');
322
384
  }
@@ -338,7 +400,7 @@ export function createJupiterSwapAdapter(config = {}) {
338
400
  };
339
401
  }
340
402
  export function createDFlowSwapAdapter(config = {}) {
341
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
403
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
342
404
  const apiKey = config.apiKey?.trim() ?? '';
343
405
  const rawUrl = config.apiUrl?.trim() ?? '';
344
406
  const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://quote-api.dflow.net', 'DFlow');
@@ -367,12 +429,14 @@ export function createDFlowSwapAdapter(config = {}) {
367
429
  }
368
430
  const base = resolveBase();
369
431
  const t0 = Date.now();
432
+ const excluded = req.excludeDexes ?? JUPITER_CPI_EXCLUDED_DEXES;
370
433
  const qs = new URLSearchParams({
371
434
  inputMint: req.inputMint,
372
435
  outputMint: req.outputMint,
373
436
  amount: req.amount,
374
437
  slippageBps: String(req.slippageBps),
375
438
  transactionVersion: 'v1',
439
+ ...(excluded.length > 0 ? { excludeDexes: excluded.join(',') } : {}),
376
440
  ...(req.onlyDirectRoutes ? { onlyDirectRoutes: 'true' } : {}),
377
441
  ...(req.platformFeeBps && req.platformFeeBps > 0
378
442
  ? { platformFeeBps: String(req.platformFeeBps) }
@@ -384,7 +448,10 @@ export function createDFlowSwapAdapter(config = {}) {
384
448
  }, 'DFlow');
385
449
  if (!res.ok)
386
450
  throw new Error(`DFlow quote HTTP ${res.status}`);
387
- const raw = (await res.json());
451
+ const rawJson = await res.json();
452
+ if (!isPlainObject(rawJson))
453
+ throw new Error('DFlow returned non-object quote JSON');
454
+ const raw = rawJson;
388
455
  const outBi = parsePositiveUintString(raw.outAmount);
389
456
  if (outBi === null)
390
457
  throw new Error('DFlow returned invalid or zero outAmount');
@@ -450,7 +517,10 @@ export function createDFlowSwapAdapter(config = {}) {
450
517
  }, 'DFlow');
451
518
  if (!res.ok)
452
519
  throw new Error(`DFlow swap-instructions HTTP ${res.status}`);
453
- const payload = (await res.json());
520
+ const payloadRaw = await res.json();
521
+ if (!isPlainObject(payloadRaw))
522
+ throw new Error('DFlow returned non-object swap-instructions JSON');
523
+ const payload = payloadRaw;
454
524
  if (!isValidRouterInstruction(payload.swapInstruction)) {
455
525
  throw new Error('DFlow did not return a valid swapInstruction');
456
526
  }
@@ -477,7 +547,7 @@ export function createDFlowSwapAdapter(config = {}) {
477
547
  const OKX_CHAIN_INDEX = '501';
478
548
  const OKX_SWAP_IX_PATH = '/api/v6/dex/aggregator/swap-instruction';
479
549
  export function createOkxSwapAdapter(config = {}) {
480
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
550
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
481
551
  const apiKey = config.apiKey?.trim() ?? '';
482
552
  const secretKey = config.secretKey?.trim() ?? '';
483
553
  const passphrase = config.passphrase?.trim() ?? '';
@@ -520,40 +590,63 @@ export function createOkxSwapAdapter(config = {}) {
520
590
  }
521
591
  const base = resolveBase();
522
592
  const t0 = Date.now();
523
- const qs = new URLSearchParams({
524
- chainIndex: OKX_CHAIN_INDEX,
525
- amount: req.amount,
526
- fromTokenAddress: req.inputMint,
527
- toTokenAddress: req.outputMint,
528
- slippagePercent: (req.slippageBps / 100).toString(),
529
- userWalletAddress: req.escrowPubkey,
530
- swapMode: 'exactIn',
531
- ...(req.platformFeeBps && req.platformFeeBps > 0 && req.feeOwnerWallet
532
- ? {
533
- feePercent: (req.platformFeeBps / 100).toFixed(4).replace(/\.?0+$/, ''),
534
- toTokenReferrerWalletAddress: req.feeOwnerWallet,
535
- }
536
- : {}),
537
- });
538
- const queryString = `?${qs.toString()}`;
539
- const headers = await signHeaders('GET', OKX_SWAP_IX_PATH, queryString);
540
- const res = await safeAggregatorFetch(fetchImpl, `${base}${OKX_SWAP_IX_PATH}${queryString}`, {
541
- headers,
542
- signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
543
- }, 'OKX');
544
- if (!res.ok)
545
- throw new Error(`OKX swap-instruction HTTP ${res.status}`);
546
- const body = (await res.json());
547
- const entry = Array.isArray(body.data) ? body.data[0] : body.data;
548
- const outBi = parsePositiveUintString(entry?.routerResult?.toTokenAmount);
549
- if (body.code !== '0' || !entry?.routerResult || outBi === null) {
550
- throw new Error(`OKX API returned no valid route${body.msg ? `: ${body.msg}` : ''}`);
593
+ const escrowPubkey = req.escrowPubkey;
594
+ const fetchOkxCandidate = async (directRoute) => {
595
+ const qs = new URLSearchParams({
596
+ chainIndex: OKX_CHAIN_INDEX,
597
+ amount: req.amount,
598
+ fromTokenAddress: req.inputMint,
599
+ toTokenAddress: req.outputMint,
600
+ slippagePercent: (req.slippageBps / 100).toString(),
601
+ userWalletAddress: escrowPubkey,
602
+ swapMode: 'exactIn',
603
+ ...(directRoute ? { directRoute: 'true' } : {}),
604
+ ...(req.platformFeeBps && req.platformFeeBps > 0 && req.feeOwnerWallet
605
+ ? {
606
+ feePercent: (req.platformFeeBps / 100).toFixed(4).replace(/\.?0+$/, ''),
607
+ toTokenReferrerWalletAddress: req.feeOwnerWallet,
608
+ }
609
+ : {}),
610
+ });
611
+ const queryString = `?${qs.toString()}`;
612
+ const headers = await signHeaders('GET', OKX_SWAP_IX_PATH, queryString);
613
+ const res = await safeAggregatorFetch(fetchImpl, `${base}${OKX_SWAP_IX_PATH}${queryString}`, {
614
+ headers,
615
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
616
+ }, 'OKX');
617
+ if (!res.ok)
618
+ throw new Error(`OKX swap-instruction HTTP ${res.status}`);
619
+ const bodyRaw = await res.json();
620
+ if (!isPlainObject(bodyRaw))
621
+ throw new Error('OKX returned non-object response JSON');
622
+ const body = bodyRaw;
623
+ const entry = Array.isArray(body.data) ? body.data[0] : body.data;
624
+ const outBi = parsePositiveUintString(entry?.routerResult?.toTokenAmount);
625
+ if (body.code !== '0' || !entry?.routerResult || outBi === null) {
626
+ const safeCode = typeof body.code === 'string' && body.code.trim() ? body.code.trim().slice(0, 16) : 'unknown';
627
+ throw new Error(`OKX API returned no valid route (code ${safeCode})`);
628
+ }
629
+ const prebuiltIxs = Array.isArray(entry.instructionLists)
630
+ ? entry.instructionLists.filter(isValidRouterInstruction)
631
+ : [];
632
+ const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, escrowPubkey, 'OKX');
633
+ return { entry, rr: entry.routerResult, outBi, swapIx };
634
+ };
635
+ let candidate;
636
+ try {
637
+ candidate = await fetchOkxCandidate(Boolean(req.onlyDirectRoutes));
551
638
  }
552
- const rr = entry.routerResult;
553
- const prebuiltIxs = Array.isArray(entry.instructionLists)
554
- ? entry.instructionLists.filter(isValidRouterInstruction)
555
- : [];
556
- validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'OKX');
639
+ catch (err) {
640
+ const msg = err instanceof Error ? err.message : String(err);
641
+ const isBoundsRejection = /exceeds ExecViaEscrow max|exceeds Solana Tx v1|non-wrapper swap instruction/i.test(msg);
642
+ if (!req.onlyDirectRoutes && isBoundsRejection && !req.signal?.aborted) {
643
+ candidate = await fetchOkxCandidate(true);
644
+ }
645
+ else {
646
+ throw err;
647
+ }
648
+ }
649
+ const { entry, rr, outBi, swapIx } = candidate;
557
650
  const outAmount = outBi.toString();
558
651
  const minOut = ((outBi * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
559
652
  const routePlan = [];
@@ -619,6 +712,7 @@ export function createOkxSwapAdapter(config = {}) {
619
712
  percent: 100,
620
713
  });
621
714
  }
715
+ const feeApplied = Boolean(req.platformFeeBps && req.platformFeeBps > 0 && req.feeOwnerWallet);
622
716
  return {
623
717
  provider: 'okx',
624
718
  inputMint: req.inputMint,
@@ -628,7 +722,7 @@ export function createOkxSwapAdapter(config = {}) {
628
722
  otherAmountThreshold: minOut,
629
723
  slippageBps: req.slippageBps,
630
724
  priceImpactPct: rr.priceImpactPercentage ?? null,
631
- platformFee: req.platformFeeBps && req.platformFeeBps > 0
725
+ platformFee: feeApplied
632
726
  ? {
633
727
  amount: ((outBi * BigInt(req.platformFeeBps)) / 10000n).toString(),
634
728
  feeBps: req.platformFeeBps,
@@ -640,9 +734,10 @@ export function createOkxSwapAdapter(config = {}) {
640
734
  latencyMs: Date.now() - t0,
641
735
  rawQuote: {
642
736
  escrowPubkey: req.escrowPubkey,
737
+ routerProgramId: swapIx.programId,
643
738
  instructionLists: entry.instructionLists ?? [],
644
739
  addressLookupTableAccount: entry.addressLookupTableAccount ?? [],
645
- platformFee: req.platformFeeBps && req.platformFeeBps > 0 ? { feeBps: req.platformFeeBps } : null,
740
+ platformFee: feeApplied ? { feeBps: req.platformFeeBps } : null,
646
741
  },
647
742
  };
648
743
  },
@@ -658,11 +753,7 @@ export function createOkxSwapAdapter(config = {}) {
658
753
  throw new Error('OKX quoteResponse missing instructionLists array');
659
754
  }
660
755
  const ixs = raw.instructionLists.filter(isValidRouterInstruction);
661
- const swapIx = ixs.find((ix) => !WRAPPER_PROGRAMS.has(ix.programId) &&
662
- ix.accounts.some((a) => a.pubkey === req.escrowPubkey));
663
- if (!swapIx) {
664
- throw new Error('OKX response did not include an escrow-signed swap instruction');
665
- }
756
+ const swapIx = validatePrebuiltEscrowInstructionBounds(ixs, req.escrowPubkey, 'OKX');
666
757
  return {
667
758
  provider: 'okx',
668
759
  swapInstruction: swapIx,
@@ -670,7 +761,7 @@ export function createOkxSwapAdapter(config = {}) {
670
761
  ? raw.addressLookupTableAccount.filter((x) => typeof x === 'string')
671
762
  : [],
672
763
  computeUnitLimit: computeAggregatorExecCuLimit({ forceMultiHopHeadroom: true }),
673
- feeAccount: req.feeOwnerWallet ?? req.feeAccountAta ?? null,
764
+ feeAccount: req.feeOwnerWallet ?? null,
674
765
  };
675
766
  },
676
767
  };
@@ -706,7 +797,7 @@ function normalizeTitanInstruction(ix) {
706
797
  return { programId, data, accounts };
707
798
  }
708
799
  export function createTitanSwapAdapter(config = {}) {
709
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
800
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
710
801
  const apiKey = config.apiKey?.trim() ?? '';
711
802
  const rawUrl = config.apiUrl?.trim() ?? '';
712
803
  const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://api.titan.exchange/api/v1', 'Titan');
@@ -753,7 +844,10 @@ export function createTitanSwapAdapter(config = {}) {
753
844
  }, 'Titan');
754
845
  if (!res.ok)
755
846
  throw new Error(`Titan quote HTTP ${res.status}`);
756
- const decoded = (await res.json());
847
+ const decodedRaw = await res.json();
848
+ if (!isPlainObject(decodedRaw))
849
+ throw new Error('Titan returned non-object quote JSON');
850
+ const decoded = decodedRaw;
757
851
  const quotesMap = decoded.quotes && typeof decoded.quotes === 'object' && !Array.isArray(decoded.quotes)
758
852
  ? decoded.quotes
759
853
  : {};
@@ -785,12 +879,12 @@ export function createTitanSwapAdapter(config = {}) {
785
879
  if (!route || routeOut === null) {
786
880
  throw new Error('Titan returned no valid quotes');
787
881
  }
788
- if (Array.isArray(route.instructions)) {
789
- const prebuiltIxs = route.instructions
882
+ const prebuiltIxs = Array.isArray(route.instructions)
883
+ ? route.instructions
790
884
  .map(normalizeTitanInstruction)
791
- .filter((x) => x !== null);
792
- validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'Titan');
793
- }
885
+ .filter((x) => x !== null)
886
+ : [];
887
+ const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'Titan');
794
888
  const outAmount = routeOut.toString();
795
889
  const minOut = ((routeOut * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
796
890
  const steps = Array.isArray(route.steps)
@@ -822,6 +916,7 @@ export function createTitanSwapAdapter(config = {}) {
822
916
  percent: 100,
823
917
  },
824
918
  ];
919
+ const feeApplied = Boolean(req.platformFeeBps && req.platformFeeBps > 0 && req.feeAccountAta);
825
920
  return {
826
921
  provider: 'titan',
827
922
  inputMint: decoded.inputMint ?? req.inputMint,
@@ -830,7 +925,7 @@ export function createTitanSwapAdapter(config = {}) {
830
925
  outAmount,
831
926
  otherAmountThreshold: minOut,
832
927
  slippageBps: route.slippageBps ?? req.slippageBps,
833
- platformFee: req.platformFeeBps && req.platformFeeBps > 0
928
+ platformFee: feeApplied
834
929
  ? {
835
930
  amount: ((routeOut * BigInt(req.platformFeeBps)) / 10000n).toString(),
836
931
  feeBps: req.platformFeeBps,
@@ -843,8 +938,9 @@ export function createTitanSwapAdapter(config = {}) {
843
938
  rawQuote: {
844
939
  winner: winnerKey,
845
940
  escrowPubkey: req.escrowPubkey,
941
+ routerProgramId: swapIx.programId,
846
942
  route,
847
- platformFee: req.platformFeeBps && req.platformFeeBps > 0 ? { feeBps: req.platformFeeBps } : null,
943
+ platformFee: feeApplied ? { feeBps: req.platformFeeBps } : null,
848
944
  },
849
945
  };
850
946
  },
@@ -862,11 +958,7 @@ export function createTitanSwapAdapter(config = {}) {
862
958
  const ixs = raw.route.instructions
863
959
  .map(normalizeTitanInstruction)
864
960
  .filter((x) => x !== null);
865
- const swapIx = ixs.find((ix) => !WRAPPER_PROGRAMS.has(ix.programId) &&
866
- ix.accounts.some((a) => a.pubkey === req.escrowPubkey));
867
- if (!swapIx) {
868
- throw new Error('Titan route did not expose a single escrow-signed swapInstruction');
869
- }
961
+ const swapIx = validatePrebuiltEscrowInstructionBounds(ixs, req.escrowPubkey, 'Titan');
870
962
  const routeHopCount = Array.isArray(raw.route.steps) && raw.route.steps.length > 0 ? raw.route.steps.length : null;
871
963
  return {
872
964
  provider: 'titan',
@@ -884,7 +976,7 @@ export function createTitanSwapAdapter(config = {}) {
884
976
  };
885
977
  }
886
978
  export function createBedrockSwapAdapter(config = {}) {
887
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
979
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
888
980
  const apiKey = config.apiKey?.trim() ?? '';
889
981
  const rawUrl = config.apiUrl?.trim() ?? '';
890
982
  const resolveBase = () => {
@@ -934,7 +1026,10 @@ export function createBedrockSwapAdapter(config = {}) {
934
1026
  }, 'Bedrock');
935
1027
  if (!res.ok)
936
1028
  throw new Error(`Bedrock quote HTTP ${res.status}`);
937
- const raw = (await res.json());
1029
+ const rawJson = await res.json();
1030
+ if (!isPlainObject(rawJson))
1031
+ throw new Error('Bedrock returned non-object quote JSON');
1032
+ const raw = rawJson;
938
1033
  const outBi = parsePositiveUintString(raw.outAmount);
939
1034
  if (outBi === null)
940
1035
  throw new Error('Bedrock returned invalid or zero outAmount');
@@ -956,6 +1051,7 @@ export function createBedrockSwapAdapter(config = {}) {
956
1051
  };
957
1052
  });
958
1053
  const feeObj = raw.fee ?? raw.platformFee;
1054
+ const parsedSlippage = Number(raw.slippageBps);
959
1055
  return {
960
1056
  provider: 'bedrock',
961
1057
  inputMint: raw.inputMint ?? req.inputMint,
@@ -963,7 +1059,7 @@ export function createBedrockSwapAdapter(config = {}) {
963
1059
  inAmount: raw.inAmount ?? req.amount,
964
1060
  outAmount: outBi.toString(),
965
1061
  otherAmountThreshold: raw.otherAmountThreshold ?? outBi.toString(),
966
- slippageBps: Number(raw.slippageBps ?? req.slippageBps),
1062
+ slippageBps: Number.isFinite(parsedSlippage) && parsedSlippage >= 0 ? parsedSlippage : req.slippageBps,
967
1063
  priceImpactPct: raw.priceImpactPct ?? null,
968
1064
  platformFee: feeObj?.amount
969
1065
  ? {
@@ -994,7 +1090,10 @@ export function createBedrockSwapAdapter(config = {}) {
994
1090
  }, 'Bedrock');
995
1091
  if (!res.ok)
996
1092
  throw new Error(`Bedrock swap-instructions HTTP ${res.status}`);
997
- const payload = (await res.json());
1093
+ const payloadRaw = await res.json();
1094
+ if (!isPlainObject(payloadRaw))
1095
+ throw new Error('Bedrock returned non-object swap-instructions JSON');
1096
+ const payload = payloadRaw;
998
1097
  if (!isValidRouterInstruction(payload.swapInstruction)) {
999
1098
  throw new Error('Bedrock did not return a valid swapInstruction');
1000
1099
  }
@@ -1010,7 +1109,7 @@ export function createBedrockSwapAdapter(config = {}) {
1010
1109
  reportedRouterCu: payload.transactionConfig?.computeUnitLimit,
1011
1110
  routeHopCount,
1012
1111
  }),
1013
- feeAccount: req.feeOwnerWallet ?? req.feeAccountAta ?? null,
1112
+ feeAccount: req.feeOwnerWallet ?? null,
1014
1113
  };
1015
1114
  },
1016
1115
  };
@@ -1032,15 +1131,15 @@ export class AudrenSwapRouter {
1032
1131
  createBedrockSwapAdapter({ ...config.bedrock, fetchImpl: config.bedrock?.fetchImpl ?? sharedFetch }),
1033
1132
  ];
1034
1133
  for (const adapter of builtins) {
1035
- this.adapters.set(adapter.id, adapter);
1134
+ this.register(adapter);
1036
1135
  }
1037
1136
  for (const custom of config.customAdapters ?? []) {
1038
- this.adapters.set(custom.id, custom);
1137
+ this.register(custom);
1039
1138
  }
1040
1139
  this.enabledProviders = config.enabledProviders
1041
1140
  ? new Set(config.enabledProviders.map((s) => s.trim().toLowerCase()).filter(Boolean))
1042
1141
  : null;
1043
- this.defaultProvider = config.defaultProvider ?? 'auto';
1142
+ this.defaultProvider = (config.defaultProvider ?? 'auto').trim().toLowerCase();
1044
1143
  this.defaultTimeoutMs = config.timeoutMs ?? 10_000;
1045
1144
  this.allowedRouterPrograms = config.allowedRouterPrograms ?? AUDREN_AUDITED_SWAP_ROUTERS;
1046
1145
  this.allowUnverifiedRouter = config.allowUnverifiedRouter ?? false;
@@ -1081,27 +1180,59 @@ export class AudrenSwapRouter {
1081
1180
  }
1082
1181
  /** Register or override a custom aggregator adapter at runtime. */
1083
1182
  register(adapter) {
1084
- this.adapters.set(adapter.id, adapter);
1183
+ const key = adapter.id.trim().toLowerCase();
1184
+ if (!key || key === 'auto') {
1185
+ throw new RangeError(`Invalid swap aggregator id "${adapter.id}" (must be non-empty and not "auto")`);
1186
+ }
1187
+ this.adapters.set(key, adapter);
1085
1188
  return this;
1086
1189
  }
1087
1190
  getAdapter(id) {
1088
1191
  return this.adapters.get(id.trim().toLowerCase());
1089
1192
  }
1193
+ getAllowedRouterPrograms() {
1194
+ return [...this.allowedRouterPrograms];
1195
+ }
1090
1196
  isEnabled(id) {
1091
- return this.enabledProviders === null || this.enabledProviders.has(id.toLowerCase());
1197
+ return this.enabledProviders === null || this.enabledProviders.has(id.trim().toLowerCase());
1092
1198
  }
1093
1199
  listProviders() {
1094
- return Array.from(this.adapters.values()).map((a) => ({
1095
- id: a.id,
1200
+ return Array.from(this.adapters.entries()).map(([key, a]) => ({
1201
+ id: key,
1096
1202
  name: a.name,
1097
- enabled: this.isEnabled(a.id) && a.isConfigured(),
1203
+ enabled: this.isEnabled(key) && a.isConfigured(),
1098
1204
  configured: a.isConfigured(),
1099
- isDefault: a.id === this.defaultProvider,
1205
+ isDefault: key === this.defaultProvider,
1100
1206
  capabilities: a.capabilities,
1101
1207
  }));
1102
1208
  }
1103
1209
  resolveActiveAdapters() {
1104
- return Array.from(this.adapters.values()).filter((a) => this.isEnabled(a.id) && a.isConfigured());
1210
+ return Array.from(this.adapters.entries())
1211
+ .filter(([key, a]) => this.isEnabled(key) && a.isConfigured())
1212
+ .map(([key, adapter]) => ({ key, adapter }));
1213
+ }
1214
+ checkFeeAccountForAdapter(adapter, req) {
1215
+ if (!req.platformFeeBps || req.platformFeeBps <= 0)
1216
+ return null;
1217
+ if (!adapter.capabilities.supportsPlatformFeeBps) {
1218
+ return `Aggregator "${adapter.id}" does not support platformFeeBps`;
1219
+ }
1220
+ if (adapter.capabilities.feeAccountStyle === 'ata' && !req.feeAccountAta) {
1221
+ return `Aggregator "${adapter.id}" requires feeAccountAta when platformFeeBps > 0`;
1222
+ }
1223
+ if (adapter.capabilities.feeAccountStyle === 'owner_wallet' && !req.feeOwnerWallet) {
1224
+ return `Aggregator "${adapter.id}" requires feeOwnerWallet when platformFeeBps > 0`;
1225
+ }
1226
+ return null;
1227
+ }
1228
+ checkPrebuiltRouterAllowlist(quote) {
1229
+ if (this.allowUnverifiedRouter)
1230
+ return null;
1231
+ const prebuiltRouter = extractPrebuiltRouterProgramId(quote.rawQuote);
1232
+ if (prebuiltRouter && !this.allowedRouterPrograms.includes(prebuiltRouter)) {
1233
+ return `Aggregator "${quote.provider}" returned unapproved swap router program ${prebuiltRouter}`;
1234
+ }
1235
+ return null;
1105
1236
  }
1106
1237
  async quote(req) {
1107
1238
  validateQuoteParams(req);
@@ -1119,20 +1250,26 @@ export class AudrenSwapRouter {
1119
1250
  const adapter = this.adapters.get(chosen);
1120
1251
  if (!adapter)
1121
1252
  throw new Error(`Unknown swap aggregator "${chosen}"`);
1122
- if (!this.isEnabled(adapter.id)) {
1123
- throw new Error(`Swap aggregator "${adapter.id}" is disabled by router configuration`);
1253
+ if (!this.isEnabled(chosen)) {
1254
+ throw new Error(`Swap aggregator "${chosen}" is disabled by router configuration`);
1124
1255
  }
1125
1256
  if (!adapter.isConfigured()) {
1126
- throw new Error(`Swap aggregator "${adapter.id}" is not configured`);
1257
+ throw new Error(`Swap aggregator "${chosen}" is not configured`);
1127
1258
  }
1259
+ const feeErr = this.checkFeeAccountForAdapter(adapter, adapterReq);
1260
+ if (feeErr)
1261
+ throw new Error(feeErr);
1128
1262
  const quote = await adapter.quote(adapterReq);
1129
1263
  const badVenue = findExcludedCpiVenue(quote, excluded);
1130
1264
  if (badVenue) {
1131
- throw new Error(`Aggregator "${adapter.id}" routed via PDA-CPI-excluded venue "${badVenue}"`);
1265
+ throw new Error(`Aggregator "${chosen}" routed via PDA-CPI-excluded venue "${badVenue}"`);
1132
1266
  }
1267
+ const routerErr = this.checkPrebuiltRouterAllowlist(quote);
1268
+ if (routerErr)
1269
+ throw new Error(routerErr);
1133
1270
  return {
1134
1271
  winner: quote,
1135
- candidates: [{ provider: adapter.id, outAmount: quote.outAmount, latencyMs: quote.latencyMs }],
1272
+ candidates: [{ provider: chosen, outAmount: quote.outAmount, latencyMs: quote.latencyMs }],
1136
1273
  escrowPubkey,
1137
1274
  };
1138
1275
  }
@@ -1140,11 +1277,21 @@ export class AudrenSwapRouter {
1140
1277
  if (active.length === 0) {
1141
1278
  throw new Error('No swap aggregators are configured on this AudrenSwapRouter');
1142
1279
  }
1143
- const settled = await Promise.allSettled(active.map((a) => a.quote(adapterReq)));
1144
- const quotes = [];
1280
+ const eligible = [];
1145
1281
  const candidates = [];
1282
+ for (const entry of active) {
1283
+ const feeErr = this.checkFeeAccountForAdapter(entry.adapter, adapterReq);
1284
+ if (feeErr) {
1285
+ candidates.push({ provider: entry.key, error: feeErr });
1286
+ }
1287
+ else {
1288
+ eligible.push(entry);
1289
+ }
1290
+ }
1291
+ const settled = await Promise.allSettled(eligible.map((e) => e.adapter.quote(adapterReq)));
1292
+ const quotes = [];
1146
1293
  settled.forEach((res, idx) => {
1147
- const id = active[idx].id;
1294
+ const id = eligible[idx].key;
1148
1295
  if (res.status === 'fulfilled') {
1149
1296
  const badVenue = findExcludedCpiVenue(res.value, excluded);
1150
1297
  if (badVenue) {
@@ -1155,6 +1302,15 @@ export class AudrenSwapRouter {
1155
1302
  });
1156
1303
  return;
1157
1304
  }
1305
+ const routerErr = this.checkPrebuiltRouterAllowlist(res.value);
1306
+ if (routerErr) {
1307
+ candidates.push({
1308
+ provider: id,
1309
+ latencyMs: res.value.latencyMs,
1310
+ error: routerErr,
1311
+ });
1312
+ return;
1313
+ }
1158
1314
  quotes.push(res.value);
1159
1315
  candidates.push({
1160
1316
  provider: id,
@@ -1185,11 +1341,11 @@ export class AudrenSwapRouter {
1185
1341
  const adapter = this.adapters.get(providerId);
1186
1342
  if (!adapter)
1187
1343
  throw new Error(`Unknown swap aggregator "${providerId}"`);
1188
- if (!this.isEnabled(adapter.id)) {
1189
- throw new Error(`Swap aggregator "${adapter.id}" is disabled by router configuration`);
1344
+ if (!this.isEnabled(providerId)) {
1345
+ throw new Error(`Swap aggregator "${providerId}" is disabled by router configuration`);
1190
1346
  }
1191
1347
  if (!adapter.isConfigured()) {
1192
- throw new Error(`Swap aggregator "${adapter.id}" is not configured`);
1348
+ throw new Error(`Swap aggregator "${providerId}" is not configured`);
1193
1349
  }
1194
1350
  const built = await adapter.swapInstructions({
1195
1351
  quoteResponse: req.quoteResponse,
@@ -1202,15 +1358,22 @@ export class AudrenSwapRouter {
1202
1358
  timeoutMs: req.timeoutMs ?? this.defaultTimeoutMs,
1203
1359
  signal: req.signal,
1204
1360
  });
1361
+ if (!built.swapInstruction.accounts.some((a) => a.pubkey === req.escrowPubkey)) {
1362
+ throw new Error(`Aggregator "${providerId}" swapInstruction does not reference escrow PDA ${req.escrowPubkey}`);
1363
+ }
1205
1364
  if (built.swapInstruction.accounts.length > MAX_EXEC_ROUTER_CPI_ACCOUNTS) {
1206
- throw new Error(`Aggregator "${adapter.id}" returned ${built.swapInstruction.accounts.length} router accounts (exceeds ExecViaEscrow max ${MAX_EXEC_ROUTER_CPI_ACCOUNTS})`);
1365
+ throw new Error(`Aggregator "${providerId}" returned ${built.swapInstruction.accounts.length} router accounts (exceeds ExecViaEscrow max ${MAX_EXEC_ROUTER_CPI_ACCOUNTS})`);
1366
+ }
1367
+ const uniquePubkeys = new Set(built.swapInstruction.accounts.map((a) => a.pubkey)).size;
1368
+ if (uniquePubkeys > MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS) {
1369
+ throw new Error(`Aggregator "${providerId}" returned ${uniquePubkeys} unique router accounts (exceeds Tx v1 safe budget ${MAX_TX_V1_UNIQUE_ROUTER_ACCOUNTS})`);
1207
1370
  }
1208
1371
  const allowUnverified = req.allowUnverifiedRouter ?? this.allowUnverifiedRouter;
1209
1372
  if (!allowUnverified) {
1210
1373
  const allowed = req.allowedRouterPrograms ?? this.allowedRouterPrograms;
1211
1374
  const routerProg = built.swapInstruction.programId;
1212
1375
  if (!allowed.includes(routerProg)) {
1213
- throw new Error(`Aggregator "${adapter.id}" returned unapproved swap router program ${routerProg}`);
1376
+ throw new Error(`Aggregator "${providerId}" returned unapproved swap router program ${routerProg}`);
1214
1377
  }
1215
1378
  }
1216
1379
  return built;
package/dist/relayer.js CHANGED
@@ -109,8 +109,16 @@ export class AudrenRelayClient {
109
109
  res = await fetchFn(`${this.baseUrl}${path}`, {
110
110
  ...init,
111
111
  ...(headers ? { headers } : {}),
112
+ redirect: 'manual',
112
113
  signal: controller.signal,
113
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
+ }
114
122
  text = await res.text();
115
123
  }
116
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 base = aggregatorBaseUrl.replace(/\/$/, '');
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 = swap?.swapInstruction?.programId;
90
- if (typeof routerProg !== 'string' || !allowed.includes(routerProg)) {
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",
3
+ "version": "1.3.5",
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)",