@gibs/bridge-client 1.19.0 → 1.26.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.
@@ -1,30 +1,16 @@
1
1
  import { nativeTokenName, nativeTokenSymbol, toChain } from '@gibs/bridge-sdk/config';
2
2
  import { isNativeAsset } from '@gibs/bridge-sdk/ecosystems';
3
- import { erc20Abi, erc20Abi_bytes32, hexToString } from 'viem';
3
+ import { decodeBytes32Text, shortAddressLabel } from '@gibs/common/erc20';
4
+ import { erc20Abi, erc20Abi_bytes32, isAddress } from 'viem';
4
5
  import { clientFromChain } from './client.js';
5
6
  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
7
  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
8
  const splitIntoChunks = (items, size) => Array.from({ length: Math.ceil(items.length / size) }, (_unused, index) => items.slice(index * size, (index + 1) * size));
20
9
  const bytes32Whitelist = new Set();
21
- // In-memory store for token metadata (loaded once, no persistence)
22
10
  const tokenMetadataStore = new Map();
23
- // Generate store key
24
11
  export function getStoreKey(chainId, tokenAddress) {
25
12
  return `${chainId}:${tokenAddress.toLowerCase()}`;
26
13
  }
27
- // Parse a ChainScopedAddress into its components
28
14
  export function parseChainScopedAddress(key) {
29
15
  const [chainIdStr, address] = key.split(':');
30
16
  const chainId = parseInt(chainIdStr ?? '', 10);
@@ -39,7 +25,6 @@ export function parseChainScopedAddress(key) {
39
25
  address: address,
40
26
  };
41
27
  }
42
- // Parse a string key (chainId:address format) into its components with proper types
43
28
  export function parseTokenKey(key) {
44
29
  const [chainIdStr, address] = key.split(':');
45
30
  const chainId = parseInt(chainIdStr ?? '', 10);
@@ -49,21 +34,17 @@ export function parseTokenKey(key) {
49
34
  if (!address) {
50
35
  throw new Error(`Invalid address in token key: ${address}`);
51
36
  }
52
- // Ensure address is properly formatted as Hex
53
37
  const hexAddress = address.startsWith('0x') ? address : `0x${address}`;
54
38
  return {
55
39
  chainId,
56
40
  address: hexAddress,
57
41
  };
58
42
  }
59
- // Get native token metadata
60
43
  function getNativeTokenMetadata(chainId) {
61
44
  const chain = evmChainsById.get(chainId);
62
- // Safely get native token info from SDK
63
45
  let name = chain?.nativeCurrency?.name || 'Ether';
64
46
  let symbol = chain?.nativeCurrency?.symbol || 'ETH';
65
47
  const decimals = chain?.nativeCurrency?.decimals || 18;
66
- // Try to get more specific info from SDK if available
67
48
  try {
68
49
  const chainKey = toChain(chainId);
69
50
  const sdkName = nativeTokenName[chainKey];
@@ -76,29 +57,21 @@ function getNativeTokenMetadata(chainId) {
76
57
  }
77
58
  }
78
59
  catch {
79
- // Fallback to viem chain info
80
60
  }
81
61
  return { name, symbol, decimals };
82
62
  }
83
- // Batch fetch token metadata for multiple tokens on the same chain
84
63
  async function batchFetchTokenMetadata(chainId, tokenAddresses) {
85
64
  const results = new Map();
86
65
  if (tokenAddresses.length === 0)
87
66
  return results;
88
- // Get the chain and client
89
67
  const chain = evmChainsById.get(chainId);
90
68
  if (!chain) {
91
69
  throw new Error(`Chain not found for chainId: ${chainId}`);
92
70
  }
93
71
  const client = clientFromChain(chainId);
94
- // Separate native tokens from ERC20 tokens
95
72
  const nativeTokens = [];
96
73
  const erc20Tokens = [];
97
74
  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
75
  if (isNativeAsset(address, 'evm')) {
103
76
  nativeTokens.push(address);
104
77
  }
@@ -106,17 +79,13 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
106
79
  erc20Tokens.push(address);
107
80
  }
108
81
  });
109
- // Handle native tokens
110
82
  const nativeMetadata = getNativeTokenMetadata(chainId);
111
83
  nativeTokens.forEach((address) => {
112
84
  results.set(address.toLowerCase(), nativeMetadata);
113
85
  });
114
- // Handle ERC20 tokens with batch multicall
115
86
  if (erc20Tokens.length === 0) {
116
- // console.log(`No ERC20 tokens to process for chain ${chainId}`)
117
87
  return results;
118
88
  }
119
- // console.log(`Processing ${erc20Tokens.length} ERC20 tokens for chain ${chainId}:`, erc20Tokens)
120
89
  const addressChunks = splitIntoChunks(erc20Tokens, TOKENS_PER_MULTICALL);
121
90
  const methods = ['symbol', 'name', 'decimals'];
122
91
  const addressChunksToCallChunks = (addressChunks, abi) => addressChunks.map((chunk) => chunk.map((address) => methods.map((functionName) => ({
@@ -126,18 +95,9 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
126
95
  allowFailure: true,
127
96
  args: [],
128
97
  }))));
129
- // Try with standard ERC20 ABI first
130
98
  const chunkedCalls = addressChunksToCallChunks(addressChunks, (address) => bytes32Whitelist.has(getStoreKey(chainId, address)) ? erc20Abi_bytes32 : erc20Abi);
131
99
  const fallback = [];
132
100
  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
101
  const chunkAddresses = addressChunks[chunkIndex];
142
102
  try {
143
103
  const batchResults = await client.multicall({
@@ -149,7 +109,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
149
109
  const symbol = batch[0].result;
150
110
  const name = batch[1].result;
151
111
  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
112
  if (name && symbol && !isNaN(decimals)) {
154
113
  results.set(tokenAddress.toLowerCase(), { name, symbol, decimals });
155
114
  }
@@ -161,9 +120,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
161
120
  }
162
121
  catch (error) {
163
122
  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
123
  fallback.push(...chunkAddresses);
168
124
  }
169
125
  }
@@ -174,7 +130,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
174
130
  const fallbackAddressChunks = splitIntoChunks(fallback, TOKENS_PER_MULTICALL);
175
131
  const fallbackChunkedCalls = addressChunksToCallChunks(fallbackAddressChunks, () => erc20Abi_bytes32);
176
132
  for (const [chunkIndex, chunk] of fallbackChunkedCalls.entries()) {
177
- // Same pairing rule as the primary loop above.
178
133
  const chunkAddresses = fallbackAddressChunks[chunkIndex];
179
134
  try {
180
135
  console.log(`Executing fallback multicall for chain ${chainId} with ${chunk.flat().length} contracts`);
@@ -188,8 +143,8 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
188
143
  const symbol = batch[0];
189
144
  const name = batch[1];
190
145
  const decimals = Number(batch[2]);
191
- const symbolString = hexToString(symbol);
192
- const nameString = hexToString(name);
146
+ const symbolString = decodeBytes32Text({ value: symbol, fallback: shortAddressLabel(tokenAddress) });
147
+ const nameString = decodeBytes32Text({ value: name, fallback: shortAddressLabel(tokenAddress) });
193
148
  console.log(`Fallback token ${tokenAddress} results:`, {
194
149
  symbolString,
195
150
  nameString,
@@ -200,7 +155,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
200
155
  symbol: symbolString,
201
156
  decimals,
202
157
  });
203
- // Add to bytes32 whitelist for future optimization
204
158
  bytes32Whitelist.add(getStoreKey(chainId, tokenAddress));
205
159
  });
206
160
  }
@@ -210,14 +164,11 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
210
164
  }
211
165
  return results;
212
166
  }
213
- // Get token metadata synchronously (from store only)
214
167
  export function getTokenMetadata(chainId, tokenAddress) {
215
168
  const storeKey = getStoreKey(chainId, tokenAddress);
216
169
  return tokenMetadataStore.get(storeKey) || null;
217
170
  }
218
- // Load token metadata for multiple tokens (called once on page load)
219
171
  export async function loadTokenMetadata(tokens) {
220
- // Group tokens by chain ID for batching
221
172
  const tokensByChain = new Map();
222
173
  tokens.forEach(({ chainId, address }) => {
223
174
  if (!tokensByChain.has(chainId)) {
@@ -225,18 +176,13 @@ export async function loadTokenMetadata(tokens) {
225
176
  }
226
177
  tokensByChain.get(chainId).push(address);
227
178
  });
228
- // Batch fetch for each chain
229
179
  const batchPromises = Array.from(tokensByChain.entries()).map(async ([chainId, addresses]) => {
230
180
  try {
231
- // console.log(`Loading token metadata for chain ${chainId} (${addresses.length} tokens):`, addresses)
232
181
  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
182
  results.forEach((metadata, address) => {
236
183
  if (metadata) {
237
184
  const storeKey = getStoreKey(chainId, address);
238
185
  tokenMetadataStore.set(storeKey, metadata);
239
- // console.log(`Stored metadata for ${storeKey}:`, metadata)
240
186
  }
241
187
  });
242
188
  }
@@ -246,11 +192,9 @@ export async function loadTokenMetadata(tokens) {
246
192
  });
247
193
  await Promise.allSettled(batchPromises);
248
194
  }
249
- // Get store size
250
195
  export function getStoreSize() {
251
196
  return tokenMetadataStore.size;
252
197
  }
253
- // Utility functions for bridge transactions
254
198
  export function getTokenAddressFromBridge(bridge) {
255
199
  return (bridge.originationToken?.address ||
256
200
  bridge.destinationToken?.address ||
@@ -272,3 +216,31 @@ export function getBridgeTokenMetadata(bridge) {
272
216
  return null;
273
217
  return getTokenMetadata(chainId, address);
274
218
  }
219
+ const decimalsReads = new Map();
220
+ export const readDecimalsOnChain = ({ chainId, address }) => {
221
+ const key = getStoreKey(chainId, address);
222
+ const known = decimalsReads.get(key);
223
+ if (known)
224
+ return known;
225
+ const pending = clientFromChain(chainId)
226
+ .readContract({ address, abi: erc20Abi, functionName: 'decimals' })
227
+ .then((answer) => {
228
+ const decimals = Number(answer);
229
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 255) {
230
+ throw new Error(`Token ${address} on chain ${chainId} reported decimals ${String(answer)}`);
231
+ }
232
+ return decimals;
233
+ });
234
+ decimalsReads.set(key, pending);
235
+ pending.catch(() => decimalsReads.delete(key));
236
+ return pending;
237
+ };
238
+ export const decimalsComeFromChain = (token) => evmChainsById.has(token.chainId) &&
239
+ isAddress(token.address, { strict: false }) &&
240
+ !isNativeAsset(token.address, 'evm');
241
+ export const withChainDecimals = async (token, readDecimals = readDecimalsOnChain) => {
242
+ if (!decimalsComeFromChain(token))
243
+ return token;
244
+ const decimals = await readDecimals({ chainId: token.chainId, address: token.address });
245
+ return decimals === token.decimals ? token : { ...token, decimals };
246
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gibs/bridge-client",
3
- "version": "1.19.0",
3
+ "version": "1.26.0",
4
4
  "description": "Browser-side endpoints, clients, and caching for a Gibs Finance bridge interface.",
5
5
  "keywords": [
6
6
  "ethereum",
@@ -84,6 +84,33 @@
84
84
  "types": "./dist/cache.d.ts",
85
85
  "default": "./dist/cache.js"
86
86
  },
87
+ "./crossing-simulator": {
88
+ "gibs-source": "./src/crossing-simulator.ts",
89
+ "react-native": {
90
+ "import": {
91
+ "types": "./dist/crossing-simulator.d.ts",
92
+ "default": "./dist/crossing-simulator.js"
93
+ },
94
+ "require": {
95
+ "types": "./dist/cjs/crossing-simulator.d.ts",
96
+ "default": "./dist/cjs/crossing-simulator.js"
97
+ },
98
+ "default": {
99
+ "types": "./dist/cjs/crossing-simulator.d.ts",
100
+ "default": "./dist/cjs/crossing-simulator.js"
101
+ }
102
+ },
103
+ "import": {
104
+ "types": "./dist/crossing-simulator.d.ts",
105
+ "default": "./dist/crossing-simulator.js"
106
+ },
107
+ "require": {
108
+ "types": "./dist/cjs/crossing-simulator.d.ts",
109
+ "default": "./dist/cjs/crossing-simulator.js"
110
+ },
111
+ "types": "./dist/crossing-simulator.d.ts",
112
+ "default": "./dist/crossing-simulator.js"
113
+ },
87
114
  "./image": {
88
115
  "gibs-source": "./src/image.ts",
89
116
  "react-native": {
@@ -256,6 +283,7 @@
256
283
  "LICENSE",
257
284
  "llms.txt",
258
285
  "cache",
286
+ "crossing-simulator",
259
287
  "image",
260
288
  "networks",
261
289
  "endpoints",
@@ -274,8 +302,8 @@
274
302
  "test:watch": "vitest"
275
303
  },
276
304
  "dependencies": {
277
- "@gibs/bridge-sdk": "^1.19.0",
278
- "@gibs/common": "^1.19.0"
305
+ "@gibs/bridge-sdk": "^1.26.0",
306
+ "@gibs/common": "^1.26.0"
279
307
  },
280
308
  "peerDependencies": {
281
309
  "viem": ">=2.35.0 <3"