@gibs/bridge-client 1.19.0 → 1.20.0

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.
@@ -14,28 +14,13 @@ const ecosystems_1 = require("@gibs/bridge-sdk/ecosystems");
14
14
  const viem_1 = require("viem");
15
15
  const client_js_1 = require("./client.js");
16
16
  const networks_js_1 = require("./networks.js");
17
- /**
18
- * How many tokens one multicall asks about. Results come back flat, so each
19
- * loop below MUST pair a result triple with the address chunk that produced it
20
- * — see the primary loop for what indexing the flat array cost.
21
- */
22
17
  const TOKENS_PER_MULTICALL = 100;
23
- /**
24
- * Splits a list into consecutive runs of at most `size` items, in order.
25
- *
26
- * @param items - the list to split
27
- * @param size - the most items one run holds
28
- * @returns the runs; the last one may be shorter
29
- */
30
18
  const splitIntoChunks = (items, size) => Array.from({ length: Math.ceil(items.length / size) }, (_unused, index) => items.slice(index * size, (index + 1) * size));
31
19
  const bytes32Whitelist = new Set();
32
- // In-memory store for token metadata (loaded once, no persistence)
33
20
  const tokenMetadataStore = new Map();
34
- // Generate store key
35
21
  function getStoreKey(chainId, tokenAddress) {
36
22
  return `${chainId}:${tokenAddress.toLowerCase()}`;
37
23
  }
38
- // Parse a ChainScopedAddress into its components
39
24
  function parseChainScopedAddress(key) {
40
25
  const [chainIdStr, address] = key.split(':');
41
26
  const chainId = parseInt(chainIdStr ?? '', 10);
@@ -50,7 +35,6 @@ function parseChainScopedAddress(key) {
50
35
  address: address,
51
36
  };
52
37
  }
53
- // Parse a string key (chainId:address format) into its components with proper types
54
38
  function parseTokenKey(key) {
55
39
  const [chainIdStr, address] = key.split(':');
56
40
  const chainId = parseInt(chainIdStr ?? '', 10);
@@ -60,21 +44,17 @@ function parseTokenKey(key) {
60
44
  if (!address) {
61
45
  throw new Error(`Invalid address in token key: ${address}`);
62
46
  }
63
- // Ensure address is properly formatted as Hex
64
47
  const hexAddress = address.startsWith('0x') ? address : `0x${address}`;
65
48
  return {
66
49
  chainId,
67
50
  address: hexAddress,
68
51
  };
69
52
  }
70
- // Get native token metadata
71
53
  function getNativeTokenMetadata(chainId) {
72
54
  const chain = networks_js_1.evmChainsById.get(chainId);
73
- // Safely get native token info from SDK
74
55
  let name = chain?.nativeCurrency?.name || 'Ether';
75
56
  let symbol = chain?.nativeCurrency?.symbol || 'ETH';
76
57
  const decimals = chain?.nativeCurrency?.decimals || 18;
77
- // Try to get more specific info from SDK if available
78
58
  try {
79
59
  const chainKey = (0, config_1.toChain)(chainId);
80
60
  const sdkName = config_1.nativeTokenName[chainKey];
@@ -87,29 +67,21 @@ function getNativeTokenMetadata(chainId) {
87
67
  }
88
68
  }
89
69
  catch {
90
- // Fallback to viem chain info
91
70
  }
92
71
  return { name, symbol, decimals };
93
72
  }
94
- // Batch fetch token metadata for multiple tokens on the same chain
95
73
  async function batchFetchTokenMetadata(chainId, tokenAddresses) {
96
74
  const results = new Map();
97
75
  if (tokenAddresses.length === 0)
98
76
  return results;
99
- // Get the chain and client
100
77
  const chain = networks_js_1.evmChainsById.get(chainId);
101
78
  if (!chain) {
102
79
  throw new Error(`Chain not found for chainId: ${chainId}`);
103
80
  }
104
81
  const client = (0, client_js_1.clientFromChain)(chainId);
105
- // Separate native tokens from ERC20 tokens
106
82
  const nativeTokens = [];
107
83
  const erc20Tokens = [];
108
84
  tokenAddresses.forEach((address) => {
109
- // The registry's rule, not a hand-written one. Two spellings of the same
110
- // comparison sat here — an exact match OR a lower-cased one — which is what
111
- // a duplicated rule looks like once nobody is sure which half is load
112
- // bearing.
113
85
  if ((0, ecosystems_1.isNativeAsset)(address, 'evm')) {
114
86
  nativeTokens.push(address);
115
87
  }
@@ -117,17 +89,13 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
117
89
  erc20Tokens.push(address);
118
90
  }
119
91
  });
120
- // Handle native tokens
121
92
  const nativeMetadata = getNativeTokenMetadata(chainId);
122
93
  nativeTokens.forEach((address) => {
123
94
  results.set(address.toLowerCase(), nativeMetadata);
124
95
  });
125
- // Handle ERC20 tokens with batch multicall
126
96
  if (erc20Tokens.length === 0) {
127
- // console.log(`No ERC20 tokens to process for chain ${chainId}`)
128
97
  return results;
129
98
  }
130
- // console.log(`Processing ${erc20Tokens.length} ERC20 tokens for chain ${chainId}:`, erc20Tokens)
131
99
  const addressChunks = splitIntoChunks(erc20Tokens, TOKENS_PER_MULTICALL);
132
100
  const methods = ['symbol', 'name', 'decimals'];
133
101
  const addressChunksToCallChunks = (addressChunks, abi) => addressChunks.map((chunk) => chunk.map((address) => methods.map((functionName) => ({
@@ -137,18 +105,9 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
137
105
  allowFailure: true,
138
106
  args: [],
139
107
  }))));
140
- // Try with standard ERC20 ABI first
141
108
  const chunkedCalls = addressChunksToCallChunks(addressChunks, (address) => bytes32Whitelist.has(getStoreKey(chainId, address)) ? viem_1.erc20Abi_bytes32 : viem_1.erc20Abi);
142
109
  const fallback = [];
143
110
  for (const [chunkIndex, chunk] of chunkedCalls.entries()) {
144
- // The addresses THIS chunk asked about. Indexing the flat `erc20Tokens`
145
- // here instead was a silent data-corruption bug: `index` restarts at 0 for
146
- // every chunk, so with more than TOKENS_PER_MULTICALL tokens on one chain,
147
- // the second chunk's results were stored under the FIRST chunk's addresses
148
- // — every token past the first 100 got another token's name, symbol and
149
- // decimals. A wrong `decimals` misprints every amount rendered for that
150
- // token. Reading from the same partition that built the calls makes the
151
- // pairing structural rather than arithmetic.
152
111
  const chunkAddresses = addressChunks[chunkIndex];
153
112
  try {
154
113
  const batchResults = await client.multicall({
@@ -160,7 +119,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
160
119
  const symbol = batch[0].result;
161
120
  const name = batch[1].result;
162
121
  const decimals = Number(batch[2].result);
163
- // console.log(`Token ${tokenAddress} results:`, { symbol, name, decimals, errors: [batch[0].error, batch[1].error, batch[2].error] })
164
122
  if (name && symbol && !isNaN(decimals)) {
165
123
  results.set(tokenAddress.toLowerCase(), { name, symbol, decimals });
166
124
  }
@@ -172,9 +130,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
172
130
  }
173
131
  catch (error) {
174
132
  console.error(`Multicall failed for chain ${chainId}:`, error);
175
- // Only THIS chunk's addresses. Pushing every token meant one failing
176
- // chunk re-queued the whole set through the bytes32 fallback, including
177
- // the tokens that had just succeeded.
178
133
  fallback.push(...chunkAddresses);
179
134
  }
180
135
  }
@@ -185,7 +140,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
185
140
  const fallbackAddressChunks = splitIntoChunks(fallback, TOKENS_PER_MULTICALL);
186
141
  const fallbackChunkedCalls = addressChunksToCallChunks(fallbackAddressChunks, () => viem_1.erc20Abi_bytes32);
187
142
  for (const [chunkIndex, chunk] of fallbackChunkedCalls.entries()) {
188
- // Same pairing rule as the primary loop above.
189
143
  const chunkAddresses = fallbackAddressChunks[chunkIndex];
190
144
  try {
191
145
  console.log(`Executing fallback multicall for chain ${chainId} with ${chunk.flat().length} contracts`);
@@ -211,7 +165,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
211
165
  symbol: symbolString,
212
166
  decimals,
213
167
  });
214
- // Add to bytes32 whitelist for future optimization
215
168
  bytes32Whitelist.add(getStoreKey(chainId, tokenAddress));
216
169
  });
217
170
  }
@@ -221,14 +174,11 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
221
174
  }
222
175
  return results;
223
176
  }
224
- // Get token metadata synchronously (from store only)
225
177
  function getTokenMetadata(chainId, tokenAddress) {
226
178
  const storeKey = getStoreKey(chainId, tokenAddress);
227
179
  return tokenMetadataStore.get(storeKey) || null;
228
180
  }
229
- // Load token metadata for multiple tokens (called once on page load)
230
181
  async function loadTokenMetadata(tokens) {
231
- // Group tokens by chain ID for batching
232
182
  const tokensByChain = new Map();
233
183
  tokens.forEach(({ chainId, address }) => {
234
184
  if (!tokensByChain.has(chainId)) {
@@ -236,18 +186,13 @@ async function loadTokenMetadata(tokens) {
236
186
  }
237
187
  tokensByChain.get(chainId).push(address);
238
188
  });
239
- // Batch fetch for each chain
240
189
  const batchPromises = Array.from(tokensByChain.entries()).map(async ([chainId, addresses]) => {
241
190
  try {
242
- // console.log(`Loading token metadata for chain ${chainId} (${addresses.length} tokens):`, addresses)
243
191
  const results = await batchFetchTokenMetadata(chainId, addresses);
244
- // console.log(`Loaded ${results.size} token metadata results for chain ${chainId}:`, Array.from(results.entries()))
245
- // Store the results
246
192
  results.forEach((metadata, address) => {
247
193
  if (metadata) {
248
194
  const storeKey = getStoreKey(chainId, address);
249
195
  tokenMetadataStore.set(storeKey, metadata);
250
- // console.log(`Stored metadata for ${storeKey}:`, metadata)
251
196
  }
252
197
  });
253
198
  }
@@ -257,11 +202,9 @@ async function loadTokenMetadata(tokens) {
257
202
  });
258
203
  await Promise.allSettled(batchPromises);
259
204
  }
260
- // Get store size
261
205
  function getStoreSize() {
262
206
  return tokenMetadataStore.size;
263
207
  }
264
- // Utility functions for bridge transactions
265
208
  function getTokenAddressFromBridge(bridge) {
266
209
  return (bridge.originationToken?.address ||
267
210
  bridge.destinationToken?.address ||
package/dist/client.js CHANGED
@@ -3,58 +3,14 @@ import { chainKey, clientCache, clientFromChain as buildClient, MAX_SAME_METHOD_
3
3
  import { bsc } from 'viem/chains';
4
4
  import * as endpoints from './endpoints.js';
5
5
  import { evmChainsById } from './networks.js';
6
- /**
7
- * Chains whose public nodes reject BATCH remote procedure call requests (an
8
- * array-wrapped body). viem otherwise wraps even a single request in an array
9
- * when batching is on, which those nodes refuse — so every call fails and is
10
- * retried, burning through requests. Their clients are built with batching
11
- * disabled so requests go out as plain objects the node accepts. Binance Smart
12
- * Chain's `publicnode` endpoint is the known offender.
13
- */
14
6
  const chainsWithoutRpcBatching = new Set([bsc.id]);
15
- /**
16
- * The request-batching setting for a chain's client.
17
- *
18
- * `false` for chains whose nodes reject a batch body at all (see
19
- * {@link chainsWithoutRpcBatching}). Otherwise batching stays on, capped at
20
- * {@link MAX_SAME_METHOD_CALLS_PER_SECOND} so no single post can exceed the
21
- * proxy's per-method budget on its own and lose every call in it.
22
- *
23
- * The `wait` of ten milliseconds is viem's own default, restated here because
24
- * naming `batchSize` alone would otherwise drop it.
25
- *
26
- * @param chainId - the chain to resolve the batch setting for
27
- * @returns `false` when batching must be disabled, otherwise the batch config
28
- */
29
7
  export const rpcBatchSetting = (chainId) => chainsWithoutRpcBatching.has(chainId)
30
8
  ? false
31
9
  : { batchSize: MAX_SAME_METHOD_CALLS_PER_SECOND, wait: 10 };
32
- /**
33
- * A chain's own default endpoints, used when the editable table has no entry.
34
- *
35
- * @param chainId - the chain to look up
36
- * @returns the chain's default endpoints (possibly empty)
37
- */
38
10
  const defaultUrlsFor = (chainId) => {
39
11
  if (!chainId) {
40
12
  throw new Error('chainId is required');
41
13
  }
42
- // The APPLICATION's metadata first, viem's chain object only for the chains it
43
- // does not override.
44
- //
45
- // These are two different answers to the same question, and reading only the
46
- // second is why demoting a rate-limited Sepolia endpoint in the demo list
47
- // changed nothing: the seed built from that map, while THIS function — which
48
- // decides what a client actually talks to when the stored table is empty —
49
- // returned viem's own default and went on hitting the demoted host first.
50
- //
51
- // The bridge chains are overridden precisely because viem's defaults are not
52
- // the ones this application wants; the wider list (Arbitrum, Base, and the
53
- // rest) has no override and correctly falls through.
54
- //
55
- // THE DEMO LIST IS ASKED FOR BY NAME. `chainsMetadata` no longer carries the
56
- // shared `vk_demo` key, so a third party who builds on it never inherits that
57
- // key. This package is the Gibs interface's own client layer, so it opts in.
58
14
  const demoUrls = demoRpcUrlsFor(chainId);
59
15
  if (demoUrls.length) {
60
16
  return demoUrls;
@@ -66,22 +22,6 @@ const defaultUrlsFor = (chainId) => {
66
22
  const { http } = chain.rpcUrls.default;
67
23
  return [...(http ?? [])];
68
24
  };
69
- /**
70
- * Returns a viem {@link PublicClient} for a chain, reusing the cached instance
71
- * while the chain's endpoint list is unchanged. The cache key is derived from the
72
- * chain id plus its urls, so editing the list yields a fresh client and lets the
73
- * previous transport be garbage collected.
74
- *
75
- * The url source is the user-editable endpoint table; when it has no entry — or
76
- * an EMPTY one — the chain's own defaults are used instead. The empty case is not
77
- * hypothetical: the endpoint editor lets a user delete every entry for a chain,
78
- * and an empty array is truthy, so a `||` fallback here quietly built a client
79
- * with no transports at all and every read on that chain failed until the list
80
- * was restored.
81
- *
82
- * @param chainId - the chain to build a client for
83
- * @returns the cached or freshly built public client
84
- */
85
25
  export const clientFromChain = (chainId) => {
86
26
  const stored = endpoints.get(chainId);
87
27
  const urls = (stored?.length ? stored : defaultUrlsFor(chainId)).filter((url) => Boolean(url));
@@ -92,12 +32,6 @@ export const clientFromChain = (chainId) => {
92
32
  }
93
33
  const chain = evmChainsById.get(chainId);
94
34
  if (!chain) {
95
- // Previously this searched every chain viem ships and asserted a hit with a
96
- // `!`. That answered for chains this application does not support, and did
97
- // so badly: there are no endpoints for them, so the client was built with
98
- // none and silently fell back to viem's own public node — or, for a chain
99
- // viem had never heard of, died on an unreadable `undefined.id` several
100
- // frames away. Both are worse than saying so here.
101
35
  throw new Error(`Chain ${chainId} is not one of the supported networks.`);
102
36
  }
103
37
  const client = buildClient({ chain, urls, batch: rpcBatchSetting(chainId) });
package/dist/endpoints.js CHANGED
@@ -1,75 +1,23 @@
1
1
  import { demoRpcUrlsFor } from '@gibs/bridge-sdk/chains';
2
2
  import { Chains } from '@gibs/bridge-sdk/config';
3
3
  import { chainTable } from './chain-table.js';
4
- /**
5
- * The storage key holding the endpoint table.
6
- *
7
- * The literal must not change: users have their own nodes saved under it, and a
8
- * rename silently reverts every one of them to the defaults on the next load.
9
- */
10
4
  export const ENDPOINTS_STORAGE_KEY = 'rpcs';
11
- /**
12
- * EVERY SUPPORTED CHAIN GETS AN ENTRY, and the entry comes from viem.
13
- *
14
- * This used to seed three chains — PulseChain, Ethereum and Binance Smart Chain
15
- * — while the aggregators quote routes from seventy-odd. A chain absent from
16
- * this table is not refused; `clientFromChain` falls through to viem's own
17
- * public nodes for it. So every read on an aggregator origin went to a node
18
- * nobody chose, which is where the rate limiting came from, and the endpoint
19
- * editor could not show the chain at all: a reader whose Base node was throttled
20
- * had no way to replace it, because Base was not in the list they were editing.
21
- *
22
- * Seeding from `chainTable` fixes both at once. The urls are viem's own
23
- * defaults, which is what the three seeded chains always used — the change is
24
- * the breadth, not the source.
25
- */
26
5
  const seedFor = (chains) => chains.map((chain) => [Number(chain), demoRpcUrlsFor(Number(chain))]);
27
- /** The bridge's own chains, kept first so a picker built from this reads well. */
28
6
  const BRIDGE_CHAIN_IDS = [
29
7
  Number(Chains.PLS),
30
8
  Number(Chains.ETH),
31
9
  Number(Chains.BNB),
32
10
  ];
33
- /**
34
- * Every chain the application can reach, the bridge's own first.
35
- *
36
- * The bridge's three keep taking their urls from `demoRpcUrlsFor`, which is
37
- * where the product's own node choices live and which must win over viem's
38
- * generic default for them.
39
- */
40
11
  export const productionSeed = [
41
12
  ...seedFor([Chains.PLS, Chains.ETH, Chains.BNB]),
42
13
  ...chainTable
43
- .filter((entry) =>
44
- // The bridge's own three are seeded above, from `demoRpcUrlsFor`, and
45
- // must not be seeded twice. That map is where the product's node
46
- // choices live — demoting a rate-limited host there has to take effect,
47
- // and a table entry added after it would silently win.
48
- !BRIDGE_CHAIN_IDS.includes(entry.id) &&
49
- // A PRODUCTION BUILD PROMISES NOT TO OFFER A TEST NETWORK, and the
50
- // endpoint table is one of the places that promise can be broken: the
51
- // chains seeded here are the chains the endpoint editor lists. The
52
- // table carries test networks deliberately, because a client still has
53
- // to be buildable for them on a testnet build; this is where they are
54
- // held back.
14
+ .filter((entry) => !BRIDGE_CHAIN_IDS.includes(entry.id) &&
55
15
  !entry.isTestnet)
56
16
  .map((entry) => [entry.id, [...entry.http]]),
57
17
  ];
58
- /** The bridge's test chains, for a build that is not production. */
59
18
  export const testnetSeed = seedFor([Chains.V4PLS, Chains.SEP]);
60
- /** The seed the next load starts from. */
61
19
  let seed = productionSeed;
62
- /**
63
- * Where the table is persisted. `undefined` means "use the browser default,
64
- * resolved on first use"; null means "nowhere".
65
- */
66
20
  let storage;
67
- /**
68
- * Resolves the browser's `localStorage` without letting a failure escape.
69
- *
70
- * Touching the global can throw (private windows, Node 22 without a storage
71
- * file) or print a warning, so nothing calls this at import time.
72
- */
73
21
  const browserStorage = () => {
74
22
  try {
75
23
  return typeof globalThis.localStorage === 'undefined'
@@ -80,14 +28,12 @@ const browserStorage = () => {
80
28
  return null;
81
29
  }
82
30
  };
83
- /** The persistence target in effect, resolving the default on first call. */
84
31
  const activeStorage = () => {
85
32
  if (storage === undefined) {
86
33
  storage = browserStorage();
87
34
  }
88
35
  return storage;
89
36
  };
90
- /** The live table, or null while it has not been loaded yet. */
91
37
  let value = null;
92
38
  const listeners = new Set();
93
39
  const emit = () => {
@@ -95,17 +41,6 @@ const emit = () => {
95
41
  listener();
96
42
  }
97
43
  };
98
- /**
99
- * Replaces the seed table and the persistence target.
100
- *
101
- * Both fields are optional so a host can override one without restating the
102
- * other. The loaded table is discarded either way, so the next read rebuilds
103
- * from the new seed merged with whatever is stored — which means this is safe to
104
- * call after something has already read, not only at startup.
105
- *
106
- * @param options.seed - the entries to start from when storage holds nothing
107
- * @param options.storage - where the table is persisted, or null for nowhere
108
- */
109
44
  export const configureEndpoints = ({ seed: nextSeed, storage: nextStorage, }) => {
110
45
  if (nextSeed !== undefined) {
111
46
  seed = nextSeed;
@@ -116,14 +51,7 @@ export const configureEndpoints = ({ seed: nextSeed, storage: nextStorage, }) =>
116
51
  value = null;
117
52
  emit();
118
53
  };
119
- /** Serializes one chain's list the way it is persisted: `chainId,url,url`. */
120
54
  export const key = (chain, list) => `${chain},${list.join(',')}`;
121
- /**
122
- * Parses a stored blob back into a table, merged onto the seeded entries.
123
- *
124
- * @param entry - the persisted blob, or null when nothing is stored
125
- * @returns the merged table, or null when there was nothing to parse
126
- */
127
55
  export const parse = (entry) => {
128
56
  if (!entry) {
129
57
  return null;
@@ -134,13 +62,6 @@ export const parse = (entry) => {
134
62
  });
135
63
  return new Map([...seed, ...stored]);
136
64
  };
137
- /**
138
- * Reads the persisted table, or null when there is nothing usable to read.
139
- *
140
- * Any failure falls back to the seeded defaults rather than propagating: a
141
- * corrupt or unreadable entry must not be the reason the application cannot
142
- * reach a chain at all.
143
- */
144
65
  const readStored = () => {
145
66
  const target = activeStorage();
146
67
  if (!target) {
@@ -154,41 +75,22 @@ const readStored = () => {
154
75
  return null;
155
76
  }
156
77
  };
157
- /** The table, loaded from storage the first time it is asked for. */
158
78
  const loaded = () => {
159
79
  if (!value) {
160
80
  value = readStored() ?? new Map(seed);
161
81
  }
162
82
  return value;
163
83
  };
164
- /** Serializes every entry, one chain per line. */
165
84
  export const stringify = () => [...loaded().entries()].map(([chainId, list]) => key(chainId, list)).join('\n');
166
- /**
167
- * Subscribes to changes in the endpoint table.
168
- *
169
- * @param listener - called after any mutation
170
- * @returns the unsubscribe function
171
- */
172
85
  export const subscribe = (listener) => {
173
86
  listeners.add(listener);
174
87
  return () => {
175
88
  listeners.delete(listener);
176
89
  };
177
90
  };
178
- /**
179
- * The current table.
180
- *
181
- * The identity is stable until something changes it — every mutating accessor
182
- * replaces the map rather than mutating in place — which is what lets a caller
183
- * use this directly as a `useSyncExternalStore` snapshot without re-rendering
184
- * forever.
185
- */
186
91
  export const getSnapshot = () => loaded();
187
- /** The url list for a chain, or null when it has no entry. */
188
92
  export const get = (chain) => loaded().get(chain) ?? null;
189
- /** All `[chainId, urls]` entries as a fresh array. */
190
93
  export const entries = () => [...loaded().entries()];
191
- /** Replaces a chain's url list, persists it, and notifies subscribers. */
192
94
  export const setEndpoints = (chain, list) => {
193
95
  const next = new Map(loaded());
194
96
  next.set(chain, list);
@@ -196,7 +98,6 @@ export const setEndpoints = (chain, list) => {
196
98
  activeStorage()?.setItem(ENDPOINTS_STORAGE_KEY, stringify());
197
99
  emit();
198
100
  };
199
- /** Replaces the url at index `i`; a no-op when the value is unchanged. */
200
101
  export const update = (chain, i, url) => {
201
102
  const list = get(chain) ?? [];
202
103
  if (list[i] === url) {
@@ -206,22 +107,15 @@ export const update = (chain, i, url) => {
206
107
  next[i] = url;
207
108
  setEndpoints(chain, next);
208
109
  };
209
- /** Removes the url at index `i`. */
210
110
  export const remove = (chain, i) => {
211
111
  const next = (get(chain) ?? []).slice(0);
212
112
  next.splice(i, 1);
213
113
  setEndpoints(chain, next);
214
114
  };
215
- /**
216
- * Applies `addition` to a chain's url list and stores the result, keeping only
217
- * the first item if it is empty (the leading "add new" slot) and dropping every
218
- * other empty. A no-op when the filtered list is unchanged.
219
- */
220
115
  export const add = (chain, addition = (urls) => [''].concat(urls)) => {
221
116
  const before = get(chain) ?? [];
222
117
  const list = addition(before.slice(0));
223
118
  const filteredList = list.filter((val, i) => {
224
- // only the first item in the list may be empty
225
119
  if (!val && !i) {
226
120
  return true;
227
121
  }
@@ -233,14 +127,12 @@ export const add = (chain, addition = (urls) => [''].concat(urls)) => {
233
127
  }
234
128
  setEndpoints(chain, filteredList);
235
129
  };
236
- /** Whether `list` already contains the chain's canonical default endpoint. */
237
130
  export const hasDefault = (chain, list) => {
238
131
  const defaultUrl = demoRpcUrlsFor(chain)[0];
239
132
  if (!defaultUrl)
240
133
  return false;
241
134
  return list.includes(defaultUrl);
242
135
  };
243
- /** Appends the chain's canonical default endpoints back onto its list. */
244
136
  export const restoreDefault = (chain) => {
245
137
  add(chain, (l) => l.concat(demoRpcUrlsFor(chain)));
246
138
  };
package/dist/image.js CHANGED
@@ -2,62 +2,7 @@ import * as imageLinks from '@gibs/bridge-sdk/image-links';
2
2
  import { ecosystemByChainId, relayChainIds } from '@gibs/bridge-sdk/relay-quote';
3
3
  import { zeroAddress } from 'viem';
4
4
  import { chainTable } from './chain-table.js';
5
- /**
6
- * Chain-logo resolution, in one place.
7
- *
8
- * gib.show serves almost every chain a route can start from — including the
9
- * non-Ethereum ones — but it keys them by a CAIP-2 style identifier rather than
10
- * by Relay's invented decimal ids, so the two have to be mapped. Only Eclipse
11
- * and Hyperliquid are genuinely absent from it, and those alone fall back to
12
- * Relay's own icon service.
13
- *
14
- * This is a module rather than an inline template string because getting the
15
- * key wrong is invisible: a 404 in an `<img src>` is drawn by the browser as a
16
- * broken-image glyph, so the mistake surfaces as a blemish on a token pill
17
- * rather than as an error anyone would go looking for.
18
- */
19
- /**
20
- * Relay's public chain-icon service, keyed on Relay's own chain identifiers —
21
- * the authority for the ids it invented.
22
- *
23
- * The `light` variant is the full-colour brand mark (the pair is light/dark
24
- * BACKGROUND, not a monochrome inversion), so one variant serves both of our
25
- * themes. Not every id is populated — The Open Network answers 403, which is
26
- * what the bundled asset used to exist for — so callers must still tolerate a
27
- * badge that fails to load. Only Eclipse and Hyperliquid reach this now.
28
- *
29
- * @param chainId - a Relay chain identifier
30
- * @returns the icon url
31
- */
32
5
  export const relayChainIconUrl = (chainId) => `https://assets.relay.link/icons/${chainId}/light.png`;
33
- /**
34
- * gib.show's own key for a chain that Relay reaches us under a pseudo id.
35
- *
36
- * THE SERVICE WAS NEVER MISSING THESE CHAINS — WE WERE ASKING BY THE WRONG KEY.
37
- * gib.show keys every chain by a CAIP-2 style identifier: `eip155-1`,
38
- * `solana-501`, `bip122-0`. Relay invented its own decimal ids for the
39
- * non-Ethereum origins (Solana is 792703809, Bitcoin 8253038), and asking
40
- * gib.show for one of those 404s — which read as "gib.show does not serve
41
- * Solana" and sent every non-Ethereum badge to a second service. It serves them
42
- * all, under its own key.
43
- *
44
- * Each entry below was verified twice: the url returns 200 with a real PNG, and
45
- * the picture was LOOKED AT and is the chain's genuine mark. A 200 alone proves
46
- * nothing here — `/image/999` returns 200 and hands back a completely different
47
- * chain's logo, which is why an identifier is only listed once someone has seen
48
- * what comes back.
49
- *
50
- * ECLIPSE AND HYPERLIQUID ARE ABSENT ON PURPOSE. Neither appears anywhere in
51
- * gib.show's network list under any key, so they keep Relay's service. Guessing
52
- * a plausible identifier for them would be worse than falling back: Hyperliquid
53
- * in particular collides with an unrelated chain at id 999, so a guess renders
54
- * the wrong company's logo rather than none at all.
55
- *
56
- * The pay-by-hand chains (Zcash and, later, its siblings) are NOT listed by
57
- * hand here. `bridge-sdk`'s `image-links.ts` is the one place that key is
58
- * declared — see its `pseudoChainGibShowIdentifier` — and this table spreads
59
- * that map in, so a pay-by-hand chain added there needs no matching edit here.
60
- */
61
6
  const gibShowChainIdentifier = {
62
7
  [relayChainIds.solana]: 'solana-501',
63
8
  [relayChainIds.bitcoin]: 'bip122-0',
@@ -65,29 +10,9 @@ const gibShowChainIdentifier = {
65
10
  [relayChainIds.ton]: 'ton-607',
66
11
  ...imageLinks.pseudoChainGibShowIdentifier,
67
12
  };
68
- /**
69
- * Resolves the logo url for a chain, choosing the service that can serve it.
70
- *
71
- * A chain gib.show knows under its own identifier wins outright
72
- * ({@link gibShowChainIdentifier}). Otherwise an Ethereum-Virtual-Machine chain
73
- * goes to gib.show by number, honouring the configured image root so a
74
- * self-hosted deployment is respected rather than hard-coding the public host.
75
- * What remains is Eclipse and Hyperliquid, which gib.show does not carry, and
76
- * they go to Relay.
77
- *
78
- * @param chainId - the decimal chain id, Relay's pseudo identifiers included
79
- * @param displayPx - the CSS pixel size the logo renders at; when supplied,
80
- * gib.show is asked for twice that in webp per its retina guidance. Ignored
81
- * for a Relay-served icon and for an identifier-keyed mark, neither of which
82
- * takes sizing parameters.
83
- * @returns an image url for the chain
84
- */
85
13
  export const chainLogoUrl = ({ chainId, displayPx, }) => {
86
14
  const identifier = gibShowChainIdentifier[chainId];
87
15
  if (identifier !== undefined) {
88
- // gib.show serves this chain, just not under Relay's number. No sizing
89
- // parameters: these are fixed-size marks rather than the resizable images
90
- // the numeric endpoint serves.
91
16
  return `${imageLinks.getImageRoot()}/image/${identifier}`;
92
17
  }
93
18
  if (ecosystemByChainId(chainId) !== 'evm') {
@@ -99,44 +24,8 @@ export const chainLogoUrl = ({ chainId, displayPx, }) => {
99
24
  }
100
25
  return `${base}?w=${displayPx * 2}&h=${displayPx * 2}&format=webp`;
101
26
  };
102
- /**
103
- * The chain a native coin actually belongs to, found by its symbol.
104
- *
105
- * WHY THIS IS NEEDED. gib.show serves a coin's own picture under
106
- * `<chain>/<zero address>`, and it carries that picture only for the chain the
107
- * coin is native to — not for every chain the coin has been bridged onto. Ether
108
- * on Base is the case that exposed it: `8453/<zero address>` is a 404, so the
109
- * lookup fell through to the chain mark and drew Base's blue disc where the
110
- * ether diamond belongs. The same picture is one source away under `1/<zero
111
- * address>`, and gib.show's multi-source lookup will cross chains to reach it.
112
- *
113
- * READ FROM THE TABLE, NOT FROM A LIST WRITTEN HERE. The generated chain table
114
- * orders the bridge's own chains first and the rest in the order the product
115
- * chose, so the EARLIEST entry carrying a symbol is the chain that coin came
116
- * from: ether resolves to Ethereum ahead of the dozen chains that also call
117
- * their coin ETH, and the mapping stays right as the table grows. The table is
118
- * reversed before the map is built because a later `set` wins — reversing makes
119
- * the earliest entry the last one written.
120
- *
121
- * A coin whose home chain has no dedicated picture — Binance Coin, Polygon
122
- * Ecosystem Token, Avalanche — loses nothing. Their home chain IS the chain
123
- * they are asked about, so the list collapses to what it already was, and for
124
- * a chain's own coin the chain mark is the coin mark.
125
- */
126
27
  const homeChainOfSymbol = new Map([...chainTable].reverse().map((entry) => [entry.nativeCurrency.symbol, entry.id]));
127
- /** Every chain's own native symbol, for resolving a coin from its chain alone. */
128
28
  const symbolOfChain = new Map(chainTable.map((entry) => [entry.id, entry.nativeCurrency.symbol]));
129
- /**
130
- * The gib.show sources for a chain's NATIVE COIN, best first.
131
- *
132
- * The service serves the first source that resolves: the coin as this chain
133
- * keys it, then the coin as its home chain keys it, then the chain's own mark.
134
- * The last is an honest fallback rather than a mistake — for a chain's own coin
135
- * the two marks are the same picture.
136
- *
137
- * @param chainId - the chain the coin is being shown on
138
- * @returns the ordered source list, for {@link imageLinks.images}
139
- */
140
29
  export const nativeCoinImageSources = (chainId) => {
141
30
  const sources = [`${chainId}/${zeroAddress}`];
142
31
  const symbol = symbolOfChain.get(chainId);
@@ -147,10 +36,4 @@ export const nativeCoinImageSources = (chainId) => {
147
36
  sources.push(`${chainId}/`);
148
37
  return sources;
149
38
  };
150
- /**
151
- * Resolves the picture of a chain's native coin, as opposed to of the chain.
152
- *
153
- * @param chainId - the chain the coin is being shown on
154
- * @returns an image url
155
- */
156
39
  export const nativeCoinLogoUrl = (chainId) => imageLinks.images(nativeCoinImageSources(chainId));