@gibs/bridge-client 1.18.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.
package/dist/index.js CHANGED
@@ -1,18 +1,3 @@
1
- /**
2
- * Browser-side machinery for talking to the chains the bridge supports.
3
- *
4
- * Everything here is framework-free. It is the layer between `@gibs/bridge-sdk`,
5
- * which knows about pathways, quotes and fees but performs no input or output,
6
- * and an application, which renders. Endpoint resolution, public clients, chain
7
- * reads, token metadata, caching and logo resolution all live here so that a
8
- * second application does not have to rebuild them — and so that the rules they
9
- * encode (which node answers for a chain, which image service knows a chain's
10
- * mark) have exactly one home.
11
- *
12
- * Subpath exports are the intended way in — `@gibs/bridge-client/client`,
13
- * `/endpoints`, `/image` and so on — so that importing one does not pull the
14
- * rest. This barrel exists for consumers that would rather not think about it.
15
- */
16
1
  export { Cache } from './cache.js';
17
2
  export { checkAllowance } from './chain-read.js';
18
3
  export { clientFromChain, rpcBatchSetting } from './client.js';
package/dist/networks.js CHANGED
@@ -1,24 +1,5 @@
1
1
  import { registerChainNames } from '@gibs/bridge-sdk/chain-names';
2
2
  import { chainTable } from './chain-table.js';
3
- /**
4
- * Turns one row of the generated table into the shape viem wants.
5
- *
6
- * NAMED VIEM IMPORTS USED TO LIVE HERE — 37 of them, each pulling that chain's
7
- * whole definition including fee logic, formatters and contract addresses this
8
- * application never reads. That cost about 3.7 kB compressed for a third of the
9
- * chains the aggregators quote; naming all 73 would have cost about 7.3 kB
10
- * against roughly 7.8 kB of headroom under the first-load budget. The generated
11
- * table carries the same 73 in 2.6 kB, so the whole supported set now weighs
12
- * less than the third of it that shipped before.
13
- *
14
- * A namespace import is still never used, for the reason the old comment here
15
- * gave: `Object.values(chains)` defeats tree-shaking and emitted all ~674
16
- * definitions, measured at 255 kB. The generator does that read in Node, at
17
- * build time, where it costs a reader nothing.
18
- *
19
- * `blockExplorers` is omitted rather than faked when a chain has no explorer —
20
- * viem treats the field as optional and an empty url would render a dead link.
21
- */
22
3
  const toViemChain = (entry) => ({
23
4
  id: entry.id,
24
5
  name: entry.name,
@@ -27,53 +8,11 @@ const toViemChain = (entry) => ({
27
8
  ...(entry.explorer === null
28
9
  ? {}
29
10
  : { blockExplorers: { default: { name: 'Explorer', url: entry.explorer } } }),
30
- // WITHOUT THIS, NOTHING CAN BATCH A READ. viem's `multicall` action reads the
31
- // Multicall3 address off the chain and throws `ChainDoesNotSupportContract`
32
- // when it is absent, so every chain built here refused — including
33
- // PulseChain, whose token-metadata fallback failed with exactly that.
34
- //
35
- // It went missing when this table replaced viem's own chain objects to keep
36
- // 255 kB of unused per-chain data out of the build. The table kept the four
37
- // fields a TRANSPORT needs and dropped the one field an ACTION needs.
38
- //
39
- // Read per chain, never assumed: the canonical `0xcA11bde0…` covers most, but
40
- // there are 8 distinct deployments across the chains listed here.
41
11
  ...(entry.multicall3 === null
42
12
  ? {}
43
13
  : { contracts: { multicall3: { address: entry.multicall3 } } }),
44
14
  });
45
- /**
46
- * Every Ethereum-Virtual-Machine chain this client can build a public client for.
47
- *
48
- * The leading entries are the bridge's own chains; the rest are the routing
49
- * destinations reachable through the aggregators. Ordering is preserved because
50
- * chain pickers render it directly.
51
- *
52
- * Solana and Bitcoin are deliberately absent. They are supported ORIGINS, but
53
- * they are not Ethereum-style chains: they are keyed by a genesis hash and by
54
- * their own string rather than by a number, and nothing here can build a client
55
- * for them. Anything wallet-facing that needs them keys off the aggregator's
56
- * chain identifiers instead.
57
- */
58
15
  export const evmChains = chainTable.map(toViemChain);
59
- /**
60
- * Lookup from a chain id to its viem chain definition, for supported chains only.
61
- *
62
- * Keyed as `string | number` because callers hold ids that have been through a
63
- * url, a wallet, or a quote response, and a lookup that silently misses on a
64
- * numeric-versus-string mismatch reads as "chain not supported".
65
- */
66
16
  export const evmChainsById = new Map(evmChains.map((chain) => [chain.id, chain]));
67
- // Hand these names to the SDK's display-name table so ONE function answers
68
- // "what is this chain called" everywhere. Done at module load, before anything
69
- // renders, because a name that arrives late is a name that changes under the
70
- // reader — which is precisely the flicker this removes. The SDK's own entries
71
- // win on conflict, so the product's chosen spellings are not overwritten.
72
17
  registerChainNames(evmChains.map((chain) => [chain.id, chain.name]));
73
- /**
74
- * Whether this client can reach a chain over Ethereum-style remote procedure calls.
75
- *
76
- * @param chainId - the chain id to test
77
- * @returns true when the chain has a definition here
78
- */
79
18
  export const isSupportedEvmChain = (chainId) => evmChainsById.has(chainId);
@@ -3,28 +3,13 @@ import { isNativeAsset } from '@gibs/bridge-sdk/ecosystems';
3
3
  import { erc20Abi, erc20Abi_bytes32, hexToString } from 'viem';
4
4
  import { clientFromChain } from './client.js';
5
5
  import { evmChainsById } from './networks.js';
6
- /**
7
- * How many tokens one multicall asks about. Results come back flat, so each
8
- * loop below MUST pair a result triple with the address chunk that produced it
9
- * — see the primary loop for what indexing the flat array cost.
10
- */
11
6
  const TOKENS_PER_MULTICALL = 100;
12
- /**
13
- * Splits a list into consecutive runs of at most `size` items, in order.
14
- *
15
- * @param items - the list to split
16
- * @param size - the most items one run holds
17
- * @returns the runs; the last one may be shorter
18
- */
19
7
  const splitIntoChunks = (items, size) => Array.from({ length: Math.ceil(items.length / size) }, (_unused, index) => items.slice(index * size, (index + 1) * size));
20
8
  const bytes32Whitelist = new Set();
21
- // In-memory store for token metadata (loaded once, no persistence)
22
9
  const tokenMetadataStore = new Map();
23
- // Generate store key
24
10
  export function getStoreKey(chainId, tokenAddress) {
25
11
  return `${chainId}:${tokenAddress.toLowerCase()}`;
26
12
  }
27
- // Parse a ChainScopedAddress into its components
28
13
  export function parseChainScopedAddress(key) {
29
14
  const [chainIdStr, address] = key.split(':');
30
15
  const chainId = parseInt(chainIdStr ?? '', 10);
@@ -39,7 +24,6 @@ export function parseChainScopedAddress(key) {
39
24
  address: address,
40
25
  };
41
26
  }
42
- // Parse a string key (chainId:address format) into its components with proper types
43
27
  export function parseTokenKey(key) {
44
28
  const [chainIdStr, address] = key.split(':');
45
29
  const chainId = parseInt(chainIdStr ?? '', 10);
@@ -49,21 +33,17 @@ export function parseTokenKey(key) {
49
33
  if (!address) {
50
34
  throw new Error(`Invalid address in token key: ${address}`);
51
35
  }
52
- // Ensure address is properly formatted as Hex
53
36
  const hexAddress = address.startsWith('0x') ? address : `0x${address}`;
54
37
  return {
55
38
  chainId,
56
39
  address: hexAddress,
57
40
  };
58
41
  }
59
- // Get native token metadata
60
42
  function getNativeTokenMetadata(chainId) {
61
43
  const chain = evmChainsById.get(chainId);
62
- // Safely get native token info from SDK
63
44
  let name = chain?.nativeCurrency?.name || 'Ether';
64
45
  let symbol = chain?.nativeCurrency?.symbol || 'ETH';
65
46
  const decimals = chain?.nativeCurrency?.decimals || 18;
66
- // Try to get more specific info from SDK if available
67
47
  try {
68
48
  const chainKey = toChain(chainId);
69
49
  const sdkName = nativeTokenName[chainKey];
@@ -76,29 +56,21 @@ function getNativeTokenMetadata(chainId) {
76
56
  }
77
57
  }
78
58
  catch {
79
- // Fallback to viem chain info
80
59
  }
81
60
  return { name, symbol, decimals };
82
61
  }
83
- // Batch fetch token metadata for multiple tokens on the same chain
84
62
  async function batchFetchTokenMetadata(chainId, tokenAddresses) {
85
63
  const results = new Map();
86
64
  if (tokenAddresses.length === 0)
87
65
  return results;
88
- // Get the chain and client
89
66
  const chain = evmChainsById.get(chainId);
90
67
  if (!chain) {
91
68
  throw new Error(`Chain not found for chainId: ${chainId}`);
92
69
  }
93
70
  const client = clientFromChain(chainId);
94
- // Separate native tokens from ERC20 tokens
95
71
  const nativeTokens = [];
96
72
  const erc20Tokens = [];
97
73
  tokenAddresses.forEach((address) => {
98
- // The registry's rule, not a hand-written one. Two spellings of the same
99
- // comparison sat here — an exact match OR a lower-cased one — which is what
100
- // a duplicated rule looks like once nobody is sure which half is load
101
- // bearing.
102
74
  if (isNativeAsset(address, 'evm')) {
103
75
  nativeTokens.push(address);
104
76
  }
@@ -106,17 +78,13 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
106
78
  erc20Tokens.push(address);
107
79
  }
108
80
  });
109
- // Handle native tokens
110
81
  const nativeMetadata = getNativeTokenMetadata(chainId);
111
82
  nativeTokens.forEach((address) => {
112
83
  results.set(address.toLowerCase(), nativeMetadata);
113
84
  });
114
- // Handle ERC20 tokens with batch multicall
115
85
  if (erc20Tokens.length === 0) {
116
- // console.log(`No ERC20 tokens to process for chain ${chainId}`)
117
86
  return results;
118
87
  }
119
- // console.log(`Processing ${erc20Tokens.length} ERC20 tokens for chain ${chainId}:`, erc20Tokens)
120
88
  const addressChunks = splitIntoChunks(erc20Tokens, TOKENS_PER_MULTICALL);
121
89
  const methods = ['symbol', 'name', 'decimals'];
122
90
  const addressChunksToCallChunks = (addressChunks, abi) => addressChunks.map((chunk) => chunk.map((address) => methods.map((functionName) => ({
@@ -126,18 +94,9 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
126
94
  allowFailure: true,
127
95
  args: [],
128
96
  }))));
129
- // Try with standard ERC20 ABI first
130
97
  const chunkedCalls = addressChunksToCallChunks(addressChunks, (address) => bytes32Whitelist.has(getStoreKey(chainId, address)) ? erc20Abi_bytes32 : erc20Abi);
131
98
  const fallback = [];
132
99
  for (const [chunkIndex, chunk] of chunkedCalls.entries()) {
133
- // The addresses THIS chunk asked about. Indexing the flat `erc20Tokens`
134
- // here instead was a silent data-corruption bug: `index` restarts at 0 for
135
- // every chunk, so with more than TOKENS_PER_MULTICALL tokens on one chain,
136
- // the second chunk's results were stored under the FIRST chunk's addresses
137
- // — every token past the first 100 got another token's name, symbol and
138
- // decimals. A wrong `decimals` misprints every amount rendered for that
139
- // token. Reading from the same partition that built the calls makes the
140
- // pairing structural rather than arithmetic.
141
100
  const chunkAddresses = addressChunks[chunkIndex];
142
101
  try {
143
102
  const batchResults = await client.multicall({
@@ -149,7 +108,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
149
108
  const symbol = batch[0].result;
150
109
  const name = batch[1].result;
151
110
  const decimals = Number(batch[2].result);
152
- // console.log(`Token ${tokenAddress} results:`, { symbol, name, decimals, errors: [batch[0].error, batch[1].error, batch[2].error] })
153
111
  if (name && symbol && !isNaN(decimals)) {
154
112
  results.set(tokenAddress.toLowerCase(), { name, symbol, decimals });
155
113
  }
@@ -161,9 +119,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
161
119
  }
162
120
  catch (error) {
163
121
  console.error(`Multicall failed for chain ${chainId}:`, error);
164
- // Only THIS chunk's addresses. Pushing every token meant one failing
165
- // chunk re-queued the whole set through the bytes32 fallback, including
166
- // the tokens that had just succeeded.
167
122
  fallback.push(...chunkAddresses);
168
123
  }
169
124
  }
@@ -174,7 +129,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
174
129
  const fallbackAddressChunks = splitIntoChunks(fallback, TOKENS_PER_MULTICALL);
175
130
  const fallbackChunkedCalls = addressChunksToCallChunks(fallbackAddressChunks, () => erc20Abi_bytes32);
176
131
  for (const [chunkIndex, chunk] of fallbackChunkedCalls.entries()) {
177
- // Same pairing rule as the primary loop above.
178
132
  const chunkAddresses = fallbackAddressChunks[chunkIndex];
179
133
  try {
180
134
  console.log(`Executing fallback multicall for chain ${chainId} with ${chunk.flat().length} contracts`);
@@ -200,7 +154,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
200
154
  symbol: symbolString,
201
155
  decimals,
202
156
  });
203
- // Add to bytes32 whitelist for future optimization
204
157
  bytes32Whitelist.add(getStoreKey(chainId, tokenAddress));
205
158
  });
206
159
  }
@@ -210,14 +163,11 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
210
163
  }
211
164
  return results;
212
165
  }
213
- // Get token metadata synchronously (from store only)
214
166
  export function getTokenMetadata(chainId, tokenAddress) {
215
167
  const storeKey = getStoreKey(chainId, tokenAddress);
216
168
  return tokenMetadataStore.get(storeKey) || null;
217
169
  }
218
- // Load token metadata for multiple tokens (called once on page load)
219
170
  export async function loadTokenMetadata(tokens) {
220
- // Group tokens by chain ID for batching
221
171
  const tokensByChain = new Map();
222
172
  tokens.forEach(({ chainId, address }) => {
223
173
  if (!tokensByChain.has(chainId)) {
@@ -225,18 +175,13 @@ export async function loadTokenMetadata(tokens) {
225
175
  }
226
176
  tokensByChain.get(chainId).push(address);
227
177
  });
228
- // Batch fetch for each chain
229
178
  const batchPromises = Array.from(tokensByChain.entries()).map(async ([chainId, addresses]) => {
230
179
  try {
231
- // console.log(`Loading token metadata for chain ${chainId} (${addresses.length} tokens):`, addresses)
232
180
  const results = await batchFetchTokenMetadata(chainId, addresses);
233
- // console.log(`Loaded ${results.size} token metadata results for chain ${chainId}:`, Array.from(results.entries()))
234
- // Store the results
235
181
  results.forEach((metadata, address) => {
236
182
  if (metadata) {
237
183
  const storeKey = getStoreKey(chainId, address);
238
184
  tokenMetadataStore.set(storeKey, metadata);
239
- // console.log(`Stored metadata for ${storeKey}:`, metadata)
240
185
  }
241
186
  });
242
187
  }
@@ -246,11 +191,9 @@ export async function loadTokenMetadata(tokens) {
246
191
  });
247
192
  await Promise.allSettled(batchPromises);
248
193
  }
249
- // Get store size
250
194
  export function getStoreSize() {
251
195
  return tokenMetadataStore.size;
252
196
  }
253
- // Utility functions for bridge transactions
254
197
  export function getTokenAddressFromBridge(bridge) {
255
198
  return (bridge.originationToken?.address ||
256
199
  bridge.destinationToken?.address ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gibs/bridge-client",
3
- "version": "1.18.0",
3
+ "version": "1.20.0",
4
4
  "description": "Browser-side endpoints, clients, and caching for a Gibs Finance bridge interface.",
5
5
  "keywords": [
6
6
  "ethereum",
@@ -274,8 +274,8 @@
274
274
  "test:watch": "vitest"
275
275
  },
276
276
  "dependencies": {
277
- "@gibs/bridge-sdk": "^1.18.0",
278
- "@gibs/common": "^1.18.0"
277
+ "@gibs/bridge-sdk": "^1.20.0",
278
+ "@gibs/common": "^1.20.0"
279
279
  },
280
280
  "peerDependencies": {
281
281
  "viem": ">=2.35.0 <3"