@audren-xyz/sdk 1.3.3 → 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.
@@ -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')
119
137
  return null;
120
- const bi = BigInt(s);
121
- return bi > 0n ? bi : null;
138
+ if (!/^\d+$/.test(v) || v.length > 20)
139
+ return 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');
@@ -384,7 +446,10 @@ export function createDFlowSwapAdapter(config = {}) {
384
446
  }, 'DFlow');
385
447
  if (!res.ok)
386
448
  throw new Error(`DFlow quote HTTP ${res.status}`);
387
- const raw = (await res.json());
449
+ const rawJson = await res.json();
450
+ if (!isPlainObject(rawJson))
451
+ throw new Error('DFlow returned non-object quote JSON');
452
+ const raw = rawJson;
388
453
  const outBi = parsePositiveUintString(raw.outAmount);
389
454
  if (outBi === null)
390
455
  throw new Error('DFlow returned invalid or zero outAmount');
@@ -450,7 +515,10 @@ export function createDFlowSwapAdapter(config = {}) {
450
515
  }, 'DFlow');
451
516
  if (!res.ok)
452
517
  throw new Error(`DFlow swap-instructions HTTP ${res.status}`);
453
- const payload = (await res.json());
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;
454
522
  if (!isValidRouterInstruction(payload.swapInstruction)) {
455
523
  throw new Error('DFlow did not return a valid swapInstruction');
456
524
  }
@@ -477,7 +545,7 @@ export function createDFlowSwapAdapter(config = {}) {
477
545
  const OKX_CHAIN_INDEX = '501';
478
546
  const OKX_SWAP_IX_PATH = '/api/v6/dex/aggregator/swap-instruction';
479
547
  export function createOkxSwapAdapter(config = {}) {
480
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
548
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
481
549
  const apiKey = config.apiKey?.trim() ?? '';
482
550
  const secretKey = config.secretKey?.trim() ?? '';
483
551
  const passphrase = config.passphrase?.trim() ?? '';
@@ -543,17 +611,21 @@ export function createOkxSwapAdapter(config = {}) {
543
611
  }, 'OKX');
544
612
  if (!res.ok)
545
613
  throw new Error(`OKX swap-instruction HTTP ${res.status}`);
546
- const body = (await res.json());
614
+ const bodyRaw = await res.json();
615
+ if (!isPlainObject(bodyRaw))
616
+ throw new Error('OKX returned non-object response JSON');
617
+ const body = bodyRaw;
547
618
  const entry = Array.isArray(body.data) ? body.data[0] : body.data;
548
619
  const outBi = parsePositiveUintString(entry?.routerResult?.toTokenAmount);
549
620
  if (body.code !== '0' || !entry?.routerResult || outBi === null) {
550
- throw new Error(`OKX API returned no valid route${body.msg ? `: ${body.msg}` : ''}`);
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})`);
551
623
  }
552
624
  const rr = entry.routerResult;
553
625
  const prebuiltIxs = Array.isArray(entry.instructionLists)
554
626
  ? entry.instructionLists.filter(isValidRouterInstruction)
555
627
  : [];
556
- validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'OKX');
628
+ const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'OKX');
557
629
  const outAmount = outBi.toString();
558
630
  const minOut = ((outBi * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
559
631
  const routePlan = [];
@@ -619,6 +691,7 @@ export function createOkxSwapAdapter(config = {}) {
619
691
  percent: 100,
620
692
  });
621
693
  }
694
+ const feeApplied = Boolean(req.platformFeeBps && req.platformFeeBps > 0 && req.feeOwnerWallet);
622
695
  return {
623
696
  provider: 'okx',
624
697
  inputMint: req.inputMint,
@@ -628,7 +701,7 @@ export function createOkxSwapAdapter(config = {}) {
628
701
  otherAmountThreshold: minOut,
629
702
  slippageBps: req.slippageBps,
630
703
  priceImpactPct: rr.priceImpactPercentage ?? null,
631
- platformFee: req.platformFeeBps && req.platformFeeBps > 0
704
+ platformFee: feeApplied
632
705
  ? {
633
706
  amount: ((outBi * BigInt(req.platformFeeBps)) / 10000n).toString(),
634
707
  feeBps: req.platformFeeBps,
@@ -640,9 +713,10 @@ export function createOkxSwapAdapter(config = {}) {
640
713
  latencyMs: Date.now() - t0,
641
714
  rawQuote: {
642
715
  escrowPubkey: req.escrowPubkey,
716
+ routerProgramId: swapIx.programId,
643
717
  instructionLists: entry.instructionLists ?? [],
644
718
  addressLookupTableAccount: entry.addressLookupTableAccount ?? [],
645
- platformFee: req.platformFeeBps && req.platformFeeBps > 0 ? { feeBps: req.platformFeeBps } : null,
719
+ platformFee: feeApplied ? { feeBps: req.platformFeeBps } : null,
646
720
  },
647
721
  };
648
722
  },
@@ -658,11 +732,7 @@ export function createOkxSwapAdapter(config = {}) {
658
732
  throw new Error('OKX quoteResponse missing instructionLists array');
659
733
  }
660
734
  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
- }
735
+ const swapIx = validatePrebuiltEscrowInstructionBounds(ixs, req.escrowPubkey, 'OKX');
666
736
  return {
667
737
  provider: 'okx',
668
738
  swapInstruction: swapIx,
@@ -670,7 +740,7 @@ export function createOkxSwapAdapter(config = {}) {
670
740
  ? raw.addressLookupTableAccount.filter((x) => typeof x === 'string')
671
741
  : [],
672
742
  computeUnitLimit: computeAggregatorExecCuLimit({ forceMultiHopHeadroom: true }),
673
- feeAccount: req.feeOwnerWallet ?? req.feeAccountAta ?? null,
743
+ feeAccount: req.feeOwnerWallet ?? null,
674
744
  };
675
745
  },
676
746
  };
@@ -706,7 +776,7 @@ function normalizeTitanInstruction(ix) {
706
776
  return { programId, data, accounts };
707
777
  }
708
778
  export function createTitanSwapAdapter(config = {}) {
709
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
779
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
710
780
  const apiKey = config.apiKey?.trim() ?? '';
711
781
  const rawUrl = config.apiUrl?.trim() ?? '';
712
782
  const resolveBase = () => validateAggregatorBaseUrl(rawUrl || 'https://api.titan.exchange/api/v1', 'Titan');
@@ -753,7 +823,10 @@ export function createTitanSwapAdapter(config = {}) {
753
823
  }, 'Titan');
754
824
  if (!res.ok)
755
825
  throw new Error(`Titan quote HTTP ${res.status}`);
756
- const decoded = (await res.json());
826
+ const decodedRaw = await res.json();
827
+ if (!isPlainObject(decodedRaw))
828
+ throw new Error('Titan returned non-object quote JSON');
829
+ const decoded = decodedRaw;
757
830
  const quotesMap = decoded.quotes && typeof decoded.quotes === 'object' && !Array.isArray(decoded.quotes)
758
831
  ? decoded.quotes
759
832
  : {};
@@ -785,12 +858,12 @@ export function createTitanSwapAdapter(config = {}) {
785
858
  if (!route || routeOut === null) {
786
859
  throw new Error('Titan returned no valid quotes');
787
860
  }
788
- if (Array.isArray(route.instructions)) {
789
- const prebuiltIxs = route.instructions
861
+ const prebuiltIxs = Array.isArray(route.instructions)
862
+ ? route.instructions
790
863
  .map(normalizeTitanInstruction)
791
- .filter((x) => x !== null);
792
- validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'Titan');
793
- }
864
+ .filter((x) => x !== null)
865
+ : [];
866
+ const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'Titan');
794
867
  const outAmount = routeOut.toString();
795
868
  const minOut = ((routeOut * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
796
869
  const steps = Array.isArray(route.steps)
@@ -822,6 +895,7 @@ export function createTitanSwapAdapter(config = {}) {
822
895
  percent: 100,
823
896
  },
824
897
  ];
898
+ const feeApplied = Boolean(req.platformFeeBps && req.platformFeeBps > 0 && req.feeAccountAta);
825
899
  return {
826
900
  provider: 'titan',
827
901
  inputMint: decoded.inputMint ?? req.inputMint,
@@ -830,7 +904,7 @@ export function createTitanSwapAdapter(config = {}) {
830
904
  outAmount,
831
905
  otherAmountThreshold: minOut,
832
906
  slippageBps: route.slippageBps ?? req.slippageBps,
833
- platformFee: req.platformFeeBps && req.platformFeeBps > 0
907
+ platformFee: feeApplied
834
908
  ? {
835
909
  amount: ((routeOut * BigInt(req.platformFeeBps)) / 10000n).toString(),
836
910
  feeBps: req.platformFeeBps,
@@ -843,8 +917,9 @@ export function createTitanSwapAdapter(config = {}) {
843
917
  rawQuote: {
844
918
  winner: winnerKey,
845
919
  escrowPubkey: req.escrowPubkey,
920
+ routerProgramId: swapIx.programId,
846
921
  route,
847
- platformFee: req.platformFeeBps && req.platformFeeBps > 0 ? { feeBps: req.platformFeeBps } : null,
922
+ platformFee: feeApplied ? { feeBps: req.platformFeeBps } : null,
848
923
  },
849
924
  };
850
925
  },
@@ -862,11 +937,7 @@ export function createTitanSwapAdapter(config = {}) {
862
937
  const ixs = raw.route.instructions
863
938
  .map(normalizeTitanInstruction)
864
939
  .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
- }
940
+ const swapIx = validatePrebuiltEscrowInstructionBounds(ixs, req.escrowPubkey, 'Titan');
870
941
  const routeHopCount = Array.isArray(raw.route.steps) && raw.route.steps.length > 0 ? raw.route.steps.length : null;
871
942
  return {
872
943
  provider: 'titan',
@@ -884,7 +955,7 @@ export function createTitanSwapAdapter(config = {}) {
884
955
  };
885
956
  }
886
957
  export function createBedrockSwapAdapter(config = {}) {
887
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
958
+ const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
888
959
  const apiKey = config.apiKey?.trim() ?? '';
889
960
  const rawUrl = config.apiUrl?.trim() ?? '';
890
961
  const resolveBase = () => {
@@ -934,7 +1005,10 @@ export function createBedrockSwapAdapter(config = {}) {
934
1005
  }, 'Bedrock');
935
1006
  if (!res.ok)
936
1007
  throw new Error(`Bedrock quote HTTP ${res.status}`);
937
- const raw = (await res.json());
1008
+ const rawJson = await res.json();
1009
+ if (!isPlainObject(rawJson))
1010
+ throw new Error('Bedrock returned non-object quote JSON');
1011
+ const raw = rawJson;
938
1012
  const outBi = parsePositiveUintString(raw.outAmount);
939
1013
  if (outBi === null)
940
1014
  throw new Error('Bedrock returned invalid or zero outAmount');
@@ -956,6 +1030,7 @@ export function createBedrockSwapAdapter(config = {}) {
956
1030
  };
957
1031
  });
958
1032
  const feeObj = raw.fee ?? raw.platformFee;
1033
+ const parsedSlippage = Number(raw.slippageBps);
959
1034
  return {
960
1035
  provider: 'bedrock',
961
1036
  inputMint: raw.inputMint ?? req.inputMint,
@@ -963,7 +1038,7 @@ export function createBedrockSwapAdapter(config = {}) {
963
1038
  inAmount: raw.inAmount ?? req.amount,
964
1039
  outAmount: outBi.toString(),
965
1040
  otherAmountThreshold: raw.otherAmountThreshold ?? outBi.toString(),
966
- slippageBps: Number(raw.slippageBps ?? req.slippageBps),
1041
+ slippageBps: Number.isFinite(parsedSlippage) && parsedSlippage >= 0 ? parsedSlippage : req.slippageBps,
967
1042
  priceImpactPct: raw.priceImpactPct ?? null,
968
1043
  platformFee: feeObj?.amount
969
1044
  ? {
@@ -994,7 +1069,10 @@ export function createBedrockSwapAdapter(config = {}) {
994
1069
  }, 'Bedrock');
995
1070
  if (!res.ok)
996
1071
  throw new Error(`Bedrock swap-instructions HTTP ${res.status}`);
997
- const payload = (await res.json());
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;
998
1076
  if (!isValidRouterInstruction(payload.swapInstruction)) {
999
1077
  throw new Error('Bedrock did not return a valid swapInstruction');
1000
1078
  }
@@ -1010,7 +1088,7 @@ export function createBedrockSwapAdapter(config = {}) {
1010
1088
  reportedRouterCu: payload.transactionConfig?.computeUnitLimit,
1011
1089
  routeHopCount,
1012
1090
  }),
1013
- feeAccount: req.feeOwnerWallet ?? req.feeAccountAta ?? null,
1091
+ feeAccount: req.feeOwnerWallet ?? null,
1014
1092
  };
1015
1093
  },
1016
1094
  };
@@ -1032,15 +1110,15 @@ export class AudrenSwapRouter {
1032
1110
  createBedrockSwapAdapter({ ...config.bedrock, fetchImpl: config.bedrock?.fetchImpl ?? sharedFetch }),
1033
1111
  ];
1034
1112
  for (const adapter of builtins) {
1035
- this.adapters.set(adapter.id, adapter);
1113
+ this.register(adapter);
1036
1114
  }
1037
1115
  for (const custom of config.customAdapters ?? []) {
1038
- this.adapters.set(custom.id, custom);
1116
+ this.register(custom);
1039
1117
  }
1040
1118
  this.enabledProviders = config.enabledProviders
1041
1119
  ? new Set(config.enabledProviders.map((s) => s.trim().toLowerCase()).filter(Boolean))
1042
1120
  : null;
1043
- this.defaultProvider = config.defaultProvider ?? 'auto';
1121
+ this.defaultProvider = (config.defaultProvider ?? 'auto').trim().toLowerCase();
1044
1122
  this.defaultTimeoutMs = config.timeoutMs ?? 10_000;
1045
1123
  this.allowedRouterPrograms = config.allowedRouterPrograms ?? AUDREN_AUDITED_SWAP_ROUTERS;
1046
1124
  this.allowUnverifiedRouter = config.allowUnverifiedRouter ?? false;
@@ -1081,27 +1159,59 @@ export class AudrenSwapRouter {
1081
1159
  }
1082
1160
  /** Register or override a custom aggregator adapter at runtime. */
1083
1161
  register(adapter) {
1084
- this.adapters.set(adapter.id, adapter);
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);
1085
1167
  return this;
1086
1168
  }
1087
1169
  getAdapter(id) {
1088
1170
  return this.adapters.get(id.trim().toLowerCase());
1089
1171
  }
1172
+ getAllowedRouterPrograms() {
1173
+ return [...this.allowedRouterPrograms];
1174
+ }
1090
1175
  isEnabled(id) {
1091
- return this.enabledProviders === null || this.enabledProviders.has(id.toLowerCase());
1176
+ return this.enabledProviders === null || this.enabledProviders.has(id.trim().toLowerCase());
1092
1177
  }
1093
1178
  listProviders() {
1094
- return Array.from(this.adapters.values()).map((a) => ({
1095
- id: a.id,
1179
+ return Array.from(this.adapters.entries()).map(([key, a]) => ({
1180
+ id: key,
1096
1181
  name: a.name,
1097
- enabled: this.isEnabled(a.id) && a.isConfigured(),
1182
+ enabled: this.isEnabled(key) && a.isConfigured(),
1098
1183
  configured: a.isConfigured(),
1099
- isDefault: a.id === this.defaultProvider,
1184
+ isDefault: key === this.defaultProvider,
1100
1185
  capabilities: a.capabilities,
1101
1186
  }));
1102
1187
  }
1103
1188
  resolveActiveAdapters() {
1104
- return Array.from(this.adapters.values()).filter((a) => this.isEnabled(a.id) && a.isConfigured());
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;
1105
1215
  }
1106
1216
  async quote(req) {
1107
1217
  validateQuoteParams(req);
@@ -1119,20 +1229,26 @@ export class AudrenSwapRouter {
1119
1229
  const adapter = this.adapters.get(chosen);
1120
1230
  if (!adapter)
1121
1231
  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`);
1232
+ if (!this.isEnabled(chosen)) {
1233
+ throw new Error(`Swap aggregator "${chosen}" is disabled by router configuration`);
1124
1234
  }
1125
1235
  if (!adapter.isConfigured()) {
1126
- throw new Error(`Swap aggregator "${adapter.id}" is not configured`);
1236
+ throw new Error(`Swap aggregator "${chosen}" is not configured`);
1127
1237
  }
1238
+ const feeErr = this.checkFeeAccountForAdapter(adapter, adapterReq);
1239
+ if (feeErr)
1240
+ throw new Error(feeErr);
1128
1241
  const quote = await adapter.quote(adapterReq);
1129
1242
  const badVenue = findExcludedCpiVenue(quote, excluded);
1130
1243
  if (badVenue) {
1131
- throw new Error(`Aggregator "${adapter.id}" routed via PDA-CPI-excluded venue "${badVenue}"`);
1244
+ throw new Error(`Aggregator "${chosen}" routed via PDA-CPI-excluded venue "${badVenue}"`);
1132
1245
  }
1246
+ const routerErr = this.checkPrebuiltRouterAllowlist(quote);
1247
+ if (routerErr)
1248
+ throw new Error(routerErr);
1133
1249
  return {
1134
1250
  winner: quote,
1135
- candidates: [{ provider: adapter.id, outAmount: quote.outAmount, latencyMs: quote.latencyMs }],
1251
+ candidates: [{ provider: chosen, outAmount: quote.outAmount, latencyMs: quote.latencyMs }],
1136
1252
  escrowPubkey,
1137
1253
  };
1138
1254
  }
@@ -1140,11 +1256,21 @@ export class AudrenSwapRouter {
1140
1256
  if (active.length === 0) {
1141
1257
  throw new Error('No swap aggregators are configured on this AudrenSwapRouter');
1142
1258
  }
1143
- const settled = await Promise.allSettled(active.map((a) => a.quote(adapterReq)));
1144
- const quotes = [];
1259
+ const eligible = [];
1145
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 = [];
1146
1272
  settled.forEach((res, idx) => {
1147
- const id = active[idx].id;
1273
+ const id = eligible[idx].key;
1148
1274
  if (res.status === 'fulfilled') {
1149
1275
  const badVenue = findExcludedCpiVenue(res.value, excluded);
1150
1276
  if (badVenue) {
@@ -1155,6 +1281,15 @@ export class AudrenSwapRouter {
1155
1281
  });
1156
1282
  return;
1157
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
+ }
1158
1293
  quotes.push(res.value);
1159
1294
  candidates.push({
1160
1295
  provider: id,
@@ -1185,11 +1320,11 @@ export class AudrenSwapRouter {
1185
1320
  const adapter = this.adapters.get(providerId);
1186
1321
  if (!adapter)
1187
1322
  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`);
1323
+ if (!this.isEnabled(providerId)) {
1324
+ throw new Error(`Swap aggregator "${providerId}" is disabled by router configuration`);
1190
1325
  }
1191
1326
  if (!adapter.isConfigured()) {
1192
- throw new Error(`Swap aggregator "${adapter.id}" is not configured`);
1327
+ throw new Error(`Swap aggregator "${providerId}" is not configured`);
1193
1328
  }
1194
1329
  const built = await adapter.swapInstructions({
1195
1330
  quoteResponse: req.quoteResponse,
@@ -1202,15 +1337,22 @@ export class AudrenSwapRouter {
1202
1337
  timeoutMs: req.timeoutMs ?? this.defaultTimeoutMs,
1203
1338
  signal: req.signal,
1204
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
+ }
1205
1343
  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})`);
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})`);
1207
1349
  }
1208
1350
  const allowUnverified = req.allowUnverifiedRouter ?? this.allowUnverifiedRouter;
1209
1351
  if (!allowUnverified) {
1210
1352
  const allowed = req.allowedRouterPrograms ?? this.allowedRouterPrograms;
1211
1353
  const routerProg = built.swapInstruction.programId;
1212
1354
  if (!allowed.includes(routerProg)) {
1213
- throw new Error(`Aggregator "${adapter.id}" returned unapproved swap router program ${routerProg}`);
1355
+ throw new Error(`Aggregator "${providerId}" returned unapproved swap router program ${routerProg}`);
1214
1356
  }
1215
1357
  }
1216
1358
  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.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)",