@trustware/sdk-staging 1.0.16-staging.13 → 1.0.17-staging.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.cjs ADDED
@@ -0,0 +1,3107 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
24
+
25
+ // src/config/defaults.ts
26
+ var DEFAULT_SLIPPAGE, DEFAULT_AUTO_DETECT_PROVIDER, DEFAULT_THEME, DEFAULT_MESSAGES;
27
+ var init_defaults = __esm({
28
+ "src/config/defaults.ts"() {
29
+ "use strict";
30
+ DEFAULT_SLIPPAGE = 1;
31
+ DEFAULT_AUTO_DETECT_PROVIDER = false;
32
+ DEFAULT_THEME = {
33
+ primaryColor: "#4F46E5",
34
+ secondaryColor: "#6366F1",
35
+ backgroundColor: "#FFFFFF",
36
+ textColor: "#111827",
37
+ borderColor: "#E5E7EB",
38
+ radius: 8
39
+ };
40
+ DEFAULT_MESSAGES = {
41
+ title: "Trustware SDK",
42
+ description: "Seamlessly bridge assets across chains with Trustware."
43
+ };
44
+ }
45
+ });
46
+
47
+ // src/types/config.ts
48
+ var DEFAULT_RETRY_CONFIG;
49
+ var init_config = __esm({
50
+ "src/types/config.ts"() {
51
+ "use strict";
52
+ DEFAULT_RETRY_CONFIG = {
53
+ autoRetry: true,
54
+ maxRetries: 3,
55
+ baseDelayMs: 1e3,
56
+ approachingThreshold: 5
57
+ };
58
+ }
59
+ });
60
+
61
+ // src/constants.ts
62
+ var SDK_NAME, SDK_VERSION, API_ROOT, API_PREFIX, WALLETCONNECT_PROJECT_ID;
63
+ var init_constants = __esm({
64
+ "src/constants.ts"() {
65
+ "use strict";
66
+ SDK_NAME = "@trustware/sdk";
67
+ SDK_VERSION = "1.0.17-staging.15";
68
+ API_ROOT = "https://bv-staging-api.trustware.io";
69
+ API_PREFIX = "/api";
70
+ WALLETCONNECT_PROJECT_ID = "4ead125c-63be-4b1a-a835-cef2dce67b84";
71
+ }
72
+ });
73
+
74
+ // src/config/merge.ts
75
+ function resolveWalletConnectConfig(input) {
76
+ if (input?.disabled) return void 0;
77
+ const projectId = input?.projectId ?? WALLETCONNECT_PROJECT_ID;
78
+ return {
79
+ projectId,
80
+ chains: input?.chains ?? [1],
81
+ // Default to Ethereum mainnet
82
+ optionalChains: input?.optionalChains ?? [
83
+ 1,
84
+ 10,
85
+ 56,
86
+ 137,
87
+ 8453,
88
+ 42161,
89
+ 43114
90
+ ],
91
+ // ETH, OP, BSC, Polygon, Base, Arbitrum, Avalanche
92
+ metadata: {
93
+ name: input?.metadata?.name ?? "Trustware",
94
+ description: input?.metadata?.description ?? "Cross-chain bridge & top-up",
95
+ url: input?.metadata?.url ?? "https://trustware.io",
96
+ icons: input?.metadata?.icons ?? ["https://app.trustware.io/icon.png"]
97
+ },
98
+ relayUrl: input?.relayUrl,
99
+ showQrModal: input?.showQrModal ?? true
100
+ };
101
+ }
102
+ function deepMerge(base, patch) {
103
+ if (!patch) return { ...base };
104
+ const out = Array.isArray(base) ? [...base] : { ...base };
105
+ for (const [k, v] of Object.entries(patch)) {
106
+ if (v && typeof v === "object" && !Array.isArray(v)) {
107
+ out[k] = deepMerge(base[k] ?? {}, v);
108
+ } else {
109
+ out[k] = v;
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+ function normalizeSlippage(v) {
115
+ const n = Number(v);
116
+ if (!Number.isFinite(n)) return DEFAULT_SLIPPAGE;
117
+ if (n <= 0) return DEFAULT_SLIPPAGE;
118
+ if (n > 5) return 5;
119
+ return n;
120
+ }
121
+ function resolveConfig(input) {
122
+ if (!input?.apiKey) {
123
+ throw new Error("TrustwareConfig: 'apiKey' is required.");
124
+ }
125
+ if (!input.routes?.toChain || !input.routes?.toToken) {
126
+ throw new Error(
127
+ "TrustwareConfig: 'routes.toChain' and 'routes.toToken' are required."
128
+ );
129
+ }
130
+ const autoDetectProvider = typeof input.autoDetectProvider === "boolean" ? input.autoDetectProvider : DEFAULT_AUTO_DETECT_PROVIDER;
131
+ const routes = {
132
+ toChain: input.routes.toChain,
133
+ toToken: input.routes.toToken,
134
+ fromToken: input.routes.fromToken,
135
+ fromAddress: input.routes.fromAddress,
136
+ toAddress: input.routes.toAddress,
137
+ defaultSlippage: normalizeSlippage(
138
+ input.routes.defaultSlippage ?? DEFAULT_SLIPPAGE
139
+ ),
140
+ routeType: input.routes.routeType ?? "swap",
141
+ options: {
142
+ ...input.routes.options
143
+ }
144
+ };
145
+ const theme = deepMerge(DEFAULT_THEME, input.theme);
146
+ const messages = deepMerge(DEFAULT_MESSAGES, input.messages);
147
+ const retry = {
148
+ autoRetry: input.retry?.autoRetry ?? DEFAULT_RETRY_CONFIG.autoRetry,
149
+ maxRetries: input.retry?.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,
150
+ baseDelayMs: input.retry?.baseDelayMs ?? DEFAULT_RETRY_CONFIG.baseDelayMs,
151
+ approachingThreshold: input.retry?.approachingThreshold ?? DEFAULT_RETRY_CONFIG.approachingThreshold,
152
+ onRateLimitInfo: input.retry?.onRateLimitInfo,
153
+ onRateLimited: input.retry?.onRateLimited,
154
+ onRateLimitApproaching: input.retry?.onRateLimitApproaching
155
+ };
156
+ const walletConnect = resolveWalletConnectConfig(input.walletConnect);
157
+ return {
158
+ apiKey: input.apiKey,
159
+ routes,
160
+ autoDetectProvider,
161
+ theme,
162
+ messages,
163
+ retry,
164
+ walletConnect,
165
+ onError: input.onError,
166
+ onSuccess: input.onSuccess,
167
+ onEvent: input.onEvent
168
+ };
169
+ }
170
+ var init_merge = __esm({
171
+ "src/config/merge.ts"() {
172
+ "use strict";
173
+ init_defaults();
174
+ init_config();
175
+ init_constants();
176
+ }
177
+ });
178
+
179
+ // src/config/store.ts
180
+ var store_exports = {};
181
+ __export(store_exports, {
182
+ TrustwareConfig: () => TrustwareConfig,
183
+ TrustwareConfigStore: () => TrustwareConfigStore
184
+ });
185
+ var ConfigStore, TrustwareConfigStore, TrustwareConfig;
186
+ var init_store = __esm({
187
+ "src/config/store.ts"() {
188
+ "use strict";
189
+ init_merge();
190
+ ConfigStore = class {
191
+ constructor() {
192
+ this._cfg = null;
193
+ this._listeners = /* @__PURE__ */ new Set();
194
+ }
195
+ isInitialized() {
196
+ return this._cfg != null;
197
+ }
198
+ peek() {
199
+ return this._cfg;
200
+ }
201
+ /** Initialize or replace the config */
202
+ init(opts) {
203
+ this._cfg = resolveConfig(opts);
204
+ this.emit();
205
+ }
206
+ /** Partially update by re-resolving from last + patch */
207
+ update(patch) {
208
+ if (!this._cfg) throw new Error("TrustwareConfig: call init() first.");
209
+ const next = resolveConfig({
210
+ ...this._cfg,
211
+ ...patch,
212
+ routes: { ...this._cfg.routes, ...patch.routes ?? {} },
213
+ theme: {
214
+ ...this._cfg.theme,
215
+ ...patch.theme ?? {}
216
+ },
217
+ messages: {
218
+ ...this._cfg.messages,
219
+ ...patch.messages ?? {}
220
+ },
221
+ retry: { ...this._cfg.retry, ...patch.retry ?? {} },
222
+ walletConnect: patch.walletConnect ? { ...this._cfg.walletConnect, ...patch.walletConnect } : this._cfg.walletConnect
223
+ });
224
+ this._cfg = next;
225
+ this.emit();
226
+ }
227
+ get() {
228
+ if (!this._cfg) throw new Error("TrustwareConfig: not initialized.");
229
+ return this._cfg;
230
+ }
231
+ getTheme() {
232
+ return this.get().theme;
233
+ }
234
+ getMessages() {
235
+ return this.get().messages;
236
+ }
237
+ subscribe(fn) {
238
+ this._listeners.add(fn);
239
+ if (this._cfg) fn(this._cfg);
240
+ return () => {
241
+ this._listeners.delete(fn);
242
+ };
243
+ }
244
+ emit() {
245
+ if (!this._cfg) return;
246
+ for (const fn of this._listeners) fn(this._cfg);
247
+ }
248
+ };
249
+ TrustwareConfigStore = new ConfigStore();
250
+ TrustwareConfig = {
251
+ init: (opts) => TrustwareConfigStore.init(opts),
252
+ update: (patch) => TrustwareConfigStore.update(patch),
253
+ get: () => TrustwareConfigStore.get(),
254
+ getTheme: () => TrustwareConfigStore.get().theme,
255
+ getMessages: () => TrustwareConfigStore.get().messages,
256
+ subscribe: (fn) => TrustwareConfigStore.subscribe(fn)
257
+ };
258
+ }
259
+ });
260
+
261
+ // src/utils/chains.ts
262
+ function inferChainTypeFromValue(normalized) {
263
+ if (!normalized) return void 0;
264
+ const aliased = CHAIN_TYPE_ALIASES[normalized];
265
+ if (aliased) return aliased;
266
+ if (normalized === "evm" || normalized === "solana" || normalized === "cosmos" || normalized === "bitcoin") {
267
+ return normalized;
268
+ }
269
+ if (/^eip155:\d+$/.test(normalized) || /^\d+$/.test(normalized)) {
270
+ return "evm";
271
+ }
272
+ if (normalized.startsWith("solana:") || normalized.includes("solana")) {
273
+ return "solana";
274
+ }
275
+ if (normalized.startsWith("cosmos:") || normalized.startsWith("sei:") || normalized === "sei-evm") {
276
+ return "cosmos";
277
+ }
278
+ return void 0;
279
+ }
280
+ function normalizeChainKey(value) {
281
+ if (value === void 0 || value === null) return "";
282
+ return String(value).trim().toLowerCase();
283
+ }
284
+ function normalizeChainType(chain) {
285
+ if (!chain) return void 0;
286
+ const raw = typeof chain === "string" ? chain : chain.type ?? chain.chainType ?? chain.networkIdentifier ?? chain.chainId ?? chain.id ?? chain.networkName ?? chain.axelarChainName;
287
+ if (!raw) return void 0;
288
+ const normalized = String(raw).trim().toLowerCase();
289
+ return inferChainTypeFromValue(normalized) ?? normalized;
290
+ }
291
+ function getNativeTokenAddress(chainType) {
292
+ return normalizeChainType(chainType) === "solana" ? NATIVE_SOLANA : NATIVE_EVM;
293
+ }
294
+ function isSolanaNativeTokenAlias(address) {
295
+ if (!address) return false;
296
+ const trimmed = address.trim();
297
+ if (!trimmed) return false;
298
+ return trimmed === NATIVE_SOLANA || trimmed.toLowerCase() === NATIVE_EVM;
299
+ }
300
+ function normalizeAddress(address, chainType) {
301
+ const trimmed = address.trim();
302
+ if (normalizeChainType(chainType) === "solana") {
303
+ if (isSolanaNativeTokenAlias(trimmed)) {
304
+ return NATIVE_SOLANA;
305
+ }
306
+ return trimmed;
307
+ }
308
+ return trimmed.toLowerCase();
309
+ }
310
+ function isZeroAddressLike(address, chainType) {
311
+ if (!address) return true;
312
+ const normalized = normalizeAddress(address, chainType);
313
+ return normalized === normalizeAddress(getNativeTokenAddress(chainType), chainType) || normalized === "0x0000000000000000000000000000000000000000";
314
+ }
315
+ var NATIVE_EVM, NATIVE_SOLANA, CHAIN_TYPE_ALIASES;
316
+ var init_chains = __esm({
317
+ "src/utils/chains.ts"() {
318
+ "use strict";
319
+ NATIVE_EVM = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
320
+ NATIVE_SOLANA = "So11111111111111111111111111111111111111111";
321
+ CHAIN_TYPE_ALIASES = {
322
+ btc: "bitcoin",
323
+ bitcoin: "bitcoin",
324
+ sei: "cosmos",
325
+ "pacific-1": "cosmos"
326
+ };
327
+ }
328
+ });
329
+
330
+ // src/config/index.ts
331
+ var init_config2 = __esm({
332
+ "src/config/index.ts"() {
333
+ "use strict";
334
+ init_defaults();
335
+ init_merge();
336
+ init_store();
337
+ }
338
+ });
339
+
340
+ // src/core/http.ts
341
+ var http_exports = {};
342
+ __export(http_exports, {
343
+ RateLimitError: () => RateLimitError,
344
+ apiBase: () => apiBase,
345
+ assertOK: () => assertOK,
346
+ jsonHeaders: () => jsonHeaders,
347
+ parseRateLimitHeaders: () => parseRateLimitHeaders,
348
+ rateLimitedFetch: () => rateLimitedFetch,
349
+ validateSdkAccess: () => validateSdkAccess
350
+ });
351
+ function apiBase() {
352
+ return `${API_ROOT}${API_PREFIX}`;
353
+ }
354
+ function jsonHeaders(extra) {
355
+ const cfg = TrustwareConfigStore.get();
356
+ const h = {
357
+ "Content-Type": "application/json",
358
+ "X-API-Key": cfg.apiKey,
359
+ "X-SDK-Name": SDK_NAME,
360
+ "X-SDK-Version": SDK_VERSION,
361
+ "X-API-Version": "2025-10-01"
362
+ };
363
+ return { ...h, ...extra || {} };
364
+ }
365
+ async function assertOK(r) {
366
+ if (r.ok) return;
367
+ let msg = r.statusText;
368
+ try {
369
+ const j = await r.json();
370
+ if (j?.error) msg = j.error;
371
+ } catch {
372
+ }
373
+ throw new Error(`HTTP ${r.status}: ${msg}`);
374
+ }
375
+ async function validateSdkAccess() {
376
+ const r = await fetch(`${apiBase()}/sdk/validate`, {
377
+ method: "GET",
378
+ headers: jsonHeaders()
379
+ });
380
+ await assertOK(r);
381
+ const j = await r.json();
382
+ return j.data;
383
+ }
384
+ function parseRateLimitHeaders(r) {
385
+ const limit = r.headers.get("X-RateLimit-Limit");
386
+ const remaining = r.headers.get("X-RateLimit-Remaining");
387
+ const reset = r.headers.get("X-RateLimit-Reset");
388
+ if (!limit || !remaining || !reset) {
389
+ return null;
390
+ }
391
+ const info = {
392
+ limit: parseInt(limit, 10),
393
+ remaining: parseInt(remaining, 10),
394
+ reset: parseInt(reset, 10)
395
+ };
396
+ const retryAfter = r.headers.get("Retry-After");
397
+ if (retryAfter) {
398
+ info.retryAfter = parseInt(retryAfter, 10);
399
+ }
400
+ return info;
401
+ }
402
+ function notifyRateLimitCallbacks(info, isRateLimited, retryCount) {
403
+ const cfg = TrustwareConfigStore.get();
404
+ const { retry } = cfg;
405
+ if (retry.onRateLimitInfo) {
406
+ retry.onRateLimitInfo(info);
407
+ }
408
+ if (isRateLimited && retry.onRateLimited) {
409
+ retry.onRateLimited(info, retryCount);
410
+ }
411
+ if (!isRateLimited && retry.onRateLimitApproaching && info.remaining <= retry.approachingThreshold) {
412
+ retry.onRateLimitApproaching(info, retry.approachingThreshold);
413
+ }
414
+ }
415
+ function calculateBackoffDelay(baseDelayMs, retryCount, retryAfter) {
416
+ if (retryAfter && retryAfter > 0) {
417
+ return retryAfter * 1e3;
418
+ }
419
+ return baseDelayMs * Math.pow(2, retryCount);
420
+ }
421
+ function sleep(ms) {
422
+ return new Promise((resolve) => setTimeout(resolve, ms));
423
+ }
424
+ async function rateLimitedFetch(url, options = {}) {
425
+ const { skipRateLimit, ...fetchOptions } = options;
426
+ const cfg = TrustwareConfigStore.get();
427
+ if (!cfg.retry.autoRetry || skipRateLimit) {
428
+ return fetch(url, fetchOptions);
429
+ }
430
+ const { maxRetries, baseDelayMs } = cfg.retry;
431
+ let retryCount = 0;
432
+ while (true) {
433
+ const response = await fetch(url, fetchOptions);
434
+ const rateLimitInfo = parseRateLimitHeaders(response);
435
+ if (response.status === 429) {
436
+ if (rateLimitInfo) {
437
+ notifyRateLimitCallbacks(rateLimitInfo, true, retryCount);
438
+ }
439
+ if (retryCount >= maxRetries) {
440
+ throw new RateLimitError(
441
+ rateLimitInfo || { limit: 0, remaining: 0, reset: 0 },
442
+ true
443
+ );
444
+ }
445
+ const delay = calculateBackoffDelay(
446
+ baseDelayMs,
447
+ retryCount,
448
+ rateLimitInfo?.retryAfter
449
+ );
450
+ await sleep(delay);
451
+ retryCount++;
452
+ continue;
453
+ }
454
+ if (rateLimitInfo) {
455
+ notifyRateLimitCallbacks(rateLimitInfo, false, 0);
456
+ }
457
+ return response;
458
+ }
459
+ }
460
+ var RateLimitError;
461
+ var init_http = __esm({
462
+ "src/core/http.ts"() {
463
+ "use strict";
464
+ init_constants();
465
+ init_config2();
466
+ RateLimitError = class extends Error {
467
+ constructor(info, retriesExhausted) {
468
+ const message = retriesExhausted ? `Rate limit exceeded after max retries. Try again in ${info.retryAfter ?? Math.ceil((info.reset * 1e3 - Date.now()) / 1e3)} seconds.` : `Rate limit exceeded. Try again in ${info.retryAfter} seconds.`;
469
+ super(message);
470
+ this.name = "RateLimitError";
471
+ this.rateLimitInfo = info;
472
+ this.retriesExhausted = retriesExhausted;
473
+ }
474
+ };
475
+ }
476
+ });
477
+
478
+ // src/registry.ts
479
+ var registry_exports = {};
480
+ __export(registry_exports, {
481
+ NATIVE: () => NATIVE,
482
+ Registry: () => Registry
483
+ });
484
+ function getChainAliases(chain) {
485
+ const values = [
486
+ chain.chainId,
487
+ chain.id,
488
+ chain.networkIdentifier,
489
+ chain.axelarChainName,
490
+ chain.networkName
491
+ ];
492
+ return values.map((value) => normalizeChainKey(value)).filter(Boolean);
493
+ }
494
+ var NATIVE, Registry;
495
+ var init_registry = __esm({
496
+ "src/registry.ts"() {
497
+ "use strict";
498
+ init_store();
499
+ init_chains();
500
+ NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
501
+ Registry = class {
502
+ constructor(baseURL) {
503
+ this.baseURL = baseURL;
504
+ this._chainsById = /* @__PURE__ */ new Map();
505
+ this._chainAliases = /* @__PURE__ */ new Map();
506
+ this._tokensByChain = /* @__PURE__ */ new Map();
507
+ this._loaded = false;
508
+ this._loadingPromise = null;
509
+ }
510
+ async ensureLoaded() {
511
+ if (this._loaded) return;
512
+ if (this._loadingPromise) {
513
+ await this._loadingPromise;
514
+ return;
515
+ }
516
+ this._loadingPromise = this.load();
517
+ try {
518
+ await this._loadingPromise;
519
+ } finally {
520
+ this._loadingPromise = null;
521
+ }
522
+ }
523
+ storeToken(chainKey, token) {
524
+ const list = this._tokensByChain.get(chainKey) ?? [];
525
+ list.push(token);
526
+ this._tokensByChain.set(chainKey, list);
527
+ }
528
+ async load() {
529
+ const cfg = TrustwareConfigStore.get();
530
+ const [chainsRes, tokensRes] = await Promise.all([
531
+ fetch(`${this.baseURL}/v1/routes/chains`, {
532
+ headers: { Accept: "application/json", "X-API-Key": cfg.apiKey }
533
+ }),
534
+ fetch(`${this.baseURL}/v1/routes/tokens`, {
535
+ headers: { Accept: "application/json", "X-API-Key": cfg.apiKey }
536
+ })
537
+ ]);
538
+ if (!chainsRes.ok) throw new Error(`chains: HTTP ${chainsRes.status}`);
539
+ if (!tokensRes.ok) throw new Error(`tokens: HTTP ${tokensRes.status}`);
540
+ const chains = await chainsRes.json();
541
+ const tokens = await tokensRes.json();
542
+ const chainsArr = Array.isArray(chains) ? chains : chains.data ?? [];
543
+ for (const chain of chainsArr) {
544
+ const canonical = chain?.chainId ?? chain?.id;
545
+ if (canonical == null) continue;
546
+ const normalized = {
547
+ ...chain,
548
+ id: chain.id ?? canonical,
549
+ chainId: chain.chainId ?? canonical
550
+ };
551
+ const canonicalKey = normalizeChainKey(canonical);
552
+ this._chainsById.set(canonicalKey, normalized);
553
+ for (const alias of getChainAliases(normalized)) {
554
+ this._chainAliases.set(alias, canonicalKey);
555
+ }
556
+ }
557
+ const tokensArr = Array.isArray(tokens) ? tokens : tokens.data ?? [];
558
+ for (const token of tokensArr) {
559
+ const chainRef = token?.chainId;
560
+ if (chainRef == null) continue;
561
+ const normalized = {
562
+ ...token,
563
+ chainId: token.chainId ?? chainRef
564
+ };
565
+ const resolvedChain = this.chain(chainRef);
566
+ const aliases = resolvedChain ? getChainAliases(resolvedChain) : [normalizeChainKey(chainRef)];
567
+ for (const alias of aliases) {
568
+ this.storeToken(alias, normalized);
569
+ }
570
+ }
571
+ this._loaded = true;
572
+ }
573
+ chains() {
574
+ return Array.from(this._chainsById.values());
575
+ }
576
+ chain(chainRef) {
577
+ const normalized = normalizeChainKey(chainRef);
578
+ const canonicalKey = this._chainAliases.get(normalized) ?? normalized;
579
+ return this._chainsById.get(canonicalKey);
580
+ }
581
+ allTokens() {
582
+ const unique = /* @__PURE__ */ new Map();
583
+ for (const list of this._tokensByChain.values()) {
584
+ for (const token of list) {
585
+ unique.set(`${token.chainId}:${token.address}`, token);
586
+ }
587
+ }
588
+ return Array.from(unique.values());
589
+ }
590
+ tokens(chainRef) {
591
+ return this._tokensByChain.get(normalizeChainKey(chainRef)) ?? [];
592
+ }
593
+ findToken(chainRef, address) {
594
+ const chain = this.chain(chainRef);
595
+ const chainType = normalizeChainType(chain);
596
+ const normalizedAddress = normalizeAddress(address, chainType);
597
+ return this.tokens(chainRef).find((token) => {
598
+ return normalizeAddress(token.address, chainType) === normalizedAddress;
599
+ });
600
+ }
601
+ resolveToken(chainRef, input) {
602
+ if (!input) return void 0;
603
+ const s = String(input).trim();
604
+ const chain = this.chain(chainRef);
605
+ const chainType = normalizeChainType(chain);
606
+ if (/^0x[0-9a-fA-F]{40}$/.test(s)) return s;
607
+ if (chainType === "solana" && s.length > 20) return s;
608
+ const nativeAddress = getNativeTokenAddress(chainType);
609
+ const nativeSymbol = chain?.nativeCurrency?.symbol?.toUpperCase?.();
610
+ if (nativeSymbol && s.toUpperCase() === nativeSymbol || ["ETH", "MATIC", "AVAX", "BNB", "SOL", "NATIVE"].includes(s.toUpperCase())) {
611
+ return chainType === "solana" ? nativeAddress : NATIVE;
612
+ }
613
+ const hit = this.tokens(chainRef).find((token) => {
614
+ if (!token.symbol) return false;
615
+ return token.symbol.toUpperCase() === s.toUpperCase();
616
+ });
617
+ if (hit) return hit.address;
618
+ return s;
619
+ }
620
+ };
621
+ }
622
+ });
623
+
624
+ // src/core.ts
625
+ var core_exports = {};
626
+ __export(core_exports, {
627
+ Trustware: () => Trustware
628
+ });
629
+ module.exports = __toCommonJS(core_exports);
630
+
631
+ // src/core/index.ts
632
+ init_store();
633
+
634
+ // src/wallets/eipWallets.ts
635
+ var CHAIN_PARAMS = {
636
+ 8453: {
637
+ chainIdHex: "0x2105",
638
+ chainName: "Base",
639
+ rpcUrls: ["https://mainnet.base.org"],
640
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
641
+ blockExplorerUrls: ["https://basescan.org"]
642
+ },
643
+ 42161: {
644
+ chainIdHex: "0xa4b1",
645
+ chainName: "Arbitrum One",
646
+ rpcUrls: ["https://arb1.arbitrum.io/rpc"],
647
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
648
+ blockExplorerUrls: ["https://arbiscan.io"]
649
+ },
650
+ 43114: {
651
+ chainIdHex: "0xa86a",
652
+ chainName: "Avalanche C-Chain",
653
+ rpcUrls: ["https://api.avax.network/ext/bc/C/rpc"],
654
+ nativeCurrency: { name: "Avalanche", symbol: "AVAX", decimals: 18 },
655
+ blockExplorerUrls: ["https://snowtrace.io"]
656
+ }
657
+ };
658
+ async function addThenSwitch(eth, chainId) {
659
+ const p = CHAIN_PARAMS[chainId];
660
+ if (!p) throw new Error(`Unknown chain ${chainId} (no params to add)`);
661
+ await eth.request({ method: "wallet_addEthereumChain", params: [p] });
662
+ await eth.request({
663
+ method: "wallet_switchEthereumChain",
664
+ params: [{ chainId: p.chainIdHex }]
665
+ });
666
+ }
667
+ function useEIP1193(eth) {
668
+ if (!eth?.request) throw new Error("useEIP1193: invalid provider");
669
+ let switching = false;
670
+ return {
671
+ ecosystem: "evm",
672
+ type: "eip1193",
673
+ async getAddress() {
674
+ const [a] = await eth.request({
675
+ method: "eth_requestAccounts"
676
+ });
677
+ if (!a) throw new Error("No connected address");
678
+ return a;
679
+ },
680
+ async getChainId() {
681
+ const hex = await eth.request({ method: "eth_chainId" });
682
+ return parseInt(String(hex), 16);
683
+ },
684
+ async switchChain(chainId) {
685
+ if (switching) return;
686
+ switching = true;
687
+ const hex = CHAIN_PARAMS[chainId]?.chainIdHex ?? `0x${chainId.toString(16)}`;
688
+ try {
689
+ await eth.request({
690
+ method: "wallet_switchEthereumChain",
691
+ params: [{ chainId: hex }]
692
+ });
693
+ } catch (e2) {
694
+ if (e2?.code === 4902) {
695
+ await addThenSwitch(eth, chainId);
696
+ } else if (e2?.code === 4001) {
697
+ } else {
698
+ throw e2;
699
+ }
700
+ } finally {
701
+ switching = false;
702
+ }
703
+ },
704
+ request: (args) => eth.request(args)
705
+ };
706
+ }
707
+
708
+ // src/wallets/solana.ts
709
+ var import_web3 = require("@solana/web3.js");
710
+ function getPublicKeyString(provider) {
711
+ const publicKey = provider?.publicKey;
712
+ if (!publicKey) return null;
713
+ const text = publicKey.toString().trim();
714
+ return text || null;
715
+ }
716
+ function decodeBase64(serializedTransaction) {
717
+ const trimmed = serializedTransaction.trim();
718
+ if (typeof Buffer !== "undefined") {
719
+ return Uint8Array.from(Buffer.from(trimmed, "base64"));
720
+ }
721
+ const binary = globalThis.atob(trimmed);
722
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
723
+ }
724
+ function decodeBase64Transaction(serializedTransaction) {
725
+ const bytes = decodeBase64(serializedTransaction);
726
+ try {
727
+ return import_web3.VersionedTransaction.deserialize(bytes);
728
+ } catch {
729
+ return import_web3.Transaction.from(bytes);
730
+ }
731
+ }
732
+ function bindSolanaProviderEvents(provider, handlers) {
733
+ const onConnect = () => handlers.onConnect?.();
734
+ const onAccountChanged = () => handlers.onAccountChanged?.();
735
+ const onDisconnect = () => handlers.onDisconnect?.();
736
+ provider.on?.("connect", onConnect);
737
+ provider.on?.("accountChanged", onAccountChanged);
738
+ provider.on?.("disconnect", onDisconnect);
739
+ return () => {
740
+ provider.off?.("connect", onConnect);
741
+ provider.off?.("accountChanged", onAccountChanged);
742
+ provider.off?.("disconnect", onDisconnect);
743
+ provider.removeListener?.("connect", onConnect);
744
+ provider.removeListener?.("accountChanged", onAccountChanged);
745
+ provider.removeListener?.("disconnect", onDisconnect);
746
+ };
747
+ }
748
+ function toSolanaWalletInterface(provider) {
749
+ return {
750
+ ecosystem: "solana",
751
+ type: "solana",
752
+ async getAddress() {
753
+ const current = getPublicKeyString(provider);
754
+ if (current) return current;
755
+ if (!provider.connect) {
756
+ throw new Error("Selected Solana wallet cannot connect");
757
+ }
758
+ await provider.connect();
759
+ const next = getPublicKeyString(provider);
760
+ if (!next) throw new Error("No connected Solana address");
761
+ return next;
762
+ },
763
+ async disconnect() {
764
+ await provider.disconnect?.();
765
+ },
766
+ async getChainKey() {
767
+ return "solana-mainnet-beta";
768
+ },
769
+ async sendSerializedTransaction(serializedTransactionBase64, rpcUrl) {
770
+ const transaction = decodeBase64Transaction(serializedTransactionBase64);
771
+ if (provider.signAndSendTransaction) {
772
+ const result = await provider.signAndSendTransaction(transaction, {
773
+ preflightCommitment: "confirmed"
774
+ });
775
+ if (typeof result === "string") return result;
776
+ if (result?.signature) return result.signature;
777
+ }
778
+ if (!provider.signTransaction) {
779
+ throw new Error("Connected Solana wallet cannot sign transactions");
780
+ }
781
+ const signed = await provider.signTransaction(transaction);
782
+ const connection = new import_web3.Connection(
783
+ rpcUrl?.trim() || "https://api.mainnet-beta.solana.com",
784
+ "confirmed"
785
+ );
786
+ const signature = await connection.sendRawTransaction(signed.serialize());
787
+ await connection.confirmTransaction(signature, "confirmed");
788
+ return signature;
789
+ }
790
+ };
791
+ }
792
+
793
+ // src/wallets/adapters.ts
794
+ function toWalletInterfaceFromDetected(dw) {
795
+ if (!dw?.provider) throw new Error("No provider on detected wallet");
796
+ if (dw.via === "solana-window" || dw.meta.ecosystem === "solana") {
797
+ return toSolanaWalletInterface(dw.provider);
798
+ }
799
+ const eth = dw.provider;
800
+ return useEIP1193(eth);
801
+ }
802
+
803
+ // src/wallets/connect.ts
804
+ function pickWagmiConnector(wagmi, metaName, metaId, metaCategory) {
805
+ const lower = metaName.toLowerCase();
806
+ const cons = wagmi.connectors();
807
+ return cons.find((c) => c.name.toLowerCase().includes(lower)) || metaId === "coinbase" && cons.find((c) => c.name.toLowerCase().includes("coinbase")) || metaId === "walletconnect" && cons.find((c) => (c.type ?? "").toLowerCase() === "walletconnect") || metaCategory === "injected" && cons.find((c) => (c.type ?? "").toLowerCase() === "injected") || null;
808
+ }
809
+ async function connectDetectedWallet(dw, opts) {
810
+ const { wagmi, touchAddress = true } = opts ?? {};
811
+ if (dw.meta.id === "walletconnect" || dw.via === "walletconnect") {
812
+ if (wagmi) {
813
+ const conn = pickWagmiConnector(
814
+ wagmi,
815
+ dw.meta.name,
816
+ dw.meta.id,
817
+ dw.meta.category
818
+ );
819
+ if (conn) {
820
+ await wagmi.connect(conn);
821
+ return { via: "wagmi", api: null };
822
+ }
823
+ }
824
+ throw new Error("WalletConnect connection failed. Please try again.");
825
+ }
826
+ if (dw.via === "solana-window" || dw.meta.ecosystem === "solana") {
827
+ const api2 = toWalletInterfaceFromDetected(dw);
828
+ if (touchAddress) await api2.getAddress();
829
+ return { via: "eip1193", api: api2 };
830
+ }
831
+ if (wagmi) {
832
+ const conn = pickWagmiConnector(
833
+ wagmi,
834
+ dw.meta.name,
835
+ dw.meta.id,
836
+ dw.meta.category
837
+ );
838
+ if (conn) {
839
+ await wagmi.connect(conn);
840
+ return { via: "wagmi", api: null };
841
+ }
842
+ }
843
+ const api = toWalletInterfaceFromDetected(dw);
844
+ if (touchAddress) await api.getAddress();
845
+ return { via: "eip1193", api };
846
+ }
847
+
848
+ // src/validation/address.ts
849
+ var import_viem = require("viem");
850
+
851
+ // node_modules/@solana/errors/dist/index.node.mjs
852
+ var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;
853
+ var SOLANA_ERROR__INVALID_NONCE = 2;
854
+ var SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;
855
+ var SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;
856
+ var SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;
857
+ var SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;
858
+ var SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;
859
+ var SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;
860
+ var SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;
861
+ var SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;
862
+ var SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;
863
+ var SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;
864
+ var SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;
865
+ var SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;
866
+ var SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;
867
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;
868
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;
869
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;
870
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;
871
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;
872
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;
873
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;
874
+ var SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;
875
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;
876
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;
877
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;
878
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;
879
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;
880
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;
881
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;
882
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;
883
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;
884
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;
885
+ var SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;
886
+ var SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 28e5;
887
+ var SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;
888
+ var SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;
889
+ var SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;
890
+ var SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;
891
+ var SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;
892
+ var SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;
893
+ var SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;
894
+ var SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;
895
+ var SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;
896
+ var SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;
897
+ var SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;
898
+ var SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 323e4;
899
+ var SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;
900
+ var SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;
901
+ var SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;
902
+ var SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;
903
+ var SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 361e4;
904
+ var SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;
905
+ var SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;
906
+ var SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;
907
+ var SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;
908
+ var SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;
909
+ var SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;
910
+ var SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;
911
+ var SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611e3;
912
+ var SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704e3;
913
+ var SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;
914
+ var SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;
915
+ var SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;
916
+ var SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;
917
+ var SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128e3;
918
+ var SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;
919
+ var SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;
920
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615e3;
921
+ var SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;
922
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;
923
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;
924
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;
925
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;
926
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;
927
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;
928
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;
929
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;
930
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;
931
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;
932
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;
933
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;
934
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;
935
+ var SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;
936
+ var SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;
937
+ var SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;
938
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;
939
+ var SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;
940
+ var SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;
941
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;
942
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;
943
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;
944
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;
945
+ var SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;
946
+ var SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;
947
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;
948
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;
949
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;
950
+ var SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;
951
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;
952
+ var SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;
953
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;
954
+ var SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;
955
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;
956
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;
957
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;
958
+ var SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;
959
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;
960
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;
961
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;
962
+ var SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;
963
+ var SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;
964
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;
965
+ var SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;
966
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;
967
+ var SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;
968
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;
969
+ var SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;
970
+ var SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;
971
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;
972
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;
973
+ var SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;
974
+ var SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;
975
+ var SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508e3;
976
+ var SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;
977
+ var SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;
978
+ var SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;
979
+ var SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;
980
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;
981
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;
982
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;
983
+ var SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;
984
+ var SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;
985
+ var SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;
986
+ var SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;
987
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED = 5607e3;
988
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE = 5607001;
989
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE = 5607002;
990
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH = 5607003;
991
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH = 5607004;
992
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO = 5607005;
993
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED = 5607006;
994
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH = 5607007;
995
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH = 5607008;
996
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY = 5607009;
997
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO = 5607010;
998
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING = 5607011;
999
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH = 5607012;
1000
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE = 5607013;
1001
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION = 5607014;
1002
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED = 5607015;
1003
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE = 5607016;
1004
+ var SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE = 5607017;
1005
+ var SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663e3;
1006
+ var SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;
1007
+ var SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;
1008
+ var SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;
1009
+ var SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;
1010
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;
1011
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;
1012
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;
1013
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;
1014
+ var SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;
1015
+ var SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;
1016
+ var SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;
1017
+ var SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;
1018
+ var SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;
1019
+ var SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;
1020
+ var SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;
1021
+ var SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;
1022
+ var SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;
1023
+ var SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;
1024
+ var SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;
1025
+ var SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;
1026
+ var SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;
1027
+ var SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;
1028
+ var SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 705e4;
1029
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;
1030
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;
1031
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;
1032
+ var SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;
1033
+ var SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;
1034
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;
1035
+ var SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;
1036
+ var SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;
1037
+ var SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;
1038
+ var SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;
1039
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;
1040
+ var SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;
1041
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;
1042
+ var SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;
1043
+ var SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;
1044
+ var SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;
1045
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;
1046
+ var SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;
1047
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;
1048
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;
1049
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;
1050
+ var SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;
1051
+ var SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;
1052
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;
1053
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;
1054
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;
1055
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;
1056
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;
1057
+ var SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;
1058
+ var SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;
1059
+ var SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;
1060
+ var SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;
1061
+ var SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;
1062
+ var SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;
1063
+ var SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;
1064
+ var SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;
1065
+ var SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618e3;
1066
+ var SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;
1067
+ var SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;
1068
+ var SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;
1069
+ var SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED = 7618004;
1070
+ var SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND = 7618005;
1071
+ var SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN = 7618006;
1072
+ var SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN = 7618007;
1073
+ var SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT = 7618008;
1074
+ var SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT = 7618009;
1075
+ var SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078e3;
1076
+ var SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;
1077
+ var SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;
1078
+ var SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;
1079
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;
1080
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;
1081
+ var SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;
1082
+ var SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;
1083
+ var SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;
1084
+ var SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;
1085
+ var SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;
1086
+ var SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;
1087
+ var SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;
1088
+ var SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;
1089
+ var SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;
1090
+ var SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;
1091
+ var SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;
1092
+ var SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;
1093
+ var SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;
1094
+ var SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;
1095
+ var SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;
1096
+ var SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;
1097
+ var SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;
1098
+ var SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;
1099
+ var SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 81e5;
1100
+ var SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;
1101
+ var SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;
1102
+ var SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;
1103
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 819e4;
1104
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;
1105
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;
1106
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;
1107
+ var SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;
1108
+ var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 99e5;
1109
+ var SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;
1110
+ var SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;
1111
+ var SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;
1112
+ var SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;
1113
+ var SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;
1114
+ var SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;
1115
+ function encodeValue(value) {
1116
+ if (Array.isArray(value)) {
1117
+ const commaSeparatedValues = value.map(encodeValue).join(
1118
+ "%2C%20"
1119
+ /* ", " */
1120
+ );
1121
+ return "%5B" + commaSeparatedValues + /* "]" */
1122
+ "%5D";
1123
+ } else if (typeof value === "bigint") {
1124
+ return `${value}n`;
1125
+ } else {
1126
+ return encodeURIComponent(
1127
+ String(
1128
+ value != null && Object.getPrototypeOf(value) === null ? (
1129
+ // Plain objects with no prototype don't have a `toString` method.
1130
+ // Convert them before stringifying them.
1131
+ { ...value }
1132
+ ) : value
1133
+ )
1134
+ );
1135
+ }
1136
+ }
1137
+ function encodeObjectContextEntry([key, value]) {
1138
+ return `${key}=${encodeValue(value)}`;
1139
+ }
1140
+ function encodeContextObject(context) {
1141
+ const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join("&");
1142
+ return Buffer.from(searchParamsString, "utf8").toString("base64");
1143
+ }
1144
+ var SolanaErrorMessages = {
1145
+ [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: "Account not found at address: $address",
1146
+ [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: "Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",
1147
+ [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: "Expected decoded account at address: $address",
1148
+ [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: "Failed to decode account data at address: $address",
1149
+ [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: "Accounts not found at addresses: $addresses",
1150
+ [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]: "Unable to find a viable program address bump seed.",
1151
+ [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: "$putativeAddress is not a base58-encoded address.",
1152
+ [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: "Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",
1153
+ [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: "The `CryptoKey` must be an `Ed25519` public key.",
1154
+ [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]: "$putativeOffCurveAddress is not a base58-encoded off-curve address.",
1155
+ [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: "Invalid seeds; point must fall off the Ed25519 curve.",
1156
+ [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]: "Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",
1157
+ [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: "A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",
1158
+ [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: "The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",
1159
+ [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: "Expected program derived address bump to be in the range [0, 255], got: $bump.",
1160
+ [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: "Program address cannot end with PDA marker.",
1161
+ [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",
1162
+ [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",
1163
+ [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: "The network has progressed past the last block for which this transaction could have been committed.",
1164
+ [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: "Codec [$codecDescription] cannot decode empty byte arrays.",
1165
+ [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: "Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",
1166
+ [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: "Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",
1167
+ [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: "Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",
1168
+ [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: "Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",
1169
+ [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]: "Encoder and decoder must either both be fixed-size or variable-size.",
1170
+ [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: "Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",
1171
+ [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: "Expected a fixed-size codec, got a variable-size one.",
1172
+ [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: "Codec [$codecDescription] expected a positive byte length, got $bytesLength.",
1173
+ [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: "Expected a variable-size codec, got a fixed-size one.",
1174
+ [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: "Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",
1175
+ [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: "Codec [$codecDescription] expected $expected bytes, got $bytesLength.",
1176
+ [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: "Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",
1177
+ [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: "Invalid discriminated union variant. Expected one of [$variants], got $value.",
1178
+ [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: "Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",
1179
+ [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: "Invalid literal union variant. Expected one of [$variants], got $value.",
1180
+ [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: "Expected [$codecDescription] to have $expected items, got $actual.",
1181
+ [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: "Invalid value $value for base $base with alphabet $alphabet.",
1182
+ [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: "Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",
1183
+ [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: "Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",
1184
+ [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: "Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",
1185
+ [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: "Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",
1186
+ [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: "Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",
1187
+ [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: "This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",
1188
+ [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: "No random values implementation could be found.",
1189
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: "instruction requires an uninitialized account",
1190
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]: "instruction tries to borrow reference for an account which is already borrowed",
1191
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: "instruction left account with an outstanding borrowed reference",
1192
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]: "program other than the account's owner changed the size of the account data",
1193
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: "account data too small for instruction",
1194
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: "instruction expected an executable account",
1195
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]: "An account does not have enough lamports to be rent-exempt",
1196
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: "Program arithmetic overflowed",
1197
+ [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: "Failed to serialize or deserialize account data: $encodedData",
1198
+ [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]: "Builtin programs must consume compute units",
1199
+ [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: "Cross-program invocation call depth too deep",
1200
+ [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: "Computational budget exceeded",
1201
+ [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: "custom program error: #$code",
1202
+ [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: "instruction contains duplicate accounts",
1203
+ [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]: "instruction modifications of multiply-passed account differ",
1204
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: "executable accounts must be rent exempt",
1205
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: "instruction changed executable accounts data",
1206
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]: "instruction changed the balance of an executable account",
1207
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: "instruction changed executable bit of an account",
1208
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]: "instruction modified data of an account it does not own",
1209
+ [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]: "instruction spent from the balance of an account it does not own",
1210
+ [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: "generic instruction error",
1211
+ [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: "Provided owner is not allowed",
1212
+ [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: "Account is immutable",
1213
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: "Incorrect authority provided",
1214
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: "incorrect program id for instruction",
1215
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: "insufficient funds for instruction",
1216
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: "invalid account data for instruction",
1217
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: "Invalid account owner",
1218
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: "invalid program argument",
1219
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: "program returned invalid error code",
1220
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: "invalid instruction data",
1221
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: "Failed to reallocate account data",
1222
+ [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: "Provided seeds do not result in a valid address",
1223
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]: "Accounts data allocations exceeded the maximum allowed per transaction",
1224
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: "Max accounts exceeded",
1225
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: "Max instruction trace length exceeded",
1226
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]: "Length of the seed is too long for address generation",
1227
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: "An account required by the instruction is missing",
1228
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: "missing required signature for instruction",
1229
+ [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]: "instruction illegally modified the program id of an account",
1230
+ [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: "insufficient account keys for instruction",
1231
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]: "Cross-program invocation with unauthorized signer or writable account",
1232
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]: "Failed to create program execution environment",
1233
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: "Program failed to compile",
1234
+ [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: "Program failed to complete",
1235
+ [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: "instruction modified data of a read-only account",
1236
+ [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]: "instruction changed the balance of a read-only account",
1237
+ [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]: "Cross-program invocation reentrancy not allowed for this instruction",
1238
+ [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: "instruction modified rent epoch of an account",
1239
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]: "sum of account balances before and after instruction do not match",
1240
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: "instruction requires an initialized account",
1241
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: "",
1242
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: "Unsupported program id",
1243
+ [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: "Unsupported sysvar",
1244
+ [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: "Invalid instruction plan kind: $kind.",
1245
+ [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: "The provided instruction plan is empty.",
1246
+ [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]: "No failed transaction plan result was found in the provided transaction plan result.",
1247
+ [SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]: "This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved \u2014 e.g. by targetting RPCs that support transaction bundles.",
1248
+ [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: "The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.",
1249
+ [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: "The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",
1250
+ [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: "Invalid transaction plan kind: $kind.",
1251
+ [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]: "No more instructions to pack; the message packer has completed the instruction plan.",
1252
+ [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]: "Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",
1253
+ [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]: "Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",
1254
+ [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]: "Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",
1255
+ [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]: "Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",
1256
+ [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: "The instruction does not have any accounts.",
1257
+ [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: "The instruction does not have any data.",
1258
+ [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: "Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",
1259
+ [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: "Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",
1260
+ [SOLANA_ERROR__INVALID_NONCE]: "The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",
1261
+ [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: "Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
1262
+ [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: "Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",
1263
+ [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]: "Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
1264
+ [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]: "Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
1265
+ [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: "Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
1266
+ [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: "JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",
1267
+ [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: "JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",
1268
+ [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: "JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",
1269
+ [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: "JSON-RPC error: The method does not exist / is not available ($__serverMessage)",
1270
+ [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: "JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",
1271
+ [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: "$__serverMessage",
1272
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: "$__serverMessage",
1273
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: "$__serverMessage",
1274
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: "$__serverMessage",
1275
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: "Epoch rewards period still active at slot $slot",
1276
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: "$__serverMessage",
1277
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: "$__serverMessage",
1278
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]: "Failed to query long-term storage; please try again",
1279
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: "Minimum context slot has not been reached",
1280
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: "Node is unhealthy; behind by $numSlotsBehind slots",
1281
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: "No snapshot",
1282
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: "Transaction simulation failed",
1283
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: "Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",
1284
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: "$__serverMessage",
1285
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]: "Transaction history is not available from this node",
1286
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: "$__serverMessage",
1287
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: "Transaction signature length mismatch",
1288
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]: "Transaction signature verification failure",
1289
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: "$__serverMessage",
1290
+ [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: "Key pair bytes must be of length 64, got $byteLength.",
1291
+ [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: "Expected private key bytes with length 32. Actual length: $actualLength.",
1292
+ [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: "Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",
1293
+ [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]: "The provided private key does not match the provided public key.",
1294
+ [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",
1295
+ [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: "Lamports value must be in the range [0, 2e64-1]",
1296
+ [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: "`$value` cannot be parsed as a `BigInt`",
1297
+ [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: "$message",
1298
+ [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: "`$value` cannot be parsed as a `Number`",
1299
+ [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: "No nonce account could be found at address `$nonceAccountAddress`",
1300
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]: "Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",
1301
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]: "Attempted to sign an offchain message with an address that is not a signer for it",
1302
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",
1303
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]: "The signer addresses in this offchain message envelope do not match the list of required signers in the message preamble. These unexpected signers were present in the envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope `[$missingSigners]`.",
1304
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]: "The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",
1305
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]: "Expected message format $expectedMessageFormat, got $actualMessageFormat",
1306
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]: "The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",
1307
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]: "Offchain message content must be non-empty",
1308
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]: "Offchain message must specify the address of at least one required signer",
1309
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]: "Offchain message envelope must reserve space for at least one signature",
1310
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]: "The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",
1311
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]: "The signatories of this offchain message must be listed in lexicographical order",
1312
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]: "An address must be listed no more than once among the signatories of an offchain message",
1313
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]: "Offchain message is missing signatures for addresses: $addresses.",
1314
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]: "Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",
1315
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]: "The message body provided contains characters whose codes fall outside the allowed range. In order to ensure clear-signing compatiblity with hardware wallets, the message may only contain line feeds and characters in the range [\\x20-\\x7e].",
1316
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]: "Expected offchain message version $expectedVersion. Got $actualVersion.",
1317
+ [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]: "This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",
1318
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: "The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",
1319
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]: "WebSocket was closed before payload could be added to the send buffer",
1320
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: "WebSocket connection closed",
1321
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: "WebSocket failed to connect",
1322
+ [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]: "Failed to obtain a subscription id from the server",
1323
+ [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: "Could not find an API plan for RPC method: `$method`",
1324
+ [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: "The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",
1325
+ [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: "HTTP error ($statusCode): $message",
1326
+ [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: "HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",
1327
+ [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: "Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",
1328
+ [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: "The provided value does not implement the `KeyPairSigner` interface",
1329
+ [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: "The provided value does not implement the `MessageModifyingSigner` interface",
1330
+ [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: "The provided value does not implement the `MessagePartialSigner` interface",
1331
+ [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: "The provided value does not implement any of the `MessageSigner` interfaces",
1332
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: "The provided value does not implement the `TransactionModifyingSigner` interface",
1333
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: "The provided value does not implement the `TransactionPartialSigner` interface",
1334
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: "The provided value does not implement the `TransactionSendingSigner` interface",
1335
+ [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: "The provided value does not implement any of the `TransactionSigner` interfaces",
1336
+ [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]: "More than one `TransactionSendingSigner` was identified.",
1337
+ [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]: "No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",
1338
+ [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]: "Wallet account signers do not support signing multiple messages/transactions in a single operation",
1339
+ [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: "Cannot export a non-extractable key.",
1340
+ [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: "No digest implementation could be found.",
1341
+ [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]: "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",
1342
+ [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]: "This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",
1343
+ [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]: "No signature verification implementation could be found.",
1344
+ [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: "No key generation implementation could be found.",
1345
+ [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: "No signing implementation could be found.",
1346
+ [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: "No key export implementation could be found.",
1347
+ [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: "Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",
1348
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: "Transaction processing left an account with an outstanding borrowed reference",
1349
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: "Account in use",
1350
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: "Account loaded twice",
1351
+ [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]: "Attempt to debit an account but found no record of a prior credit.",
1352
+ [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]: "Transaction loads an address table account that doesn't exist",
1353
+ [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: "This transaction has already been processed",
1354
+ [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: "Blockhash not found",
1355
+ [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: "Loader call chain is too deep",
1356
+ [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]: "Transactions are currently disabled due to cluster maintenance",
1357
+ [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: "Transaction contains a duplicate instruction ($index) that is not allowed",
1358
+ [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: "Insufficient funds for fee",
1359
+ [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: "Transaction results in an account ($accountIndex) with insufficient funds for rent",
1360
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: "This account may not be used to pay transaction fees",
1361
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: "Transaction contains an invalid account reference",
1362
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]: "Transaction loads an address table account with invalid data",
1363
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]: "Transaction address table lookup uses an invalid index",
1364
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]: "Transaction loads an address table account with an invalid owner",
1365
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]: "LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",
1366
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]: "This program may not be used for executing instructions",
1367
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]: "Transaction leaves an account with a lower balance than rent-exempt minimum",
1368
+ [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]: "Transaction loads a writable account that cannot be written",
1369
+ [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]: "Transaction exceeded max loaded accounts data size cap",
1370
+ [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]: "Transaction requires a fee but has no signature present",
1371
+ [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: "Attempt to load a program that does not exist",
1372
+ [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: "Execution of the program referenced by account at index $accountIndex is temporarily restricted.",
1373
+ [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: "ResanitizationNeeded",
1374
+ [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: "Transaction failed to sanitize accounts offsets correctly",
1375
+ [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: "Transaction did not pass signature verification",
1376
+ [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: "Transaction locked too many accounts",
1377
+ [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]: "Sum of account balances before and after transaction do not match",
1378
+ [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: "The transaction failed with the error `$errorName`",
1379
+ [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: "Transaction version is unsupported",
1380
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]: "Transaction would exceed account data limit within the block",
1381
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]: "Transaction would exceed total account data limit",
1382
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]: "Transaction would exceed max account limit within the block",
1383
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]: "Transaction would exceed max Block Cost Limit",
1384
+ [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: "Transaction would exceed max Vote Cost Limit",
1385
+ [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: "Attempted to sign a transaction with an address that is not a signer for it",
1386
+ [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: "Transaction is missing an address at index: $index.",
1387
+ [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]: "Transaction has no expected signers therefore it cannot be encoded",
1388
+ [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: "Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",
1389
+ [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: "Transaction does not have a blockhash lifetime",
1390
+ [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: "Transaction is not a durable nonce transaction",
1391
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: "Contents of these address lookup tables unknown: $lookupTableAddresses",
1392
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: "Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",
1393
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: "No fee payer set in CompiledTransaction",
1394
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: "Could not find program address at index $index",
1395
+ [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]: "Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",
1396
+ [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: "Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",
1397
+ [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: "Transaction is missing a fee payer.",
1398
+ [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]: "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",
1399
+ [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]: "Transaction first instruction is not advance nonce account instruction.",
1400
+ [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]: "Transaction with no instructions cannot be durable nonce transaction.",
1401
+ [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: "This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",
1402
+ [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: "This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",
1403
+ [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: "The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",
1404
+ [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: "Transaction is missing signatures for addresses: $addresses.",
1405
+ [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: "Transaction version must be in the range [0, 127]. `$actualVersion` given",
1406
+ [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: "This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",
1407
+ [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: "The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."
1408
+ };
1409
+ var START_INDEX = "i";
1410
+ var TYPE = "t";
1411
+ function getHumanReadableErrorMessage(code, context = {}) {
1412
+ const messageFormatString = SolanaErrorMessages[code];
1413
+ if (messageFormatString.length === 0) {
1414
+ return "";
1415
+ }
1416
+ let state;
1417
+ function commitStateUpTo(endIndex) {
1418
+ if (state[TYPE] === 2) {
1419
+ const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);
1420
+ fragments.push(
1421
+ variableName in context ? (
1422
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1423
+ `${context[variableName]}`
1424
+ ) : `$${variableName}`
1425
+ );
1426
+ } else if (state[TYPE] === 1) {
1427
+ fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));
1428
+ }
1429
+ }
1430
+ const fragments = [];
1431
+ messageFormatString.split("").forEach((char, ii) => {
1432
+ if (ii === 0) {
1433
+ state = {
1434
+ [START_INDEX]: 0,
1435
+ [TYPE]: messageFormatString[0] === "\\" ? 0 : messageFormatString[0] === "$" ? 2 : 1
1436
+ /* Text */
1437
+ };
1438
+ return;
1439
+ }
1440
+ let nextState;
1441
+ switch (state[TYPE]) {
1442
+ case 0:
1443
+ nextState = {
1444
+ [START_INDEX]: ii,
1445
+ [TYPE]: 1
1446
+ /* Text */
1447
+ };
1448
+ break;
1449
+ case 1:
1450
+ if (char === "\\") {
1451
+ nextState = {
1452
+ [START_INDEX]: ii,
1453
+ [TYPE]: 0
1454
+ /* EscapeSequence */
1455
+ };
1456
+ } else if (char === "$") {
1457
+ nextState = {
1458
+ [START_INDEX]: ii,
1459
+ [TYPE]: 2
1460
+ /* Variable */
1461
+ };
1462
+ }
1463
+ break;
1464
+ case 2:
1465
+ if (char === "\\") {
1466
+ nextState = {
1467
+ [START_INDEX]: ii,
1468
+ [TYPE]: 0
1469
+ /* EscapeSequence */
1470
+ };
1471
+ } else if (char === "$") {
1472
+ nextState = {
1473
+ [START_INDEX]: ii,
1474
+ [TYPE]: 2
1475
+ /* Variable */
1476
+ };
1477
+ } else if (!char.match(/\w/)) {
1478
+ nextState = {
1479
+ [START_INDEX]: ii,
1480
+ [TYPE]: 1
1481
+ /* Text */
1482
+ };
1483
+ }
1484
+ break;
1485
+ }
1486
+ if (nextState) {
1487
+ if (state !== nextState) {
1488
+ commitStateUpTo(ii);
1489
+ }
1490
+ state = nextState;
1491
+ }
1492
+ });
1493
+ commitStateUpTo();
1494
+ return fragments.join("");
1495
+ }
1496
+ function getErrorMessage(code, context = {}) {
1497
+ if (process.env.NODE_ENV !== "production") {
1498
+ return getHumanReadableErrorMessage(code, context);
1499
+ } else {
1500
+ let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;
1501
+ if (Object.keys(context).length) {
1502
+ decodingAdviceMessage += ` '${encodeContextObject(context)}'`;
1503
+ }
1504
+ return `${decodingAdviceMessage}\``;
1505
+ }
1506
+ }
1507
+ var SolanaError = class extends Error {
1508
+ constructor(...[code, contextAndErrorOptions]) {
1509
+ let context;
1510
+ let errorOptions;
1511
+ if (contextAndErrorOptions) {
1512
+ Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {
1513
+ if (name === "cause") {
1514
+ errorOptions = { cause: descriptor.value };
1515
+ } else {
1516
+ if (context === void 0) {
1517
+ context = {
1518
+ __code: code
1519
+ };
1520
+ }
1521
+ Object.defineProperty(context, name, descriptor);
1522
+ }
1523
+ });
1524
+ }
1525
+ const message = getErrorMessage(code, context);
1526
+ super(message, errorOptions);
1527
+ /**
1528
+ * Indicates the root cause of this {@link SolanaError}, if any.
1529
+ *
1530
+ * For example, a transaction error might have an instruction error as its root cause. In this
1531
+ * case, you will be able to access the instruction error on the transaction error as `cause`.
1532
+ */
1533
+ __publicField(this, "cause", this.cause);
1534
+ /**
1535
+ * Contains context that can assist in understanding or recovering from a {@link SolanaError}.
1536
+ */
1537
+ __publicField(this, "context");
1538
+ this.context = Object.freeze(
1539
+ context === void 0 ? {
1540
+ __code: code
1541
+ } : context
1542
+ );
1543
+ this.name = "SolanaError";
1544
+ }
1545
+ };
1546
+
1547
+ // node_modules/@solana/codecs-core/dist/index.node.mjs
1548
+ function getEncodedSize(value, encoder) {
1549
+ return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
1550
+ }
1551
+ function createEncoder(encoder) {
1552
+ return Object.freeze({
1553
+ ...encoder,
1554
+ encode: (value) => {
1555
+ const bytes = new Uint8Array(getEncodedSize(value, encoder));
1556
+ encoder.write(value, bytes, 0);
1557
+ return bytes;
1558
+ }
1559
+ });
1560
+ }
1561
+
1562
+ // node_modules/@solana/codecs-strings/dist/index.node.mjs
1563
+ function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
1564
+ if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
1565
+ throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
1566
+ alphabet: alphabet4,
1567
+ base: alphabet4.length,
1568
+ value: givenValue
1569
+ });
1570
+ }
1571
+ }
1572
+ var getBaseXEncoder = (alphabet4) => {
1573
+ return createEncoder({
1574
+ getSizeFromValue: (value) => {
1575
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
1576
+ if (!tailChars) return value.length;
1577
+ const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
1578
+ return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
1579
+ },
1580
+ write(value, bytes, offset) {
1581
+ assertValidBaseString(alphabet4, value);
1582
+ if (value === "") return offset;
1583
+ const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
1584
+ if (!tailChars) {
1585
+ bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
1586
+ return offset + leadingZeroes.length;
1587
+ }
1588
+ let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
1589
+ const tailBytes = [];
1590
+ while (base10Number > 0n) {
1591
+ tailBytes.unshift(Number(base10Number % 256n));
1592
+ base10Number /= 256n;
1593
+ }
1594
+ const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
1595
+ bytes.set(bytesToAdd, offset);
1596
+ return offset + bytesToAdd.length;
1597
+ }
1598
+ });
1599
+ };
1600
+ function partitionLeadingZeroes(value, zeroCharacter) {
1601
+ const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));
1602
+ return [leadingZeros, tailChars];
1603
+ }
1604
+ function getBigIntFromBaseX(value, alphabet4) {
1605
+ const base = BigInt(alphabet4.length);
1606
+ let sum = 0n;
1607
+ for (const char of value) {
1608
+ sum *= base;
1609
+ sum += BigInt(alphabet4.indexOf(char));
1610
+ }
1611
+ return sum;
1612
+ }
1613
+ var alphabet2 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1614
+ var getBase58Encoder = () => getBaseXEncoder(alphabet2);
1615
+ var e = globalThis.TextDecoder;
1616
+ var o = globalThis.TextEncoder;
1617
+
1618
+ // node_modules/@solana/addresses/dist/index.node.mjs
1619
+ var memoizedBase58Encoder;
1620
+ function getMemoizedBase58Encoder() {
1621
+ if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();
1622
+ return memoizedBase58Encoder;
1623
+ }
1624
+ function isAddress(putativeAddress) {
1625
+ if (
1626
+ // Lowest address (32 bytes of zeroes)
1627
+ putativeAddress.length < 32 || // Highest address (32 bytes of 255)
1628
+ putativeAddress.length > 44
1629
+ ) {
1630
+ return false;
1631
+ }
1632
+ const base58Encoder = getMemoizedBase58Encoder();
1633
+ try {
1634
+ return base58Encoder.encode(putativeAddress).byteLength === 32;
1635
+ } catch {
1636
+ return false;
1637
+ }
1638
+ }
1639
+
1640
+ // src/validation/address.ts
1641
+ init_chains();
1642
+ var BECH32_CHARSET = /^[023456789acdefghjklmnpqrstuvwxyz]+$/i;
1643
+ function hasMixedCase(value) {
1644
+ return value !== value.toLowerCase() && value !== value.toUpperCase();
1645
+ }
1646
+ function validateBech32LikeAddress(address, prefix) {
1647
+ const trimmed = address.trim();
1648
+ if (!trimmed) {
1649
+ return { isValid: false, error: "Address is required." };
1650
+ }
1651
+ if (hasMixedCase(trimmed)) {
1652
+ return { isValid: false, error: "Bech32 addresses cannot mix case." };
1653
+ }
1654
+ const lower = trimmed.toLowerCase();
1655
+ const expectedPrefix = `${prefix.toLowerCase()}1`;
1656
+ if (!lower.startsWith(expectedPrefix)) {
1657
+ return {
1658
+ isValid: false,
1659
+ error: `Address must start with ${expectedPrefix}.`
1660
+ };
1661
+ }
1662
+ const dataPart = lower.slice(expectedPrefix.length);
1663
+ if (dataPart.length < 6 || !BECH32_CHARSET.test(dataPart)) {
1664
+ return {
1665
+ isValid: false,
1666
+ error: "Bech32 address format is invalid."
1667
+ };
1668
+ }
1669
+ return { isValid: true };
1670
+ }
1671
+ function validateEvmAddress(address) {
1672
+ if (!(0, import_viem.isAddress)(address.trim())) {
1673
+ return {
1674
+ isValid: false,
1675
+ error: "EVM addresses must be 0x-prefixed 20-byte hex strings."
1676
+ };
1677
+ }
1678
+ return { isValid: true };
1679
+ }
1680
+ function validateSeiAddress(address) {
1681
+ const trimmed = address.trim();
1682
+ if ((0, import_viem.isAddress)(trimmed)) {
1683
+ return { isValid: true };
1684
+ }
1685
+ const result = validateBech32LikeAddress(trimmed, "sei");
1686
+ if (result.isValid) return result;
1687
+ return {
1688
+ isValid: false,
1689
+ error: "SEI addresses must be 0x-prefixed EVM or sei1 bech32 strings."
1690
+ };
1691
+ }
1692
+ function validateSolanaAddress(address) {
1693
+ const trimmed = address.trim();
1694
+ if (trimmed.startsWith("0x") || (0, import_viem.isAddress)(trimmed)) {
1695
+ return {
1696
+ isValid: false,
1697
+ error: "Solana addresses must be base58-encoded strings."
1698
+ };
1699
+ }
1700
+ if (trimmed.toLowerCase().startsWith("bc1") || trimmed.toLowerCase().startsWith("sei1")) {
1701
+ return {
1702
+ isValid: false,
1703
+ error: "Solana addresses cannot be bech32 strings."
1704
+ };
1705
+ }
1706
+ if (!isAddress(trimmed)) {
1707
+ return {
1708
+ isValid: false,
1709
+ error: "Solana addresses must be base58-encoded strings."
1710
+ };
1711
+ }
1712
+ return { isValid: true };
1713
+ }
1714
+ function validateBtcAddress(address) {
1715
+ const trimmed = address.trim();
1716
+ if (hasMixedCase(trimmed)) {
1717
+ return { isValid: false, error: "Bitcoin addresses cannot mix case." };
1718
+ }
1719
+ const result = validateBech32LikeAddress(trimmed, "bc");
1720
+ if (result.isValid) return result;
1721
+ return {
1722
+ isValid: false,
1723
+ error: "Bitcoin addresses must use native SegWit (bc1...) format."
1724
+ };
1725
+ }
1726
+ function validateAddressForChain(address, chain) {
1727
+ const trimmed = address.trim();
1728
+ if (!trimmed) return { isValid: true };
1729
+ const chainType = normalizeChainType(chain);
1730
+ const chainDef = typeof chain === "object" && chain ? chain : void 0;
1731
+ switch (chainType) {
1732
+ case "evm":
1733
+ return validateEvmAddress(trimmed);
1734
+ case "solana":
1735
+ return validateSolanaAddress(trimmed);
1736
+ case "bitcoin":
1737
+ return validateBtcAddress(trimmed);
1738
+ case "cosmos":
1739
+ if (chainDef?.networkIdentifier?.toLowerCase() === "sei") {
1740
+ return validateSeiAddress(trimmed);
1741
+ }
1742
+ return validateBech32LikeAddress(trimmed, "sei");
1743
+ default:
1744
+ return { isValid: false, error: "Unsupported or unknown chain type." };
1745
+ }
1746
+ }
1747
+ function validateAddressForRouteChain(address, chainType) {
1748
+ switch (normalizeChainType(chainType)) {
1749
+ case "evm":
1750
+ return validateEvmAddress(address);
1751
+ case "solana":
1752
+ return validateSolanaAddress(address);
1753
+ case "bitcoin":
1754
+ return validateBtcAddress(address);
1755
+ case "cosmos":
1756
+ return validateSeiAddress(address);
1757
+ default:
1758
+ return { isValid: false, error: "Unsupported chain type." };
1759
+ }
1760
+ }
1761
+ function validateRouteAddresses(params) {
1762
+ const fromType = normalizeChainType(params.fromChain);
1763
+ const toType = normalizeChainType(params.toChain);
1764
+ if (!fromType || !toType) {
1765
+ return {
1766
+ isValid: false,
1767
+ error: "Missing chain types for route validation."
1768
+ };
1769
+ }
1770
+ const fromAddress = params.fromAddress.trim();
1771
+ const toAddress = params.toAddress.trim();
1772
+ if (!fromAddress || !toAddress) {
1773
+ return { isValid: false, error: "Route addresses are required." };
1774
+ }
1775
+ const normalizedDirection = params.direction?.trim().toLowerCase();
1776
+ const isDepositFlow = normalizedDirection === "deposit" || (toType === "evm" || toType === "cosmos") && (fromType === "bitcoin" || fromType === "solana");
1777
+ if (isDepositFlow) {
1778
+ const fromResult2 = validateAddressForRouteChain(fromAddress, fromType);
1779
+ if (!fromResult2.isValid) {
1780
+ return {
1781
+ isValid: false,
1782
+ error: `From address: ${fromResult2.error ?? "Invalid address."}`
1783
+ };
1784
+ }
1785
+ const toResult2 = toType === "cosmos" ? validateSeiAddress(toAddress) : validateEvmAddress(toAddress);
1786
+ if (!toResult2.isValid) {
1787
+ return {
1788
+ isValid: false,
1789
+ error: `To address: ${toResult2.error ?? "Invalid address."}`
1790
+ };
1791
+ }
1792
+ if (fromType === "bitcoin") {
1793
+ const refundAddress = params.refundAddress?.trim();
1794
+ if (!refundAddress) {
1795
+ return {
1796
+ isValid: false,
1797
+ error: "Refund address is required for BTC deposit routes."
1798
+ };
1799
+ }
1800
+ const refundResult = validateBtcAddress(refundAddress);
1801
+ if (!refundResult.isValid) {
1802
+ return {
1803
+ isValid: false,
1804
+ error: `Refund address: ${refundResult.error ?? "Invalid address."}`
1805
+ };
1806
+ }
1807
+ }
1808
+ return { isValid: true };
1809
+ }
1810
+ const fromResult = validateAddressForRouteChain(fromAddress, fromType);
1811
+ if (!fromResult.isValid) {
1812
+ return {
1813
+ isValid: false,
1814
+ error: `From address: ${fromResult.error ?? "Invalid address."}`
1815
+ };
1816
+ }
1817
+ const toResult = validateAddressForRouteChain(toAddress, toType);
1818
+ if (!toResult.isValid) {
1819
+ return {
1820
+ isValid: false,
1821
+ error: `To address: ${toResult.error ?? "Invalid address."}`
1822
+ };
1823
+ }
1824
+ return { isValid: true };
1825
+ }
1826
+
1827
+ // src/identity/index.ts
1828
+ init_chains();
1829
+ function normalizeIdentityChainId(chain) {
1830
+ if (!chain || typeof chain === "string") return void 0;
1831
+ const raw = chain.chainId ?? chain.id;
1832
+ if (raw === void 0 || raw === null) return void 0;
1833
+ const normalized = String(raw).trim();
1834
+ return normalized || void 0;
1835
+ }
1836
+ function identityEntryMatchesChain(entry, chainType, chainKey, chainId) {
1837
+ if (chainKey && entry.chainKey && entry.chainKey === chainKey) return true;
1838
+ if (chainId && entry.chainId && entry.chainId === chainId) return true;
1839
+ if (chainType && entry.chainType === chainType) return true;
1840
+ return false;
1841
+ }
1842
+ function createWalletIdentity(addresses = []) {
1843
+ return { addresses };
1844
+ }
1845
+ function upsertWalletIdentityAddress(identity, next) {
1846
+ const normalizedAddress = next.address.trim();
1847
+ const normalizedChainKey = next.chainKey ? normalizeChainKey(next.chainKey) : void 0;
1848
+ const normalizedChainId = next.chainId?.trim() || void 0;
1849
+ const addresses = identity.addresses.filter((entry) => {
1850
+ if (entry.chainType !== next.chainType) return true;
1851
+ if (normalizedChainKey && entry.chainKey === normalizedChainKey)
1852
+ return false;
1853
+ if (normalizedChainId && entry.chainId === normalizedChainId) return false;
1854
+ if (!normalizedChainKey && !normalizedChainId) return false;
1855
+ return true;
1856
+ });
1857
+ if (!normalizedAddress) return createWalletIdentity(addresses);
1858
+ return createWalletIdentity([
1859
+ ...addresses,
1860
+ {
1861
+ ...next,
1862
+ address: normalizedAddress,
1863
+ chainKey: normalizedChainKey,
1864
+ chainId: normalizedChainId
1865
+ }
1866
+ ]);
1867
+ }
1868
+ function resolveWalletAddressForChain(identity, chain) {
1869
+ const chainType = normalizeChainType(chain);
1870
+ const chainDef = typeof chain === "object" && chain ? chain : void 0;
1871
+ const chainKey = chainDef ? normalizeChainKey(
1872
+ chainDef.networkIdentifier ?? chainDef.chainId ?? chainDef.id
1873
+ ) : typeof chain === "string" ? normalizeChainKey(chain) : void 0;
1874
+ const chainId = normalizeIdentityChainId(chain);
1875
+ if (!chainType) {
1876
+ return {
1877
+ status: "missing",
1878
+ reason: "unknown_chain_type",
1879
+ chainKey,
1880
+ chainId
1881
+ };
1882
+ }
1883
+ const match = identity.addresses.find(
1884
+ (entry) => identityEntryMatchesChain(entry, chainType, chainKey, chainId)
1885
+ );
1886
+ if (!match) {
1887
+ return {
1888
+ status: "missing",
1889
+ reason: "missing_chain_address",
1890
+ chainType,
1891
+ chainKey,
1892
+ chainId
1893
+ };
1894
+ }
1895
+ const validation = validateAddressForChain(
1896
+ match.address,
1897
+ chainDef ?? chainType
1898
+ );
1899
+ if (!validation.isValid) {
1900
+ return {
1901
+ status: "invalid",
1902
+ reason: validation.error ?? "invalid_chain_address",
1903
+ address: match.address,
1904
+ source: match.source,
1905
+ chainType,
1906
+ chainKey,
1907
+ chainId
1908
+ };
1909
+ }
1910
+ return {
1911
+ status: "resolved",
1912
+ address: match.address.trim(),
1913
+ source: match.source,
1914
+ chainType,
1915
+ chainKey,
1916
+ chainId
1917
+ };
1918
+ }
1919
+ function buildWalletIdentityAddress(params) {
1920
+ const chainType = normalizeChainType(params.chain);
1921
+ if (!chainType) return null;
1922
+ const address = params.address.trim();
1923
+ const chainId = normalizeIdentityChainId(params.chain);
1924
+ const chainDef = typeof params.chain === "object" && params.chain ? params.chain : void 0;
1925
+ const chainKey = chainDef ? normalizeChainKey(
1926
+ chainDef.networkIdentifier ?? chainDef.chainId ?? chainDef.id
1927
+ ) : void 0;
1928
+ return {
1929
+ address,
1930
+ chainType,
1931
+ chainId,
1932
+ chainKey,
1933
+ providerId: params.providerId,
1934
+ source: params.source
1935
+ };
1936
+ }
1937
+ var IdentityStore = class {
1938
+ constructor() {
1939
+ this._identity = createWalletIdentity();
1940
+ }
1941
+ get snapshot() {
1942
+ return this._identity;
1943
+ }
1944
+ reset() {
1945
+ this._identity = createWalletIdentity();
1946
+ }
1947
+ upsert(next) {
1948
+ this._identity = upsertWalletIdentityAddress(this._identity, next);
1949
+ return this._identity;
1950
+ }
1951
+ resolve(chain) {
1952
+ return resolveWalletAddressForChain(this._identity, chain);
1953
+ }
1954
+ };
1955
+
1956
+ // src/wallets/manager.ts
1957
+ var import_react = require("react");
1958
+ var WalletManager = class {
1959
+ constructor() {
1960
+ this._status = "idle";
1961
+ this._wallet = null;
1962
+ this._detected = [];
1963
+ this._listeners = /* @__PURE__ */ new Set();
1964
+ this._identity = new IdentityStore();
1965
+ this._providerCleanup = null;
1966
+ this._connectedWalletId = null;
1967
+ }
1968
+ get status() {
1969
+ return this._status;
1970
+ }
1971
+ get error() {
1972
+ return this._error;
1973
+ }
1974
+ get detected() {
1975
+ return this._detected;
1976
+ }
1977
+ get wallet() {
1978
+ return this._wallet;
1979
+ }
1980
+ get simple() {
1981
+ if (!this._wallet) return null;
1982
+ const { getAddress, disconnect } = this._wallet;
1983
+ return { getAddress, disconnect };
1984
+ }
1985
+ get identity() {
1986
+ return this._identity.snapshot;
1987
+ }
1988
+ get connectedWalletId() {
1989
+ return this._connectedWalletId;
1990
+ }
1991
+ onChange(fn) {
1992
+ this._listeners.add(fn);
1993
+ return () => this._listeners.delete(fn);
1994
+ }
1995
+ emit() {
1996
+ for (const fn of this._listeners) fn(this._status);
1997
+ }
1998
+ /** Provide detection results (from your hook or custom function). */
1999
+ setDetected(list) {
2000
+ this._detected = list;
2001
+ }
2002
+ /** Optional: auto attach to the first/best detected wallet. */
2003
+ async autoAttach(opts) {
2004
+ if (!this._detected.length) return;
2005
+ const target = (opts?.pick ?? ((l) => l[0]))(this._detected);
2006
+ if (!target) return;
2007
+ await this.connectDetected(target, opts);
2008
+ }
2009
+ async connectDetected(target, opts) {
2010
+ if (this._status === "connected" && this._connectedWalletId === target.meta.id && this._wallet) {
2011
+ this.emit();
2012
+ return;
2013
+ }
2014
+ this._status = "connecting";
2015
+ this.clearConnectedWalletState();
2016
+ this.emit();
2017
+ try {
2018
+ const { api } = await connectDetectedWallet(target, {
2019
+ wagmi: opts?.wagmi
2020
+ });
2021
+ if (api) {
2022
+ this._wallet = api;
2023
+ this._connectedWalletId = target.meta.id;
2024
+ this.bindProviderEvents(target);
2025
+ await this.syncIdentityFromWallet(target.meta.id);
2026
+ }
2027
+ this._status = "connected";
2028
+ } catch (e2) {
2029
+ this._error = e2;
2030
+ this._status = "error";
2031
+ this.clearConnectedWalletState();
2032
+ } finally {
2033
+ this.emit();
2034
+ }
2035
+ }
2036
+ async disconnect(wagmi) {
2037
+ if (wagmi) await wagmi.disconnect().catch(() => {
2038
+ });
2039
+ if (this._wallet?.disconnect) {
2040
+ await this._wallet.disconnect().catch(() => {
2041
+ });
2042
+ }
2043
+ this.clearConnectedWalletState();
2044
+ this._status = "idle";
2045
+ this.emit();
2046
+ }
2047
+ /** Directly attach a pre-provided wallet interface (from old provider prop). */
2048
+ attachWallet(api) {
2049
+ this.clearConnectedWalletState();
2050
+ this._wallet = api;
2051
+ this._connectedWalletId = null;
2052
+ this._status = "connected";
2053
+ void this.syncIdentityFromWallet();
2054
+ this.emit();
2055
+ }
2056
+ /** Optional helper to set explicit status (e.g., "initializing" UX). */
2057
+ setStatus(s) {
2058
+ this._status = s;
2059
+ this.emit();
2060
+ }
2061
+ addIdentityAddress(address) {
2062
+ this._identity.upsert(address);
2063
+ }
2064
+ resolveAddressForChain(chain) {
2065
+ return this._identity.resolve(chain);
2066
+ }
2067
+ clearProviderCleanup() {
2068
+ this._providerCleanup?.();
2069
+ this._providerCleanup = null;
2070
+ }
2071
+ clearConnectedWalletState() {
2072
+ this.clearProviderCleanup();
2073
+ this._wallet = null;
2074
+ this._connectedWalletId = null;
2075
+ }
2076
+ bindProviderEvents(target) {
2077
+ if (!target.provider) return;
2078
+ if (target.via === "solana-window") {
2079
+ this._providerCleanup = bindSolanaProviderEvents(target.provider, {
2080
+ onConnect: () => {
2081
+ this._status = "connected";
2082
+ void this.syncIdentityFromWallet(target.meta.id);
2083
+ this.emit();
2084
+ },
2085
+ onAccountChanged: () => {
2086
+ void this.syncIdentityFromWallet(target.meta.id);
2087
+ this.emit();
2088
+ },
2089
+ onDisconnect: () => {
2090
+ this.clearConnectedWalletState();
2091
+ this._status = "idle";
2092
+ this.emit();
2093
+ }
2094
+ });
2095
+ return;
2096
+ }
2097
+ const provider = target.provider;
2098
+ const onAccountsChanged = (accounts) => {
2099
+ const nextAccounts = Array.isArray(accounts) ? accounts : [];
2100
+ if (nextAccounts.length === 0) {
2101
+ this.clearConnectedWalletState();
2102
+ this._status = "idle";
2103
+ this.emit();
2104
+ return;
2105
+ }
2106
+ this._status = "connected";
2107
+ void this.syncIdentityFromWallet(target.meta.id);
2108
+ this.emit();
2109
+ };
2110
+ const onDisconnect = () => {
2111
+ this.clearConnectedWalletState();
2112
+ this._status = "idle";
2113
+ this.emit();
2114
+ };
2115
+ provider.on?.("accountsChanged", onAccountsChanged);
2116
+ provider.on?.("disconnect", onDisconnect);
2117
+ this._providerCleanup = () => {
2118
+ provider.off?.("accountsChanged", onAccountsChanged);
2119
+ provider.off?.("disconnect", onDisconnect);
2120
+ provider.removeListener?.("accountsChanged", onAccountsChanged);
2121
+ provider.removeListener?.("disconnect", onDisconnect);
2122
+ };
2123
+ }
2124
+ async syncIdentityFromWallet(providerId) {
2125
+ if (!this._wallet) return;
2126
+ try {
2127
+ const address = await this._wallet.getAddress();
2128
+ const chain = this._wallet.ecosystem === "evm" ? { chainId: String(await this._wallet.getChainId()), type: "evm" } : {
2129
+ chainId: "solana-mainnet-beta",
2130
+ networkIdentifier: "solana-mainnet-beta",
2131
+ type: "solana"
2132
+ };
2133
+ const identityAddress = buildWalletIdentityAddress({
2134
+ address,
2135
+ chain,
2136
+ source: "provider",
2137
+ providerId
2138
+ });
2139
+ if (identityAddress) {
2140
+ this._identity.upsert(identityAddress);
2141
+ }
2142
+ } catch {
2143
+ }
2144
+ }
2145
+ };
2146
+ var walletManager = new WalletManager();
2147
+
2148
+ // src/core/routes.ts
2149
+ init_http();
2150
+ init_store();
2151
+ function isEvmTxRequest(txReq) {
2152
+ return Boolean(txReq?.data && (txReq.to || txReq.target));
2153
+ }
2154
+ function isSerializedSolanaTxRequest(txReq) {
2155
+ return Boolean(txReq?.data && !txReq?.to && !txReq?.target);
2156
+ }
2157
+ async function buildRoute(body, signal) {
2158
+ const addressValidation = validateRouteAddresses({
2159
+ fromChain: body.fromChain,
2160
+ toChain: body.toChain,
2161
+ fromAddress: body.fromAddress,
2162
+ toAddress: body.toAddress,
2163
+ refundAddress: body.refundAddress,
2164
+ direction: body.direction
2165
+ });
2166
+ if (!addressValidation.isValid) {
2167
+ throw new Error(addressValidation.error || "Invalid route addresses.");
2168
+ }
2169
+ const cfg = TrustwareConfigStore.get();
2170
+ const url = `${apiBase()}/v1/routes/route`;
2171
+ const payload = {
2172
+ ...body,
2173
+ slippageBps: body.slippageBps ?? (body.slippage === void 0 ? void 0 : Math.round(body.slippage * 100)),
2174
+ fromAmountUSD: body.fromAmountUSD ?? body.fromAmountUsd
2175
+ };
2176
+ const r = await rateLimitedFetch(url, {
2177
+ method: "POST",
2178
+ headers: { "Content-Type": "application/json", "X-API-Key": cfg.apiKey },
2179
+ body: JSON.stringify(payload),
2180
+ signal
2181
+ });
2182
+ let json = {};
2183
+ try {
2184
+ json = await r.json();
2185
+ } catch {
2186
+ }
2187
+ if (!r.ok) {
2188
+ const msg = json?.error || json?.message || "Failed to build route";
2189
+ throw new Error(msg);
2190
+ }
2191
+ const intentId = json?.data?.intentId ?? json?.intentId ?? "";
2192
+ const route = json?.data?.route ?? json?.route;
2193
+ const txReq = route?.execution?.transaction;
2194
+ const actions = Array.isArray(route?.steps) ? route.steps : [];
2195
+ const estimate = route?.estimate ?? {};
2196
+ const finalExchangeRate = {
2197
+ fromAmountUSD: estimate.fromAmountUsd,
2198
+ toAmountMinUSD: estimate?.toAmountMinUsd ?? estimate?.toAmountUsd
2199
+ };
2200
+ if (!txReq?.data) {
2201
+ throw new Error("Invalid route: missing transaction data");
2202
+ }
2203
+ return { intentId, txReq, actions, finalExchangeRate, route };
2204
+ }
2205
+ async function buildDepositAddress(body, signal) {
2206
+ const cfg = TrustwareConfigStore.get();
2207
+ const url = `${apiBase()}/v1/routes/deposit-address`;
2208
+ const payload = {
2209
+ ...body,
2210
+ slippageBps: body.slippageBps ?? (body.slippage === void 0 ? void 0 : Math.round(body.slippage * 100)),
2211
+ fromAmountUSD: body.fromAmountUSD ?? body.fromAmountUsd
2212
+ };
2213
+ const r = await rateLimitedFetch(url, {
2214
+ method: "POST",
2215
+ headers: { "Content-Type": "application/json", "X-API-Key": cfg.apiKey },
2216
+ body: JSON.stringify(payload),
2217
+ signal
2218
+ });
2219
+ let json = {};
2220
+ try {
2221
+ json = await r.json();
2222
+ } catch {
2223
+ }
2224
+ if (!r.ok) {
2225
+ const msg = json?.error || json?.message || "Failed to build deposit address";
2226
+ throw new Error(msg);
2227
+ }
2228
+ const intentId = json?.data?.intentId ?? json?.intentId ?? "";
2229
+ const route = json?.data?.route ?? json?.route;
2230
+ const depositAddress = json?.data?.depositAddress?.address ?? json?.depositAddress?.address ?? "";
2231
+ const actions = Array.isArray(route?.steps) ? route.steps : [];
2232
+ const estimate = route?.estimate ?? {};
2233
+ if (!depositAddress) {
2234
+ throw new Error("Invalid route: missing deposit address");
2235
+ }
2236
+ return {
2237
+ intentId,
2238
+ depositAddress,
2239
+ actions,
2240
+ finalExchangeRate: {
2241
+ fromAmountUSD: estimate.fromAmountUsd,
2242
+ toAmountMinUSD: estimate?.toAmountMinUsd ?? estimate?.toAmountUsd
2243
+ },
2244
+ route
2245
+ };
2246
+ }
2247
+ async function submitReceipt(intentId, txHash) {
2248
+ const r = await rateLimitedFetch(
2249
+ `${apiBase()}/v1/route-intent/${intentId}/receipt`,
2250
+ {
2251
+ method: "POST",
2252
+ headers: jsonHeaders({ "Idempotency-Key": txHash }),
2253
+ body: JSON.stringify({ txHash })
2254
+ }
2255
+ );
2256
+ await assertOK(r);
2257
+ const j = await r.json();
2258
+ return j.data;
2259
+ }
2260
+ async function getStatus(intentId) {
2261
+ const r = await rateLimitedFetch(
2262
+ `${apiBase()}/v1/route-intent/${intentId}/status`,
2263
+ {
2264
+ headers: jsonHeaders()
2265
+ }
2266
+ );
2267
+ await assertOK(r);
2268
+ const j = await r.json();
2269
+ return j.data;
2270
+ }
2271
+ async function pollStatus(intentId, { intervalMs = 2e3, timeoutMs = 5 * 6e4 } = {}) {
2272
+ const t0 = Date.now();
2273
+ while (true) {
2274
+ const tx = await getStatus(intentId);
2275
+ if (tx.status === "success" || tx.status === "failed") return tx;
2276
+ if (Date.now() - t0 > timeoutMs) return tx;
2277
+ await new Promise((r) => setTimeout(r, intervalMs));
2278
+ }
2279
+ }
2280
+
2281
+ // src/core/balances.ts
2282
+ init_http();
2283
+ init_registry();
2284
+ init_chains();
2285
+ var balanceCache = /* @__PURE__ */ new Map();
2286
+ function toStringOrUndefined(value) {
2287
+ if (typeof value !== "string") return void 0;
2288
+ const trimmed = value.trim();
2289
+ return trimmed || void 0;
2290
+ }
2291
+ function toNumberOrUndefined(value) {
2292
+ if (typeof value === "number") {
2293
+ return Number.isFinite(value) ? value : void 0;
2294
+ }
2295
+ if (typeof value === "string") {
2296
+ const parsed = Number(value.trim());
2297
+ return Number.isFinite(parsed) ? parsed : void 0;
2298
+ }
2299
+ return void 0;
2300
+ }
2301
+ function fallbackTokenSymbol(address, chainType) {
2302
+ if (chainType?.toLowerCase() === "solana") {
2303
+ return "SPL";
2304
+ }
2305
+ return `TOKEN-${address.slice(0, 6)}`;
2306
+ }
2307
+ function normalizeRows(rows, chain, address, registry) {
2308
+ const chainKey = chain.networkIdentifier ?? String(chain.chainId ?? chain.id);
2309
+ const chainType = normalizeChainType(chain);
2310
+ const nativeAddress = getNativeTokenAddress(chainType);
2311
+ const map = /* @__PURE__ */ new Map();
2312
+ for (const item of rows) {
2313
+ const category = toStringOrUndefined(item.category)?.toLowerCase();
2314
+ const addressRaw = item.contract ?? item.token_address ?? item.address ?? item.addr;
2315
+ const tokenAddress = typeof addressRaw === "string" ? addressRaw.trim() : void 0;
2316
+ const symbol = toStringOrUndefined(item.symbol ?? item.sym);
2317
+ const name = toStringOrUndefined(item.name ?? item.token_name ?? item.token) ?? symbol;
2318
+ const decimals = toNumberOrUndefined(item.decimals ?? item.dec);
2319
+ const balance = String(item.balance ?? item.bal ?? "0");
2320
+ const explicitNative = Boolean(item.native ?? item.is_native);
2321
+ const nativeFlag = explicitNative || category === "native" || isZeroAddressLike(tokenAddress, chainType);
2322
+ if (nativeFlag) {
2323
+ const nativeRow = {
2324
+ chain_key: chainKey,
2325
+ category: "native",
2326
+ contract: nativeAddress,
2327
+ address: nativeAddress,
2328
+ symbol: symbol ?? chain.nativeCurrency?.symbol ?? "NATIVE",
2329
+ name: name ?? chain.nativeCurrency?.name ?? symbol,
2330
+ decimals: decimals ?? chain.nativeCurrency?.decimals ?? 18,
2331
+ balance
2332
+ };
2333
+ map.set(`${chainKey}:${nativeAddress}`, nativeRow);
2334
+ continue;
2335
+ }
2336
+ if (!tokenAddress || decimals === void 0) continue;
2337
+ const metadata = registry.findToken(chain.chainId, tokenAddress);
2338
+ const displaySymbol = symbol ?? metadata?.symbol ?? fallbackTokenSymbol(tokenAddress, chainType);
2339
+ const displayName = name ?? metadata?.name ?? displaySymbol;
2340
+ const normalizedAddress = metadata?.address ?? tokenAddress;
2341
+ map.set(`${chainKey}:${normalizedAddress}`, {
2342
+ chain_key: chainKey,
2343
+ category: category ?? (chainType === "solana" ? "spl" : "erc20"),
2344
+ contract: normalizedAddress,
2345
+ address: normalizedAddress,
2346
+ symbol: displaySymbol,
2347
+ name: displayName,
2348
+ decimals: metadata?.decimals ?? decimals,
2349
+ balance,
2350
+ logoURI: metadata?.logoURI,
2351
+ usdPrice: metadata?.usdPrice
2352
+ });
2353
+ }
2354
+ if (!Array.from(map.values()).some((row) => row.category === "native")) {
2355
+ map.set(`${chainKey}:${nativeAddress}`, {
2356
+ chain_key: chainKey,
2357
+ category: "native",
2358
+ contract: nativeAddress,
2359
+ address: nativeAddress,
2360
+ symbol: chain.nativeCurrency?.symbol ?? "NATIVE",
2361
+ name: chain.nativeCurrency?.name ?? chain.nativeCurrency?.symbol,
2362
+ decimals: chain.nativeCurrency?.decimals ?? 18,
2363
+ balance: "0"
2364
+ });
2365
+ }
2366
+ return Array.from(map.values()).sort((a, b) => {
2367
+ try {
2368
+ return Number(BigInt(b.balance) - BigInt(a.balance));
2369
+ } catch {
2370
+ return 0;
2371
+ }
2372
+ });
2373
+ }
2374
+ async function getBalances(chainRef, address) {
2375
+ const reg = await ensureRegistry();
2376
+ const chain = reg.chain(chainRef);
2377
+ if (!chain) return [];
2378
+ const trimmedAddress = address.trim();
2379
+ const validation = validateAddressForChain(trimmedAddress, chain);
2380
+ if (!validation.isValid) return [];
2381
+ const chainKey = chain.networkIdentifier ?? String(chain.chainId ?? chain.id);
2382
+ const cacheKey = [
2383
+ chainKey,
2384
+ trimmedAddress,
2385
+ chain.nativeCurrency?.symbol ?? "",
2386
+ chain.nativeCurrency?.decimals ?? "",
2387
+ normalizeChainType(chain) ?? ""
2388
+ ].join(":");
2389
+ const cached = balanceCache.get(cacheKey);
2390
+ if (cached) return cached;
2391
+ const url = `${apiBase()}/v1/data/wallets/${encodeURIComponent(chainKey)}/${trimmedAddress}/balances`;
2392
+ const response = await fetch(url, {
2393
+ method: "GET",
2394
+ credentials: "omit",
2395
+ headers: jsonHeaders()
2396
+ });
2397
+ if (!response.ok) throw new Error(`balances: HTTP ${response.status}`);
2398
+ const json = await response.json();
2399
+ const rows = Array.isArray(json) ? json : json.data ?? [];
2400
+ const normalized = normalizeRows(rows, chain, trimmedAddress, reg);
2401
+ balanceCache.set(cacheKey, normalized);
2402
+ return normalized;
2403
+ }
2404
+ async function getBalancesByAddress(address) {
2405
+ const url = `${apiBase()}/data/balances/${address}`;
2406
+ const r = await fetch(url, {
2407
+ method: "GET",
2408
+ credentials: "omit",
2409
+ headers: jsonHeaders()
2410
+ });
2411
+ if (!r.ok) throw new Error(`balances: HTTP ${r.status}`);
2412
+ const j = await r.json();
2413
+ return Array.isArray(j) ? j : j.results ?? [];
2414
+ }
2415
+ var _registry;
2416
+ async function ensureRegistry() {
2417
+ if (!_registry) {
2418
+ _registry = new Registry(apiBase());
2419
+ }
2420
+ await _registry.ensureLoaded();
2421
+ return _registry;
2422
+ }
2423
+
2424
+ // src/core/tx.ts
2425
+ function isUserRejected(e2) {
2426
+ const code = e2?.code ?? e2?.data?.code;
2427
+ if (code === 4001) return true;
2428
+ const msg = String(e2?.message || e2)?.toLowerCase?.() || "";
2429
+ return msg.includes("user rejected") || msg.includes("user denied");
2430
+ }
2431
+ async function sendRouteTransaction(b, fallbackChainId) {
2432
+ const w = walletManager.wallet;
2433
+ if (!w) throw new Error("Trustware.wallet not configured");
2434
+ const txReq = b.txReq;
2435
+ if (isEvmTxRequest(txReq)) {
2436
+ if (w.ecosystem !== "evm") {
2437
+ throw new Error("An EVM wallet is required for this route");
2438
+ }
2439
+ const to = txReq.to ?? txReq.target;
2440
+ const data = txReq.data;
2441
+ const value = txReq.value ? BigInt(txReq.value) : 0n;
2442
+ const target = Number(txReq.chainId ?? fallbackChainId);
2443
+ if (Number.isFinite(target)) {
2444
+ const current = await w.getChainId();
2445
+ if (current !== target) {
2446
+ try {
2447
+ await w.switchChain(target);
2448
+ } catch {
2449
+ }
2450
+ }
2451
+ }
2452
+ if (w.type === "eip1193") {
2453
+ const from = await w.getAddress();
2454
+ const hexValue = value ? `0x${value.toString(16)}` : "0x0";
2455
+ const params = {
2456
+ from,
2457
+ to,
2458
+ data,
2459
+ value: hexValue
2460
+ };
2461
+ if (Number.isFinite(target)) {
2462
+ params.chainId = `0x${target.toString(16)}`;
2463
+ }
2464
+ const hash = await w.request({
2465
+ method: "eth_sendTransaction",
2466
+ params: [params]
2467
+ });
2468
+ return hash;
2469
+ }
2470
+ const response = await w.sendTransaction({
2471
+ to,
2472
+ data,
2473
+ value,
2474
+ chainId: Number.isFinite(target) ? target : void 0
2475
+ });
2476
+ return response.hash;
2477
+ }
2478
+ if (isSerializedSolanaTxRequest(txReq)) {
2479
+ if (w.ecosystem !== "solana") {
2480
+ throw new Error("A Solana wallet is required for this route");
2481
+ }
2482
+ const { Registry: Registry2 } = await Promise.resolve().then(() => (init_registry(), registry_exports));
2483
+ const { apiBase: apiBase2 } = await Promise.resolve().then(() => (init_http(), http_exports));
2484
+ const registry = new Registry2(apiBase2());
2485
+ await registry.ensureLoaded();
2486
+ const chain = registry.chain(
2487
+ String(fallbackChainId ?? txReq.chainId ?? "")
2488
+ );
2489
+ const rpcUrl = chain?.rpc ?? chain?.rpcList?.[0];
2490
+ return w.sendSerializedTransaction(txReq.data, rpcUrl);
2491
+ }
2492
+ throw new Error("Invalid route transaction payload");
2493
+ }
2494
+ async function runTopUp(params) {
2495
+ const w = walletManager.wallet;
2496
+ if (!w) throw new Error("Trustware.wallet not configured");
2497
+ const { Registry: Registry2 } = await Promise.resolve().then(() => (init_registry(), registry_exports));
2498
+ const { apiBase: apiBase2 } = await Promise.resolve().then(() => (init_http(), http_exports));
2499
+ const reg = new Registry2(apiBase2());
2500
+ await reg.ensureLoaded();
2501
+ const fromAddress = await w.getAddress();
2502
+ const currentChainRef = w.ecosystem === "evm" ? String(await w.getChainId()) : await w.getChainKey?.() ?? "solana-mainnet-beta";
2503
+ const originalChain = w.ecosystem === "evm" ? await w.getChainId() : void 0;
2504
+ const fromChain = params.fromChain ?? currentChainRef;
2505
+ const { TrustwareConfigStore: TrustwareConfigStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
2506
+ const cfg = TrustwareConfigStore2.get();
2507
+ const toChain = params.toChain ?? String(cfg.routes.toChain);
2508
+ const fromToken = reg.resolveToken(
2509
+ fromChain,
2510
+ params.fromToken ?? cfg.routes.fromToken ?? void 0
2511
+ ) ?? params.fromToken;
2512
+ const toToken = reg.resolveToken(
2513
+ toChain,
2514
+ params.toToken ?? cfg.routes.toToken ?? void 0
2515
+ ) ?? params.toToken;
2516
+ if (!fromToken || !toToken) {
2517
+ throw new Error("Unable to resolve route tokens");
2518
+ }
2519
+ try {
2520
+ const build = await buildRoute({
2521
+ fromChain,
2522
+ toChain,
2523
+ fromToken,
2524
+ toToken,
2525
+ fromAmount: String(params.fromAmount),
2526
+ fromAddress,
2527
+ toAddress: params.toAddress ?? cfg.routes.toAddress ?? cfg.routes.fromAddress ?? fromAddress,
2528
+ slippage: cfg.routes.defaultSlippage
2529
+ });
2530
+ const hash = await sendRouteTransaction(build, fromChain);
2531
+ await submitReceipt(build.intentId, hash);
2532
+ return await pollStatus(build.intentId);
2533
+ } catch (e2) {
2534
+ if (isUserRejected(e2)) throw new Error("Transaction cancelled by user");
2535
+ throw e2;
2536
+ } finally {
2537
+ try {
2538
+ if (w.ecosystem === "evm" && originalChain && originalChain !== Number(fromChain)) {
2539
+ await w.switchChain(originalChain);
2540
+ }
2541
+ } catch {
2542
+ }
2543
+ }
2544
+ }
2545
+
2546
+ // src/core/index.ts
2547
+ init_http();
2548
+
2549
+ // src/core/useChains.ts
2550
+ var import_react2 = require("react");
2551
+
2552
+ // src/core/registryClient.ts
2553
+ init_config2();
2554
+ init_registry();
2555
+ init_http();
2556
+ var registryCache = /* @__PURE__ */ new Map();
2557
+ function registryCacheKey() {
2558
+ const base = apiBase();
2559
+ const apiKey = TrustwareConfigStore.peek()?.apiKey ?? "__uninitialized__";
2560
+ return `${base}::${apiKey}`;
2561
+ }
2562
+ function getSharedRegistry() {
2563
+ const key = registryCacheKey();
2564
+ const existing = registryCache.get(key);
2565
+ if (existing) {
2566
+ return existing;
2567
+ }
2568
+ const registry = new Registry(apiBase());
2569
+ registryCache.set(key, registry);
2570
+ return registry;
2571
+ }
2572
+
2573
+ // src/widget/helpers/chainHelpers.ts
2574
+ function normalizeChainKey2(id) {
2575
+ if (id === void 0 || id === null) return "";
2576
+ return String(id).trim().toLowerCase();
2577
+ }
2578
+ var CHAIN_TYPE_ALIASES2 = {
2579
+ btc: "bitcoin",
2580
+ bitcoin: "bitcoin",
2581
+ sei: "cosmos",
2582
+ "pacific-1": "cosmos"
2583
+ };
2584
+ function inferChainTypeFromValue2(normalized) {
2585
+ if (!normalized) return void 0;
2586
+ const aliased = CHAIN_TYPE_ALIASES2[normalized];
2587
+ if (aliased) return aliased;
2588
+ if (normalized === "evm" || normalized === "solana" || normalized === "cosmos" || normalized === "bitcoin") {
2589
+ return normalized;
2590
+ }
2591
+ if (/^eip155:\d+$/.test(normalized) || /^\d+$/.test(normalized)) {
2592
+ return "evm";
2593
+ }
2594
+ if (normalized.startsWith("solana:") || normalized.includes("solana")) {
2595
+ return "solana";
2596
+ }
2597
+ if (normalized.startsWith("cosmos:") || normalized.startsWith("sei:") || normalized === "sei-evm") {
2598
+ return "cosmos";
2599
+ }
2600
+ return void 0;
2601
+ }
2602
+ function normalizeChainType2(chain) {
2603
+ if (!chain) return void 0;
2604
+ const raw = typeof chain === "string" ? chain : chain.type ?? chain.chainType ?? chain.networkIdentifier ?? chain.chainId ?? chain.id ?? chain.networkName ?? chain.axelarChainName;
2605
+ if (!raw) return void 0;
2606
+ const normalized = String(raw).trim().toLowerCase();
2607
+ return inferChainTypeFromValue2(normalized) ?? normalized;
2608
+ }
2609
+ function canonicalChainKeyForLink(chain) {
2610
+ const seiKey = canonicalSeiChainKey(chain.chainId ?? chain.id);
2611
+ if (seiKey) return seiKey;
2612
+ return normalizeChainKey2(
2613
+ chain.networkIdentifier ?? chain.axelarChainName ?? chain.id ?? chain.chainId ?? chain.networkName
2614
+ );
2615
+ }
2616
+ var SEI_EVM_CHAIN_ID = "1329";
2617
+ var SEI_COSMOS_CHAIN_ID = "pacific-1";
2618
+ function canonicalSeiChainKey(chainId) {
2619
+ const normalized = normalizeChainKey2(chainId);
2620
+ if (!normalized) return null;
2621
+ if (normalized === SEI_EVM_CHAIN_ID) return "sei-evm";
2622
+ if (normalized === SEI_COSMOS_CHAIN_ID) return "sei";
2623
+ return null;
2624
+ }
2625
+
2626
+ // src/core/useChains.ts
2627
+ var POPULAR_CHAIN_IDS = /* @__PURE__ */ new Set([
2628
+ 1,
2629
+ // Ethereum Mainnet
2630
+ 137,
2631
+ // Polygon
2632
+ 8453
2633
+ // Base
2634
+ ]);
2635
+ function filterSupportedChains(chains) {
2636
+ const supportedChainTypes = /* @__PURE__ */ new Set(["evm", "solana", "cosmos", "bitcoin"]);
2637
+ return chains.filter((chain) => {
2638
+ const chainType = normalizeChainType2(chain);
2639
+ if (!chainType) return false;
2640
+ if (!supportedChainTypes.has(chainType)) {
2641
+ return false;
2642
+ }
2643
+ if (chainType === "evm") {
2644
+ const evmKey = canonicalChainKeyForLink(chain);
2645
+ const disabledEvmChains = /* @__PURE__ */ new Set(["hedera", "295"]);
2646
+ if (evmKey && disabledEvmChains.has(evmKey)) {
2647
+ return false;
2648
+ }
2649
+ }
2650
+ if (chainType === "cosmos") {
2651
+ const seiKey = canonicalSeiChainKey(chain.chainId ?? chain.id);
2652
+ if (seiKey !== "sei" && seiKey !== "pacific-1") {
2653
+ return false;
2654
+ }
2655
+ }
2656
+ if (chainType === "bitcoin") {
2657
+ return false;
2658
+ }
2659
+ return true;
2660
+ });
2661
+ }
2662
+ function useChains() {
2663
+ const [chains, setChains] = (0, import_react2.useState)([]);
2664
+ const [chainMap, setChainMap] = (0, import_react2.useState)(/* @__PURE__ */ new Map());
2665
+ const [isLoading, setIsLoading] = (0, import_react2.useState)(true);
2666
+ const [error, setError] = (0, import_react2.useState)(null);
2667
+ const registry = getSharedRegistry();
2668
+ (0, import_react2.useEffect)(() => {
2669
+ if (chains.length > 0) return;
2670
+ let cancelled = false;
2671
+ const loadChains = async () => {
2672
+ try {
2673
+ setIsLoading(true);
2674
+ setError(null);
2675
+ await registry.ensureLoaded();
2676
+ if (cancelled) return;
2677
+ const loadedChains = registry.chains();
2678
+ const supportedChains = filterSupportedChains(loadedChains);
2679
+ const chainMap2 = new Map(
2680
+ supportedChains.map((chain) => [
2681
+ chain.chainId ?? chain.id,
2682
+ chain
2683
+ ])
2684
+ );
2685
+ setChainMap(chainMap2);
2686
+ setChains(supportedChains);
2687
+ } catch (err) {
2688
+ if (!cancelled) {
2689
+ const message = err instanceof Error ? err.message : "Failed to load chains";
2690
+ setError(message);
2691
+ setChains([]);
2692
+ }
2693
+ } finally {
2694
+ if (!cancelled) {
2695
+ setIsLoading(false);
2696
+ }
2697
+ }
2698
+ };
2699
+ void loadChains();
2700
+ return () => {
2701
+ cancelled = true;
2702
+ };
2703
+ }, [registry, chains.length]);
2704
+ const { popularChains, otherChains } = (0, import_react2.useMemo)(() => {
2705
+ const popular = [];
2706
+ const other = [];
2707
+ for (const chain of chains) {
2708
+ const chainId = Number(chain.chainId ?? chain.id);
2709
+ if (POPULAR_CHAIN_IDS.has(chainId)) {
2710
+ popular.push(chain);
2711
+ } else {
2712
+ other.push(chain);
2713
+ }
2714
+ }
2715
+ const popularOrder = [1, 137, 8453];
2716
+ popular.sort((a, b) => {
2717
+ const aId = Number(a.chainId ?? a.id);
2718
+ const bId = Number(b.chainId ?? b.id);
2719
+ return popularOrder.indexOf(aId) - popularOrder.indexOf(bId);
2720
+ });
2721
+ return { popularChains: popular, otherChains: other };
2722
+ }, [chains]);
2723
+ return {
2724
+ chains,
2725
+ chainMap,
2726
+ popularChains,
2727
+ otherChains,
2728
+ isLoading,
2729
+ error
2730
+ };
2731
+ }
2732
+
2733
+ // src/core/useTokens.ts
2734
+ var import_react3 = require("react");
2735
+
2736
+ // src/widget/data/chainPopularity.json
2737
+ var chainPopularity_default = {
2738
+ ethereum: 1,
2739
+ "1": 1,
2740
+ arbitrum: 2,
2741
+ "arbitrum-one": 2,
2742
+ "42161": 2,
2743
+ base: 3,
2744
+ "8453": 3,
2745
+ bsc: 4,
2746
+ binance: 4,
2747
+ "binance-smart-chain": 4,
2748
+ "56": 4,
2749
+ solana: 5,
2750
+ "solana-mainnet-beta": 5,
2751
+ avalanche: 6,
2752
+ "avalanche-c-chain": 6,
2753
+ "43114": 6,
2754
+ tron: 7,
2755
+ "728126428": 7,
2756
+ sui: 8,
2757
+ "137": 9,
2758
+ polygon: 9,
2759
+ "polygon-pos": 9,
2760
+ optimism: 10,
2761
+ "10": 10,
2762
+ bitcoin: 11,
2763
+ cosmoshub: 12,
2764
+ cosmos: 12,
2765
+ osmosis: 13,
2766
+ sei: 14,
2767
+ "sei-evm": 14,
2768
+ "pacific-1": 14,
2769
+ "1329": 14,
2770
+ mantle: 15,
2771
+ "5000": 15,
2772
+ linea: 16,
2773
+ "59144": 16,
2774
+ zksync: 17,
2775
+ "zksync-era": 17,
2776
+ "324": 17,
2777
+ blast: 18,
2778
+ "81457": 18,
2779
+ scroll: 19,
2780
+ "534352": 19,
2781
+ sonic: 20,
2782
+ "146": 20
2783
+ };
2784
+
2785
+ // src/widget/helpers/chainPopularity.ts
2786
+ var popularityByKey = chainPopularity_default;
2787
+ function getChainPopularityRank(chain) {
2788
+ if (!chain) return null;
2789
+ const aliases = [
2790
+ chain.chainId,
2791
+ chain.networkIdentifier,
2792
+ chain.networkName,
2793
+ chain.axelarChainName
2794
+ ];
2795
+ for (const alias of aliases) {
2796
+ const key = normalizeChainKey2(alias ?? null);
2797
+ if (!key) continue;
2798
+ const rank = popularityByKey[key];
2799
+ if (typeof rank === "number") {
2800
+ return rank;
2801
+ }
2802
+ }
2803
+ return null;
2804
+ }
2805
+
2806
+ // src/widget/helpers/tokenPopularity.ts
2807
+ var POPULAR_TOKEN_SYMBOLS = new Set(
2808
+ [
2809
+ "USDC",
2810
+ "USDC.E",
2811
+ "USDBC",
2812
+ "USDT",
2813
+ "DAI",
2814
+ "ETH",
2815
+ "WETH",
2816
+ "WBTC",
2817
+ "BTC",
2818
+ "SOL",
2819
+ "MATIC"
2820
+ ].map((symbol) => symbol.toUpperCase())
2821
+ );
2822
+ var POPULAR_TOKEN_CONTRACTS = /* @__PURE__ */ new Set([
2823
+ "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
2824
+ // USDC (Ethereum)
2825
+ "0xdac17f958d2ee523a2206206994597c13d831ec7",
2826
+ // USDT (Ethereum)
2827
+ "0x6b175474e89094c44da98b954eedeac495271d0f",
2828
+ // DAI (Ethereum)
2829
+ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
2830
+ // USDC (Base)
2831
+ "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359",
2832
+ // USDC (Polygon)
2833
+ "0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
2834
+ // USDC.e (Polygon)
2835
+ "0xc2132d05d31c914a87c6611c10748aeb04b58e8f",
2836
+ // USDT (Polygon)
2837
+ "0xaf88d065e77c8cc2239327c5edb3a432268e5831",
2838
+ // USDC (Arbitrum)
2839
+ "0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9",
2840
+ // USDT (Arbitrum)
2841
+ "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
2842
+ // EVM native token marker
2843
+ "so11111111111111111111111111111111111111112"
2844
+ // Wrapped SOL
2845
+ ]);
2846
+ function normalizeSymbol(symbol) {
2847
+ return (symbol ?? "").trim().toUpperCase();
2848
+ }
2849
+ function normalizeAddress2(address) {
2850
+ return (address ?? "").trim().toLowerCase();
2851
+ }
2852
+ function hasPositiveBalance(balance) {
2853
+ if (!balance) return false;
2854
+ const trimmed = balance.trim();
2855
+ if (!trimmed) return false;
2856
+ if (/^[+-]?\d+$/.test(trimmed)) {
2857
+ try {
2858
+ return BigInt(trimmed) > 0n;
2859
+ } catch {
2860
+ return false;
2861
+ }
2862
+ }
2863
+ if (/^[+-]?\d*\.\d+$/.test(trimmed)) {
2864
+ const isNegative = trimmed.startsWith("-");
2865
+ if (isNegative) return false;
2866
+ const normalized = trimmed.startsWith("+") ? trimmed.slice(1) : trimmed;
2867
+ const [whole, fraction = ""] = normalized.split(".");
2868
+ const wholeInt = whole ? BigInt(whole) : 0n;
2869
+ if (wholeInt > 0n) return true;
2870
+ return /[1-9]/.test(fraction);
2871
+ }
2872
+ const asNumber = Number(trimmed);
2873
+ return Number.isFinite(asNumber) && asNumber > 0;
2874
+ }
2875
+ function isPopularToken(token) {
2876
+ const normalizedSymbol = normalizeSymbol(token.symbol);
2877
+ const normalizedAddress = normalizeAddress2(token.address);
2878
+ return POPULAR_TOKEN_SYMBOLS.has(normalizedSymbol) || POPULAR_TOKEN_CONTRACTS.has(normalizedAddress);
2879
+ }
2880
+ function compareText(a, b) {
2881
+ return (a ?? "").localeCompare(b ?? "", void 0, {
2882
+ sensitivity: "base"
2883
+ });
2884
+ }
2885
+ function getGroupRank(token) {
2886
+ const popular = isPopularToken(token);
2887
+ const positiveBalance = hasPositiveBalance(token.balance);
2888
+ if (popular && positiveBalance) return 0;
2889
+ if (popular && !positiveBalance) return 1;
2890
+ if (!popular && positiveBalance) return 2;
2891
+ return 3;
2892
+ }
2893
+ function compareChainPopularity(a, b) {
2894
+ const rankA = getChainPopularityRank({ chainId: a.chainId });
2895
+ const rankB = getChainPopularityRank({ chainId: b.chainId });
2896
+ if (rankA !== null && rankB !== null && rankA !== rankB) {
2897
+ return rankA - rankB;
2898
+ }
2899
+ if (rankA !== null && rankB === null) return -1;
2900
+ if (rankA === null && rankB !== null) return 1;
2901
+ return 0;
2902
+ }
2903
+ function sortTokensByPopularity(tokens) {
2904
+ return tokens.map((token, index) => ({ token, index })).sort((a, b) => {
2905
+ const rankDiff = getGroupRank(a.token) - getGroupRank(b.token);
2906
+ if (rankDiff !== 0) return rankDiff;
2907
+ const chainPopularityDiff = compareChainPopularity(a.token, b.token);
2908
+ if (chainPopularityDiff !== 0) return chainPopularityDiff;
2909
+ const symbolDiff = compareText(a.token.symbol, b.token.symbol);
2910
+ if (symbolDiff !== 0) return symbolDiff;
2911
+ const nameDiff = compareText(a.token.name, b.token.name);
2912
+ if (nameDiff !== 0) return nameDiff;
2913
+ const addressDiff = compareText(a.token.address, b.token.address);
2914
+ if (addressDiff !== 0) return addressDiff;
2915
+ return a.index - b.index;
2916
+ }).map(({ token }) => token);
2917
+ }
2918
+
2919
+ // src/core/useTokens.ts
2920
+ function mapTokenDefToToken(tokenDef) {
2921
+ return {
2922
+ address: tokenDef.address,
2923
+ chainId: tokenDef.chainId,
2924
+ symbol: tokenDef.symbol,
2925
+ name: tokenDef.name,
2926
+ decimals: tokenDef.decimals,
2927
+ iconUrl: tokenDef.logoURI,
2928
+ logoURI: tokenDef.logoURI,
2929
+ // balance is populated separately when wallet is connected
2930
+ balance: void 0,
2931
+ usdPrice: tokenDef.usdPrice
2932
+ };
2933
+ }
2934
+ function useTokens(chainId) {
2935
+ const [tokens, setTokens] = (0, import_react3.useState)([]);
2936
+ const [isLoading, setIsLoading] = (0, import_react3.useState)(false);
2937
+ const [error, setError] = (0, import_react3.useState)(null);
2938
+ const [searchQuery, setSearchQuery] = (0, import_react3.useState)("");
2939
+ const registry = getSharedRegistry();
2940
+ const { chainMap } = useChains();
2941
+ (0, import_react3.useEffect)(() => {
2942
+ setSearchQuery("");
2943
+ setError(null);
2944
+ setTokens([]);
2945
+ if (chainId === void 0 || chainMap.size === 0) {
2946
+ setIsLoading(false);
2947
+ return;
2948
+ }
2949
+ let cancelled = false;
2950
+ const loadTokens = async () => {
2951
+ try {
2952
+ setIsLoading(true);
2953
+ setError(null);
2954
+ await registry.ensureLoaded();
2955
+ if (cancelled) return;
2956
+ const tokenDefs = chainId === null ? registry.allTokens() : registry.tokens(chainId);
2957
+ const filteredTokens2 = tokenDefs.filter(
2958
+ (item) => chainMap.has(item.chainId.toString())
2959
+ );
2960
+ if (filteredTokens2 !== void 0) {
2961
+ setTokens(filteredTokens2.map(mapTokenDefToToken));
2962
+ }
2963
+ } catch (err) {
2964
+ if (!cancelled) {
2965
+ const message = err instanceof Error ? err.message : "Failed to load tokens";
2966
+ setError(message);
2967
+ setTokens([]);
2968
+ }
2969
+ } finally {
2970
+ if (!cancelled) {
2971
+ setIsLoading(false);
2972
+ }
2973
+ }
2974
+ };
2975
+ void loadTokens();
2976
+ return () => {
2977
+ cancelled = true;
2978
+ };
2979
+ }, [chainId, registry, chainMap]);
2980
+ const filteredTokens = (0, import_react3.useMemo)(() => {
2981
+ const query = searchQuery.toLowerCase().trim();
2982
+ const source = query.length === 0 ? tokens : tokens.filter(
2983
+ (token) => token.symbol.toLowerCase().includes(query) || token.name.toLowerCase().includes(query) || token.address.toLowerCase().includes(query)
2984
+ );
2985
+ return sortTokensByPopularity(source);
2986
+ }, [tokens, searchQuery]);
2987
+ return {
2988
+ tokens,
2989
+ filteredTokens,
2990
+ isLoading,
2991
+ error,
2992
+ searchQuery,
2993
+ setSearchQuery
2994
+ };
2995
+ }
2996
+
2997
+ // src/errors/TrustwareError.ts
2998
+ var TrustwareError = class extends Error {
2999
+ constructor(params) {
3000
+ super(params.message);
3001
+ this.name = "TrustwareError";
3002
+ this.code = params.code;
3003
+ this.userMessage = params.userMessage;
3004
+ this.cause = params.cause;
3005
+ }
3006
+ toJSON() {
3007
+ return {
3008
+ name: this.name,
3009
+ code: this.code,
3010
+ message: this.message,
3011
+ userMessage: this.userMessage
3012
+ };
3013
+ }
3014
+ };
3015
+
3016
+ // src/core/index.ts
3017
+ var _lastValidatedKey = null;
3018
+ var Trustware = {
3019
+ /** Initialize config */
3020
+ async init(cfg) {
3021
+ TrustwareConfigStore.init(cfg);
3022
+ const key = TrustwareConfigStore.get().apiKey;
3023
+ if (_lastValidatedKey !== key) {
3024
+ try {
3025
+ await validateSdkAccess();
3026
+ _lastValidatedKey = key;
3027
+ } catch (err) {
3028
+ const reason = err instanceof Error && err.message ? `: ${err.message}` : "";
3029
+ const error = new TrustwareError({
3030
+ code: "INVALID_API_KEY" /* INVALID_API_KEY */,
3031
+ message: `Trustware.init: API key validation failed${reason}`,
3032
+ userMessage: "API key validation failed. Please verify your Trustware API key.",
3033
+ cause: err
3034
+ });
3035
+ const config = TrustwareConfigStore.get();
3036
+ config.onError?.(error);
3037
+ config.onEvent?.({ type: "error", error });
3038
+ throw error;
3039
+ }
3040
+ }
3041
+ return Trustware;
3042
+ },
3043
+ /** Attach a wallet interface directly (skips detection) */
3044
+ useWallet(w) {
3045
+ walletManager.attachWallet(w);
3046
+ return Trustware;
3047
+ },
3048
+ /** Best-effort background attach to detected wallet(s) (detection hook should be running in the app) */
3049
+ async autoDetect(_timeoutMs) {
3050
+ await walletManager.autoAttach();
3051
+ return walletManager.wallet != null;
3052
+ },
3053
+ /** Read resolved config */
3054
+ getConfig() {
3055
+ return TrustwareConfigStore.get();
3056
+ },
3057
+ setDestinationAddress(address) {
3058
+ const prev = TrustwareConfigStore.get();
3059
+ TrustwareConfigStore.update({
3060
+ routes: {
3061
+ ...prev.routes,
3062
+ toAddress: address ?? void 0
3063
+ }
3064
+ });
3065
+ return Trustware;
3066
+ },
3067
+ /** Read active wallet */
3068
+ getWallet() {
3069
+ return walletManager.wallet;
3070
+ },
3071
+ getIdentity() {
3072
+ return walletManager.identity;
3073
+ },
3074
+ resolveAddressForChain(chain) {
3075
+ return walletManager.resolveAddressForChain(chain);
3076
+ },
3077
+ addIdentityAddress(address) {
3078
+ walletManager.addIdentityAddress(address);
3079
+ return Trustware;
3080
+ },
3081
+ /** Simple helpers */
3082
+ async getAddress() {
3083
+ const w = walletManager.wallet;
3084
+ if (!w) throw new Error("Trustware.wallet not configured");
3085
+ return w.getAddress();
3086
+ },
3087
+ // ---- REST methods (re-export) ----
3088
+ buildRoute,
3089
+ buildDepositAddress,
3090
+ submitReceipt,
3091
+ getStatus,
3092
+ pollStatus,
3093
+ getBalances,
3094
+ getBalancesByAddress,
3095
+ useChains,
3096
+ useTokens,
3097
+ validateAddressForChain,
3098
+ validateRouteAddresses,
3099
+ // ---- Tx helpers ----
3100
+ sendRouteTransaction,
3101
+ runTopUp
3102
+ };
3103
+ // Annotate the CommonJS export names for ESM import in node:
3104
+ 0 && (module.exports = {
3105
+ Trustware
3106
+ });
3107
+ //# sourceMappingURL=core.cjs.map