@audren-xyz/sdk 1.3.6 → 1.3.7

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.
@@ -210,6 +210,16 @@ export interface TitanAdapterConfig {
210
210
  export interface BedrockAdapterConfig {
211
211
  apiUrl?: string;
212
212
  apiKey?: string;
213
+ /**
214
+ * Optional Ed25519 private signing key for Order OS `EdDSA` edge JWT authentication
215
+ * (32-byte seed hex/base64/base64url, 64-byte Ed25519 keypair, 48-byte PKCS#8 DER, or JWK JSON).
216
+ * Takes precedence over static `apiKey` when configured.
217
+ */
218
+ signingKey?: string;
219
+ jwtKeyId?: string;
220
+ jwtIssuer?: string;
221
+ jwtAudience?: string;
222
+ jwtSubject?: string;
213
223
  fetchImpl?: typeof fetch;
214
224
  }
215
225
  export interface AudrenSwapRouterConfig {
@@ -260,6 +270,12 @@ export interface SwapRouterEnvLike {
260
270
  TITAN_API_URL?: string;
261
271
  BEDROCK_API_URL?: string;
262
272
  BEDROCK_API_KEY?: string;
273
+ BEDROCK_SIGNING_KEY?: string;
274
+ ORDER_OS_SIGNING_KEY?: string;
275
+ BEDROCK_JWT_KID?: string;
276
+ BEDROCK_JWT_ISS?: string;
277
+ BEDROCK_JWT_AUD?: string;
278
+ BEDROCK_JWT_SUB?: string;
263
279
  ENABLED_AGGREGATORS?: string;
264
280
  DEFAULT_AGGREGATOR?: string;
265
281
  /** Optional comma-separated list of approved swap router program IDs (defaults to `AUDREN_AUDITED_SWAP_ROUTERS`). */
@@ -1,3 +1,4 @@
1
+ import { ed25519 } from '@noble/curves/ed25519.js';
1
2
  import { AUDREN_PROGRAM_ID, CLASSIC_TOKEN_PROGRAM_ID, CU_LIMIT_EXEC_VIA_ESCROW_BASE, TOKEN_2022_PROGRAM_ID, } from './constants.js';
2
3
  import { deriveEscrowPda } from './pda.js';
3
4
  import { AUDREN_AUDITED_SWAP_ROUTERS } from './relayer.js';
@@ -124,6 +125,84 @@ function bytesToBase64(bytes) {
124
125
  }
125
126
  return btoa(bin);
126
127
  }
128
+ function bytesToBase64Url(bytes) {
129
+ return bytesToBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
130
+ }
131
+ function decodeBase64Any(str) {
132
+ const norm = str.replace(/-/g, '+').replace(/_/g, '/');
133
+ const padded = norm.length % 4 === 0 ? norm : norm + '='.repeat(4 - (norm.length % 4));
134
+ const bin = atob(padded);
135
+ const out = new Uint8Array(bin.length);
136
+ for (let i = 0; i < bin.length; i++)
137
+ out[i] = bin.charCodeAt(i);
138
+ return out;
139
+ }
140
+ const ED25519_PKCS8_PREFIX = new Uint8Array([
141
+ 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
142
+ ]);
143
+ function parseEd25519Seed32(raw) {
144
+ const trimmed = raw.trim();
145
+ if (!trimmed)
146
+ throw new Error('Bedrock signingKey must not be empty');
147
+ let bytes;
148
+ if (trimmed.startsWith('{')) {
149
+ const jwk = JSON.parse(trimmed);
150
+ if (typeof jwk.d !== 'string' || !jwk.d.trim()) {
151
+ throw new Error('Bedrock signingKey JWK missing "d" private key field');
152
+ }
153
+ bytes = decodeBase64Any(jwk.d.trim());
154
+ }
155
+ else if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
156
+ bytes = new Uint8Array(32);
157
+ for (let i = 0; i < 32; i++) {
158
+ bytes[i] = parseInt(trimmed.slice(i * 2, i * 2 + 2), 16);
159
+ }
160
+ }
161
+ else {
162
+ const body = trimmed.startsWith('-----BEGIN')
163
+ ? trimmed.replace(/-----[^-]+-----/g, '').replace(/\s+/g, '')
164
+ : trimmed;
165
+ bytes = decodeBase64Any(body);
166
+ }
167
+ let seed;
168
+ if (bytes.byteLength === 32) {
169
+ seed = bytes;
170
+ }
171
+ else if (bytes.byteLength === 64) {
172
+ seed = bytes.subarray(0, 32);
173
+ }
174
+ else if (bytes.byteLength === 48 &&
175
+ ED25519_PKCS8_PREFIX.every((b, idx) => bytes[idx] === b)) {
176
+ seed = bytes.subarray(16, 48);
177
+ }
178
+ else {
179
+ throw new Error(`Bedrock signingKey has unsupported byte length (${bytes.byteLength})`);
180
+ }
181
+ if (seed.every((b) => b === 0)) {
182
+ throw new Error('Bedrock signingKey must not be all-zero');
183
+ }
184
+ return seed;
185
+ }
186
+ const JWT_TEXT_ENCODER = new TextEncoder();
187
+ function signBedrockEdDsaJwt(seed32, opts) {
188
+ const now = Math.floor(Date.now() / 1000);
189
+ const reqBytes = new Uint8Array(8);
190
+ if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
191
+ crypto.getRandomValues(reqBytes);
192
+ }
193
+ const reqId = `audren-${bytesToBase64Url(reqBytes)}`;
194
+ const hdr = bytesToBase64Url(JWT_TEXT_ENCODER.encode(JSON.stringify({ alg: 'EdDSA', typ: 'JWT', kid: opts.kid })));
195
+ const pay = bytesToBase64Url(JWT_TEXT_ENCODER.encode(JSON.stringify({
196
+ iss: opts.iss,
197
+ aud: opts.aud,
198
+ sub: opts.sub,
199
+ iat: now,
200
+ exp: now + 120,
201
+ request: reqId,
202
+ })));
203
+ const sig = ed25519.sign(JWT_TEXT_ENCODER.encode(`${hdr}.${pay}`), seed32);
204
+ return `${hdr}.${pay}.${bytesToBase64Url(sig)}`;
205
+ }
127
206
  function parsePositiveUintString(v) {
128
207
  if (typeof v === 'bigint') {
129
208
  return v > 0n && v <= U64_MAX ? v : null;
@@ -850,69 +929,96 @@ export function createTitanSwapAdapter(config = {}) {
850
929
  }
851
930
  const base = resolveBase();
852
931
  const t0 = Date.now();
853
- const qs = new URLSearchParams({
854
- inputMint: req.inputMint,
855
- outputMint: req.outputMint,
856
- amount: req.amount,
857
- slippageBps: String(req.slippageBps),
858
- userPublicKey: req.escrowPubkey,
859
- ...(req.onlyDirectRoutes ? { onlyDirectRoutes: 'true' } : {}),
860
- ...(req.platformFeeBps && req.platformFeeBps > 0 && req.feeAccountAta
861
- ? { feeBps: String(req.platformFeeBps), feeAccount: req.feeAccountAta }
862
- : {}),
863
- });
864
- const res = await safeAggregatorFetch(fetchImpl, `${base}/quote/swap?${qs.toString()}`, {
865
- headers: {
866
- accept: 'application/json',
867
- ...(apiKey ? { authorization: `Bearer ${apiKey}`, 'x-api-key': apiKey } : {}),
868
- },
869
- signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
870
- }, 'Titan');
871
- if (!res.ok) {
872
- await cancelBodyQuietly(res);
873
- throw new Error(`Titan quote HTTP ${res.status}`);
874
- }
875
- const decodedRaw = await res.json();
876
- if (!isPlainObject(decodedRaw))
877
- throw new Error('Titan returned non-object quote JSON');
878
- const decoded = decodedRaw;
879
- const quotesMap = decoded.quotes && typeof decoded.quotes === 'object' && !Array.isArray(decoded.quotes)
880
- ? decoded.quotes
881
- : {};
882
- const winnerId = decoded.metadata?.ExpectedWinner;
883
- let winnerKey = '';
884
- let route;
885
- let routeOut = null;
886
- if (typeof winnerId === 'string' && Object.prototype.hasOwnProperty.call(quotesMap, winnerId)) {
887
- const candidate = quotesMap[winnerId];
888
- const candidateOut = parsePositiveUintString(candidate?.outAmount);
889
- if (candidate && candidateOut !== null) {
890
- winnerKey = winnerId;
891
- route = candidate;
892
- routeOut = candidateOut;
932
+ const escrowPubkey = req.escrowPubkey;
933
+ const defaultAccountsLimit = Math.min(Math.max(req.maxAccounts ?? 36, 16), 40);
934
+ const fetchTitanCandidate = async (onlyDirect, accountsLimit) => {
935
+ const qs = new URLSearchParams({
936
+ inputMint: req.inputMint,
937
+ outputMint: req.outputMint,
938
+ amount: req.amount,
939
+ slippageBps: String(req.slippageBps),
940
+ userPublicKey: escrowPubkey,
941
+ outputWsol: 'true',
942
+ accountsLimitTotal: String(accountsLimit),
943
+ ...(onlyDirect ? { onlyDirectRoutes: 'true' } : {}),
944
+ ...(req.platformFeeBps && req.platformFeeBps > 0 && req.feeAccountAta
945
+ ? { feeBps: String(req.platformFeeBps), feeAccount: req.feeAccountAta }
946
+ : {}),
947
+ });
948
+ const res = await safeAggregatorFetch(fetchImpl, `${base}/quote/swap?${qs.toString()}`, {
949
+ headers: {
950
+ accept: 'application/json',
951
+ ...(apiKey ? { authorization: `Bearer ${apiKey}`, 'x-api-key': apiKey } : {}),
952
+ },
953
+ signal: buildFetchSignal(req.signal, req.timeoutMs ?? 10_000),
954
+ }, 'Titan');
955
+ if (!res.ok) {
956
+ await cancelBodyQuietly(res);
957
+ throw new Error(`Titan quote HTTP ${res.status}`);
893
958
  }
894
- }
895
- if (!route || routeOut === null) {
896
- let bestOut = 0n;
959
+ const decodedRaw = await res.json();
960
+ if (!isPlainObject(decodedRaw))
961
+ throw new Error('Titan returned non-object quote JSON');
962
+ const decoded = decodedRaw;
963
+ const quotesMap = decoded.quotes && typeof decoded.quotes === 'object' && !Array.isArray(decoded.quotes)
964
+ ? decoded.quotes
965
+ : {};
966
+ // Rank sub-providers: ExpectedWinner first (when valid), then remaining sub-providers by highest outAmount.
967
+ const ranked = [];
968
+ const winnerId = decoded.metadata?.ExpectedWinner;
897
969
  for (const [k, r] of Object.entries(quotesMap)) {
898
970
  const out = parsePositiveUintString(r?.outAmount);
899
- if (out !== null && out > bestOut) {
900
- bestOut = out;
901
- winnerKey = k;
902
- route = r;
903
- routeOut = out;
971
+ if (r && out !== null) {
972
+ ranked.push({ key: k, route: r, out });
904
973
  }
905
974
  }
975
+ if (ranked.length === 0) {
976
+ throw new Error('Titan returned no valid quotes');
977
+ }
978
+ ranked.sort((a, b) => {
979
+ if (a.key === winnerId && b.key !== winnerId)
980
+ return -1;
981
+ if (b.key === winnerId && a.key !== winnerId)
982
+ return 1;
983
+ return b.out > a.out ? 1 : b.out < a.out ? -1 : 0;
984
+ });
985
+ let firstErr = null;
986
+ for (const cand of ranked) {
987
+ const prebuiltIxs = Array.isArray(cand.route.instructions)
988
+ ? cand.route.instructions
989
+ .map(normalizeTitanInstruction)
990
+ .filter((x) => x !== null)
991
+ : [];
992
+ try {
993
+ const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, escrowPubkey, 'Titan');
994
+ return {
995
+ decoded,
996
+ winnerKey: cand.key,
997
+ route: cand.route,
998
+ routeOut: cand.out,
999
+ swapIx,
1000
+ };
1001
+ }
1002
+ catch (err) {
1003
+ if (firstErr === null)
1004
+ firstErr = err;
1005
+ }
1006
+ }
1007
+ throw firstErr ?? new Error('Titan returned no bounded escrow-compatible quotes');
1008
+ };
1009
+ let chosen;
1010
+ try {
1011
+ chosen = await fetchTitanCandidate(Boolean(req.onlyDirectRoutes), defaultAccountsLimit);
906
1012
  }
907
- if (!route || routeOut === null) {
908
- throw new Error('Titan returned no valid quotes');
1013
+ catch (err) {
1014
+ if (!req.onlyDirectRoutes && err instanceof PrebuiltRouteBoundsError && !req.signal?.aborted) {
1015
+ chosen = await fetchTitanCandidate(true, Math.min(defaultAccountsLimit, 28));
1016
+ }
1017
+ else {
1018
+ throw err;
1019
+ }
909
1020
  }
910
- const prebuiltIxs = Array.isArray(route.instructions)
911
- ? route.instructions
912
- .map(normalizeTitanInstruction)
913
- .filter((x) => x !== null)
914
- : [];
915
- const swapIx = validatePrebuiltEscrowInstructionBounds(prebuiltIxs, req.escrowPubkey, 'Titan');
1021
+ const { decoded, winnerKey, route, routeOut, swapIx } = chosen;
916
1022
  const outAmount = routeOut.toString();
917
1023
  const minOut = ((routeOut * BigInt(10_000 - req.slippageBps)) / 10000n).toString();
918
1024
  const steps = Array.isArray(route.steps)
@@ -995,7 +1101,7 @@ export function createTitanSwapAdapter(config = {}) {
995
1101
  ? raw.route.addressLookupTables.filter((x) => typeof x === 'string')
996
1102
  : [],
997
1103
  computeUnitLimit: computeAggregatorExecCuLimit({
998
- reportedRouterCu: raw.route.computeUnits,
1104
+ reportedRouterCu: raw.route.computeUnitsSafe ?? raw.route.computeUnits,
999
1105
  routeHopCount,
1000
1106
  }),
1001
1107
  feeAccount: req.feeAccountAta ?? null,
@@ -1006,17 +1112,36 @@ export function createTitanSwapAdapter(config = {}) {
1006
1112
  export function createBedrockSwapAdapter(config = {}) {
1007
1113
  const fetchImpl = config.fetchImpl ?? defaultFetchImpl;
1008
1114
  const apiKey = config.apiKey?.trim() ?? '';
1115
+ const signingKeyRaw = config.signingKey?.trim() ?? '';
1009
1116
  const rawUrl = config.apiUrl?.trim() ?? '';
1117
+ const jwtOpts = {
1118
+ kid: config.jwtKeyId?.trim() || 'k256-app-order-os-1',
1119
+ iss: config.jwtIssuer?.trim() || 'k256-gateway',
1120
+ aud: config.jwtAudience?.trim() || 'k256-order-os',
1121
+ sub: config.jwtSubject?.trim() || 'gateway',
1122
+ };
1123
+ let cachedSeed32 = null;
1010
1124
  const resolveBase = () => {
1011
1125
  if (!rawUrl)
1012
1126
  throw new Error('Bedrock adapter not configured (set apiUrl)');
1013
1127
  return validateAggregatorBaseUrl(rawUrl, 'Bedrock');
1014
1128
  };
1015
- const makeHeaders = () => ({
1016
- accept: 'application/json',
1017
- 'content-type': 'application/json',
1018
- ...(apiKey ? { authorization: `Bearer ${apiKey}`, 'x-api-key': apiKey } : {}),
1019
- });
1129
+ const makeHeaders = () => {
1130
+ const baseHeaders = {
1131
+ accept: 'application/json',
1132
+ 'content-type': 'application/json',
1133
+ };
1134
+ if (signingKeyRaw) {
1135
+ if (!cachedSeed32)
1136
+ cachedSeed32 = parseEd25519Seed32(signingKeyRaw);
1137
+ baseHeaders.authorization = `Bearer ${signBedrockEdDsaJwt(cachedSeed32, jwtOpts)}`;
1138
+ }
1139
+ else if (apiKey) {
1140
+ baseHeaders.authorization = `Bearer ${apiKey}`;
1141
+ baseHeaders['x-api-key'] = apiKey;
1142
+ }
1143
+ return baseHeaders;
1144
+ };
1020
1145
  return {
1021
1146
  id: 'bedrock',
1022
1147
  name: 'Bedrock',
@@ -1206,7 +1331,15 @@ export class AudrenSwapRouter {
1206
1331
  apiUrl: env.OKX_API_URL,
1207
1332
  },
1208
1333
  titan: { apiKey: env.TITAN_API_KEY, apiUrl: env.TITAN_API_URL },
1209
- bedrock: { apiUrl: env.BEDROCK_API_URL, apiKey: env.BEDROCK_API_KEY },
1334
+ bedrock: {
1335
+ apiUrl: env.BEDROCK_API_URL,
1336
+ apiKey: env.BEDROCK_API_KEY,
1337
+ signingKey: env.BEDROCK_SIGNING_KEY ?? env.ORDER_OS_SIGNING_KEY,
1338
+ jwtKeyId: env.BEDROCK_JWT_KID,
1339
+ jwtIssuer: env.BEDROCK_JWT_ISS,
1340
+ jwtAudience: env.BEDROCK_JWT_AUD,
1341
+ jwtSubject: env.BEDROCK_JWT_SUB,
1342
+ },
1210
1343
  ...(enabledProviders && enabledProviders.length > 0 ? { enabledProviders } : {}),
1211
1344
  ...(defaultRaw ? { defaultProvider: defaultRaw } : {}),
1212
1345
  ...(allowedRouterPrograms && allowedRouterPrograms.length > 0 ? { allowedRouterPrograms } : {}),
package/dist/relayer.js CHANGED
@@ -18,6 +18,7 @@ export const AUDREN_AUDITED_SWAP_ROUTERS = [
18
18
  '6m2CDdhRgxpH4WjvdzxAYbGxwdGUz5MziiL5jek2kBma', // OKX DEX Router (v1)
19
19
  'T1TANpTeScyeqVzzgNViGDNrkQ6qHz9KrSBS4aNXvGT', // Titan Meta-Aggregator
20
20
  'proVF4pMXVaYqmy4NjniPh4pqKNfMmsihgd4wdkCX3u', // OKX DEX Aggregation Router V2/V6
21
+ 'BrqCvvZwUaJY2fxkByyahaDuvdbmTXiAghQnfQsHvJoc', // Bedrock (Order OS)
21
22
  ];
22
23
  export class AudrenRelayError extends Error {
23
24
  status;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audren-xyz/sdk",
3
- "version": "1.3.6",
3
+ "version": "1.3.7",
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)",