@gibs/bridge-client 1.13.0 → 1.17.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/README.md +4 -4
- package/cache/package.json +6 -0
- package/chain-read/package.json +6 -0
- package/client/package.json +6 -0
- package/dist/cjs/cache.d.ts +9 -0
- package/dist/cjs/cache.js +21 -0
- package/dist/cjs/chain-read.d.ts +27 -0
- package/dist/cjs/chain-read.js +35 -0
- package/dist/cjs/chain-table.d.ts +18 -0
- package/dist/cjs/chain-table.js +92 -0
- package/dist/cjs/client.d.ts +33 -0
- package/dist/cjs/client.js +144 -0
- package/dist/cjs/endpoints.d.ts +105 -0
- package/dist/cjs/endpoints.js +263 -0
- package/dist/cjs/image.d.ts +68 -0
- package/dist/cjs/image.js +196 -0
- package/dist/cjs/index.d.ts +22 -0
- package/dist/cjs/index.js +60 -0
- package/dist/cjs/networks.d.ts +30 -0
- package/dist/cjs/networks.js +83 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/token-metadata.d.ts +21 -0
- package/dist/cjs/token-metadata.js +285 -0
- package/dist/client.js +10 -9
- package/dist/endpoints.d.ts +1 -1
- package/dist/endpoints.js +42 -15
- package/dist/token-metadata.js +15 -8
- package/endpoints/package.json +6 -0
- package/image/package.json +6 -0
- package/llms.txt +56 -0
- package/networks/package.json +6 -0
- package/package.json +198 -9
- package/token-metadata/package.json +6 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isSupportedEvmChain = exports.evmChainsById = exports.evmChains = void 0;
|
|
4
|
+
const chain_names_1 = require("@gibs/bridge-sdk/chain-names");
|
|
5
|
+
const chain_table_js_1 = require("./chain-table.js");
|
|
6
|
+
/**
|
|
7
|
+
* Turns one row of the generated table into the shape viem wants.
|
|
8
|
+
*
|
|
9
|
+
* NAMED VIEM IMPORTS USED TO LIVE HERE — 37 of them, each pulling that chain's
|
|
10
|
+
* whole definition including fee logic, formatters and contract addresses this
|
|
11
|
+
* application never reads. That cost about 3.7 kB compressed for a third of the
|
|
12
|
+
* chains the aggregators quote; naming all 73 would have cost about 7.3 kB
|
|
13
|
+
* against roughly 7.8 kB of headroom under the first-load budget. The generated
|
|
14
|
+
* table carries the same 73 in 2.6 kB, so the whole supported set now weighs
|
|
15
|
+
* less than the third of it that shipped before.
|
|
16
|
+
*
|
|
17
|
+
* A namespace import is still never used, for the reason the old comment here
|
|
18
|
+
* gave: `Object.values(chains)` defeats tree-shaking and emitted all ~674
|
|
19
|
+
* definitions, measured at 255 kB. The generator does that read in Node, at
|
|
20
|
+
* build time, where it costs a reader nothing.
|
|
21
|
+
*
|
|
22
|
+
* `blockExplorers` is omitted rather than faked when a chain has no explorer —
|
|
23
|
+
* viem treats the field as optional and an empty url would render a dead link.
|
|
24
|
+
*/
|
|
25
|
+
const toViemChain = (entry) => ({
|
|
26
|
+
id: entry.id,
|
|
27
|
+
name: entry.name,
|
|
28
|
+
nativeCurrency: entry.nativeCurrency,
|
|
29
|
+
rpcUrls: { default: { http: [...entry.http] } },
|
|
30
|
+
...(entry.explorer === null
|
|
31
|
+
? {}
|
|
32
|
+
: { blockExplorers: { default: { name: 'Explorer', url: entry.explorer } } }),
|
|
33
|
+
// WITHOUT THIS, NOTHING CAN BATCH A READ. viem's `multicall` action reads the
|
|
34
|
+
// Multicall3 address off the chain and throws `ChainDoesNotSupportContract`
|
|
35
|
+
// when it is absent, so every chain built here refused — including
|
|
36
|
+
// PulseChain, whose token-metadata fallback failed with exactly that.
|
|
37
|
+
//
|
|
38
|
+
// It went missing when this table replaced viem's own chain objects to keep
|
|
39
|
+
// 255 kB of unused per-chain data out of the build. The table kept the four
|
|
40
|
+
// fields a TRANSPORT needs and dropped the one field an ACTION needs.
|
|
41
|
+
//
|
|
42
|
+
// Read per chain, never assumed: the canonical `0xcA11bde0…` covers most, but
|
|
43
|
+
// there are 8 distinct deployments across the chains listed here.
|
|
44
|
+
...(entry.multicall3 === null
|
|
45
|
+
? {}
|
|
46
|
+
: { contracts: { multicall3: { address: entry.multicall3 } } }),
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* Every Ethereum-Virtual-Machine chain this client can build a public client for.
|
|
50
|
+
*
|
|
51
|
+
* The leading entries are the bridge's own chains; the rest are the routing
|
|
52
|
+
* destinations reachable through the aggregators. Ordering is preserved because
|
|
53
|
+
* chain pickers render it directly.
|
|
54
|
+
*
|
|
55
|
+
* Solana and Bitcoin are deliberately absent. They are supported ORIGINS, but
|
|
56
|
+
* they are not Ethereum-style chains: they are keyed by a genesis hash and by
|
|
57
|
+
* their own string rather than by a number, and nothing here can build a client
|
|
58
|
+
* for them. Anything wallet-facing that needs them keys off the aggregator's
|
|
59
|
+
* chain identifiers instead.
|
|
60
|
+
*/
|
|
61
|
+
exports.evmChains = chain_table_js_1.chainTable.map(toViemChain);
|
|
62
|
+
/**
|
|
63
|
+
* Lookup from a chain id to its viem chain definition, for supported chains only.
|
|
64
|
+
*
|
|
65
|
+
* Keyed as `string | number` because callers hold ids that have been through a
|
|
66
|
+
* url, a wallet, or a quote response, and a lookup that silently misses on a
|
|
67
|
+
* numeric-versus-string mismatch reads as "chain not supported".
|
|
68
|
+
*/
|
|
69
|
+
exports.evmChainsById = new Map(exports.evmChains.map((chain) => [chain.id, chain]));
|
|
70
|
+
// Hand these names to the SDK's display-name table so ONE function answers
|
|
71
|
+
// "what is this chain called" everywhere. Done at module load, before anything
|
|
72
|
+
// renders, because a name that arrives late is a name that changes under the
|
|
73
|
+
// reader — which is precisely the flicker this removes. The SDK's own entries
|
|
74
|
+
// win on conflict, so the product's chosen spellings are not overwritten.
|
|
75
|
+
(0, chain_names_1.registerChainNames)(exports.evmChains.map((chain) => [chain.id, chain.name]));
|
|
76
|
+
/**
|
|
77
|
+
* Whether this client can reach a chain over Ethereum-style remote procedure calls.
|
|
78
|
+
*
|
|
79
|
+
* @param chainId - the chain id to test
|
|
80
|
+
* @returns true when the chain has a definition here
|
|
81
|
+
*/
|
|
82
|
+
const isSupportedEvmChain = (chainId) => exports.evmChainsById.has(chainId);
|
|
83
|
+
exports.isSupportedEvmChain = isSupportedEvmChain;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { TokenMetadata } from '@gibs/bridge-sdk/types';
|
|
2
|
+
import type { Hex } from 'viem';
|
|
3
|
+
export type ChainScopedAddress = `${number}:${Hex}`;
|
|
4
|
+
export declare function getStoreKey(chainId: number, tokenAddress: string): ChainScopedAddress;
|
|
5
|
+
export declare function parseChainScopedAddress(key: ChainScopedAddress): {
|
|
6
|
+
chainId: number;
|
|
7
|
+
address: Hex;
|
|
8
|
+
};
|
|
9
|
+
export declare function parseTokenKey(key: string): {
|
|
10
|
+
chainId: number;
|
|
11
|
+
address: Hex;
|
|
12
|
+
};
|
|
13
|
+
export declare function getTokenMetadata(chainId: number, tokenAddress: string): TokenMetadata | null;
|
|
14
|
+
export declare function loadTokenMetadata(tokens: Array<{
|
|
15
|
+
chainId: number;
|
|
16
|
+
address: Hex;
|
|
17
|
+
}>): Promise<void>;
|
|
18
|
+
export declare function getStoreSize(): number;
|
|
19
|
+
export declare function getTokenAddressFromBridge(bridge: any): string;
|
|
20
|
+
export declare function getTokenChainIdFromBridge(bridge: any): number;
|
|
21
|
+
export declare function getBridgeTokenMetadata(bridge: any): TokenMetadata | null;
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getStoreKey = getStoreKey;
|
|
4
|
+
exports.parseChainScopedAddress = parseChainScopedAddress;
|
|
5
|
+
exports.parseTokenKey = parseTokenKey;
|
|
6
|
+
exports.getTokenMetadata = getTokenMetadata;
|
|
7
|
+
exports.loadTokenMetadata = loadTokenMetadata;
|
|
8
|
+
exports.getStoreSize = getStoreSize;
|
|
9
|
+
exports.getTokenAddressFromBridge = getTokenAddressFromBridge;
|
|
10
|
+
exports.getTokenChainIdFromBridge = getTokenChainIdFromBridge;
|
|
11
|
+
exports.getBridgeTokenMetadata = getBridgeTokenMetadata;
|
|
12
|
+
const config_1 = require("@gibs/bridge-sdk/config");
|
|
13
|
+
const ecosystems_1 = require("@gibs/bridge-sdk/ecosystems");
|
|
14
|
+
const viem_1 = require("viem");
|
|
15
|
+
const client_js_1 = require("./client.js");
|
|
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
|
+
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
|
+
const splitIntoChunks = (items, size) => Array.from({ length: Math.ceil(items.length / size) }, (_unused, index) => items.slice(index * size, (index + 1) * size));
|
|
31
|
+
const bytes32Whitelist = new Set();
|
|
32
|
+
// In-memory store for token metadata (loaded once, no persistence)
|
|
33
|
+
const tokenMetadataStore = new Map();
|
|
34
|
+
// Generate store key
|
|
35
|
+
function getStoreKey(chainId, tokenAddress) {
|
|
36
|
+
return `${chainId}:${tokenAddress.toLowerCase()}`;
|
|
37
|
+
}
|
|
38
|
+
// Parse a ChainScopedAddress into its components
|
|
39
|
+
function parseChainScopedAddress(key) {
|
|
40
|
+
const [chainIdStr, address] = key.split(':');
|
|
41
|
+
const chainId = parseInt(chainIdStr ?? '', 10);
|
|
42
|
+
if (isNaN(chainId)) {
|
|
43
|
+
throw new Error(`Invalid chain ID in ChainScopedAddress: ${chainIdStr}`);
|
|
44
|
+
}
|
|
45
|
+
if (!address || !address.startsWith('0x')) {
|
|
46
|
+
throw new Error(`Invalid address in ChainScopedAddress: ${address}`);
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
chainId,
|
|
50
|
+
address: address,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// Parse a string key (chainId:address format) into its components with proper types
|
|
54
|
+
function parseTokenKey(key) {
|
|
55
|
+
const [chainIdStr, address] = key.split(':');
|
|
56
|
+
const chainId = parseInt(chainIdStr ?? '', 10);
|
|
57
|
+
if (isNaN(chainId)) {
|
|
58
|
+
throw new Error(`Invalid chain ID in token key: ${chainIdStr}`);
|
|
59
|
+
}
|
|
60
|
+
if (!address) {
|
|
61
|
+
throw new Error(`Invalid address in token key: ${address}`);
|
|
62
|
+
}
|
|
63
|
+
// Ensure address is properly formatted as Hex
|
|
64
|
+
const hexAddress = address.startsWith('0x') ? address : `0x${address}`;
|
|
65
|
+
return {
|
|
66
|
+
chainId,
|
|
67
|
+
address: hexAddress,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
// Get native token metadata
|
|
71
|
+
function getNativeTokenMetadata(chainId) {
|
|
72
|
+
const chain = networks_js_1.evmChainsById.get(chainId);
|
|
73
|
+
// Safely get native token info from SDK
|
|
74
|
+
let name = chain?.nativeCurrency?.name || 'Ether';
|
|
75
|
+
let symbol = chain?.nativeCurrency?.symbol || 'ETH';
|
|
76
|
+
const decimals = chain?.nativeCurrency?.decimals || 18;
|
|
77
|
+
// Try to get more specific info from SDK if available
|
|
78
|
+
try {
|
|
79
|
+
const chainKey = (0, config_1.toChain)(chainId);
|
|
80
|
+
const sdkName = config_1.nativeTokenName[chainKey];
|
|
81
|
+
const sdkSymbol = config_1.nativeTokenSymbol[chainKey];
|
|
82
|
+
if (sdkName) {
|
|
83
|
+
name = sdkName;
|
|
84
|
+
}
|
|
85
|
+
if (sdkSymbol) {
|
|
86
|
+
symbol = sdkSymbol;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
// Fallback to viem chain info
|
|
91
|
+
}
|
|
92
|
+
return { name, symbol, decimals };
|
|
93
|
+
}
|
|
94
|
+
// Batch fetch token metadata for multiple tokens on the same chain
|
|
95
|
+
async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
96
|
+
const results = new Map();
|
|
97
|
+
if (tokenAddresses.length === 0)
|
|
98
|
+
return results;
|
|
99
|
+
// Get the chain and client
|
|
100
|
+
const chain = networks_js_1.evmChainsById.get(chainId);
|
|
101
|
+
if (!chain) {
|
|
102
|
+
throw new Error(`Chain not found for chainId: ${chainId}`);
|
|
103
|
+
}
|
|
104
|
+
const client = (0, client_js_1.clientFromChain)(chainId);
|
|
105
|
+
// Separate native tokens from ERC20 tokens
|
|
106
|
+
const nativeTokens = [];
|
|
107
|
+
const erc20Tokens = [];
|
|
108
|
+
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
|
+
if ((0, ecosystems_1.isNativeAsset)(address, 'evm')) {
|
|
114
|
+
nativeTokens.push(address);
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
erc20Tokens.push(address);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
// Handle native tokens
|
|
121
|
+
const nativeMetadata = getNativeTokenMetadata(chainId);
|
|
122
|
+
nativeTokens.forEach((address) => {
|
|
123
|
+
results.set(address.toLowerCase(), nativeMetadata);
|
|
124
|
+
});
|
|
125
|
+
// Handle ERC20 tokens with batch multicall
|
|
126
|
+
if (erc20Tokens.length === 0) {
|
|
127
|
+
// console.log(`No ERC20 tokens to process for chain ${chainId}`)
|
|
128
|
+
return results;
|
|
129
|
+
}
|
|
130
|
+
// console.log(`Processing ${erc20Tokens.length} ERC20 tokens for chain ${chainId}:`, erc20Tokens)
|
|
131
|
+
const addressChunks = splitIntoChunks(erc20Tokens, TOKENS_PER_MULTICALL);
|
|
132
|
+
const methods = ['symbol', 'name', 'decimals'];
|
|
133
|
+
const addressChunksToCallChunks = (addressChunks, abi) => addressChunks.map((chunk) => chunk.map((address) => methods.map((functionName) => ({
|
|
134
|
+
functionName,
|
|
135
|
+
address,
|
|
136
|
+
abi: abi(address),
|
|
137
|
+
allowFailure: true,
|
|
138
|
+
args: [],
|
|
139
|
+
}))));
|
|
140
|
+
// Try with standard ERC20 ABI first
|
|
141
|
+
const chunkedCalls = addressChunksToCallChunks(addressChunks, (address) => bytes32Whitelist.has(getStoreKey(chainId, address)) ? viem_1.erc20Abi_bytes32 : viem_1.erc20Abi);
|
|
142
|
+
const fallback = [];
|
|
143
|
+
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
|
+
const chunkAddresses = addressChunks[chunkIndex];
|
|
153
|
+
try {
|
|
154
|
+
const batchResults = await client.multicall({
|
|
155
|
+
allowFailure: true,
|
|
156
|
+
contracts: chunk.flat(),
|
|
157
|
+
});
|
|
158
|
+
splitIntoChunks(batchResults, 3).forEach((batch, index) => {
|
|
159
|
+
const tokenAddress = chunkAddresses[index];
|
|
160
|
+
const symbol = batch[0].result;
|
|
161
|
+
const name = batch[1].result;
|
|
162
|
+
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
|
+
if (name && symbol && !isNaN(decimals)) {
|
|
165
|
+
results.set(tokenAddress.toLowerCase(), { name, symbol, decimals });
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
console.log(`Adding ${tokenAddress} to fallback due to missing data`);
|
|
169
|
+
fallback.push(tokenAddress);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
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
|
+
fallback.push(...chunkAddresses);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (fallback.length === 0) {
|
|
182
|
+
return results;
|
|
183
|
+
}
|
|
184
|
+
console.log(`Processing ${fallback.length} tokens in fallback with bytes32 ABI for chain ${chainId}:`, fallback);
|
|
185
|
+
const fallbackAddressChunks = splitIntoChunks(fallback, TOKENS_PER_MULTICALL);
|
|
186
|
+
const fallbackChunkedCalls = addressChunksToCallChunks(fallbackAddressChunks, () => viem_1.erc20Abi_bytes32);
|
|
187
|
+
for (const [chunkIndex, chunk] of fallbackChunkedCalls.entries()) {
|
|
188
|
+
// Same pairing rule as the primary loop above.
|
|
189
|
+
const chunkAddresses = fallbackAddressChunks[chunkIndex];
|
|
190
|
+
try {
|
|
191
|
+
console.log(`Executing fallback multicall for chain ${chainId} with ${chunk.flat().length} contracts`);
|
|
192
|
+
const batchResults = await client.multicall({
|
|
193
|
+
allowFailure: false,
|
|
194
|
+
contracts: chunk.flat(),
|
|
195
|
+
});
|
|
196
|
+
console.log(`Fallback multicall results for chain ${chainId}:`, batchResults.length, 'results');
|
|
197
|
+
splitIntoChunks(batchResults, 3).forEach((batch, index) => {
|
|
198
|
+
const tokenAddress = chunkAddresses[index];
|
|
199
|
+
const symbol = batch[0];
|
|
200
|
+
const name = batch[1];
|
|
201
|
+
const decimals = Number(batch[2]);
|
|
202
|
+
const symbolString = (0, viem_1.hexToString)(symbol);
|
|
203
|
+
const nameString = (0, viem_1.hexToString)(name);
|
|
204
|
+
console.log(`Fallback token ${tokenAddress} results:`, {
|
|
205
|
+
symbolString,
|
|
206
|
+
nameString,
|
|
207
|
+
decimals,
|
|
208
|
+
});
|
|
209
|
+
results.set(tokenAddress.toLowerCase(), {
|
|
210
|
+
name: nameString,
|
|
211
|
+
symbol: symbolString,
|
|
212
|
+
decimals,
|
|
213
|
+
});
|
|
214
|
+
// Add to bytes32 whitelist for future optimization
|
|
215
|
+
bytes32Whitelist.add(getStoreKey(chainId, tokenAddress));
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
console.error(`Fallback multicall failed for chain ${chainId}:`, error);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return results;
|
|
223
|
+
}
|
|
224
|
+
// Get token metadata synchronously (from store only)
|
|
225
|
+
function getTokenMetadata(chainId, tokenAddress) {
|
|
226
|
+
const storeKey = getStoreKey(chainId, tokenAddress);
|
|
227
|
+
return tokenMetadataStore.get(storeKey) || null;
|
|
228
|
+
}
|
|
229
|
+
// Load token metadata for multiple tokens (called once on page load)
|
|
230
|
+
async function loadTokenMetadata(tokens) {
|
|
231
|
+
// Group tokens by chain ID for batching
|
|
232
|
+
const tokensByChain = new Map();
|
|
233
|
+
tokens.forEach(({ chainId, address }) => {
|
|
234
|
+
if (!tokensByChain.has(chainId)) {
|
|
235
|
+
tokensByChain.set(chainId, []);
|
|
236
|
+
}
|
|
237
|
+
tokensByChain.get(chainId).push(address);
|
|
238
|
+
});
|
|
239
|
+
// Batch fetch for each chain
|
|
240
|
+
const batchPromises = Array.from(tokensByChain.entries()).map(async ([chainId, addresses]) => {
|
|
241
|
+
try {
|
|
242
|
+
// console.log(`Loading token metadata for chain ${chainId} (${addresses.length} tokens):`, addresses)
|
|
243
|
+
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
|
+
results.forEach((metadata, address) => {
|
|
247
|
+
if (metadata) {
|
|
248
|
+
const storeKey = getStoreKey(chainId, address);
|
|
249
|
+
tokenMetadataStore.set(storeKey, metadata);
|
|
250
|
+
// console.log(`Stored metadata for ${storeKey}:`, metadata)
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
console.error(`Failed to load tokens for chain ${chainId}:`, error);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
await Promise.allSettled(batchPromises);
|
|
259
|
+
}
|
|
260
|
+
// Get store size
|
|
261
|
+
function getStoreSize() {
|
|
262
|
+
return tokenMetadataStore.size;
|
|
263
|
+
}
|
|
264
|
+
// Utility functions for bridge transactions
|
|
265
|
+
function getTokenAddressFromBridge(bridge) {
|
|
266
|
+
return (bridge.originationToken?.address ||
|
|
267
|
+
bridge.destinationToken?.address ||
|
|
268
|
+
bridge.originationTokenAddress ||
|
|
269
|
+
bridge.destinationTokenAddress ||
|
|
270
|
+
'');
|
|
271
|
+
}
|
|
272
|
+
function getTokenChainIdFromBridge(bridge) {
|
|
273
|
+
return Number(bridge.originationToken?.chainId ||
|
|
274
|
+
bridge.destinationToken?.chainId ||
|
|
275
|
+
bridge.originationTokenChainId ||
|
|
276
|
+
bridge.destinationTokenChainId ||
|
|
277
|
+
1);
|
|
278
|
+
}
|
|
279
|
+
function getBridgeTokenMetadata(bridge) {
|
|
280
|
+
const address = getTokenAddressFromBridge(bridge);
|
|
281
|
+
const chainId = getTokenChainIdFromBridge(bridge);
|
|
282
|
+
if (!address)
|
|
283
|
+
return null;
|
|
284
|
+
return getTokenMetadata(chainId, address);
|
|
285
|
+
}
|
package/dist/client.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { toChain } from '@gibs/bridge-sdk/config';
|
|
1
|
+
import { demoRpcUrlsFor } from '@gibs/bridge-sdk/chains';
|
|
3
2
|
import { chainKey, clientCache, clientFromChain as buildClient, MAX_SAME_METHOD_CALLS_PER_SECOND, } from '@gibs/common/client';
|
|
4
|
-
import * as _ from 'lodash-es';
|
|
5
3
|
import { bsc } from 'viem/chains';
|
|
6
4
|
import * as endpoints from './endpoints.js';
|
|
7
5
|
import { evmChainsById } from './networks.js';
|
|
@@ -45,7 +43,7 @@ const defaultUrlsFor = (chainId) => {
|
|
|
45
43
|
// does not override.
|
|
46
44
|
//
|
|
47
45
|
// These are two different answers to the same question, and reading only the
|
|
48
|
-
// second is why demoting a rate-limited Sepolia endpoint in
|
|
46
|
+
// second is why demoting a rate-limited Sepolia endpoint in the demo list
|
|
49
47
|
// changed nothing: the seed built from that map, while THIS function — which
|
|
50
48
|
// decides what a client actually talks to when the stored table is empty —
|
|
51
49
|
// returned viem's own default and went on hitting the demoted host first.
|
|
@@ -53,10 +51,13 @@ const defaultUrlsFor = (chainId) => {
|
|
|
53
51
|
// The bridge chains are overridden precisely because viem's defaults are not
|
|
54
52
|
// the ones this application wants; the wider list (Arbitrum, Base, and the
|
|
55
53
|
// rest) has no override and correctly falls through.
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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
|
+
const demoUrls = demoRpcUrlsFor(chainId);
|
|
59
|
+
if (demoUrls.length) {
|
|
60
|
+
return demoUrls;
|
|
60
61
|
}
|
|
61
62
|
const chain = evmChainsById.get(chainId);
|
|
62
63
|
if (!chain) {
|
|
@@ -83,7 +84,7 @@ const defaultUrlsFor = (chainId) => {
|
|
|
83
84
|
*/
|
|
84
85
|
export const clientFromChain = (chainId) => {
|
|
85
86
|
const stored = endpoints.get(chainId);
|
|
86
|
-
const urls =
|
|
87
|
+
const urls = (stored?.length ? stored : defaultUrlsFor(chainId)).filter((url) => Boolean(url));
|
|
87
88
|
const key = chainKey(chainId, urls);
|
|
88
89
|
const existing = clientCache.get(chainId);
|
|
89
90
|
if (existing && existing.key === key) {
|
package/dist/endpoints.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export declare const ENDPOINTS_STORAGE_KEY = "rpcs";
|
|
|
34
34
|
/**
|
|
35
35
|
* Every chain the application can reach, the bridge's own first.
|
|
36
36
|
*
|
|
37
|
-
* The bridge's three keep taking their urls from `
|
|
37
|
+
* The bridge's three keep taking their urls from `demoRpcUrlsFor`, which is
|
|
38
38
|
* where the product's own node choices live and which must win over viem's
|
|
39
39
|
* generic default for them.
|
|
40
40
|
*/
|
package/dist/endpoints.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Chains
|
|
1
|
+
import { demoRpcUrlsFor } from '@gibs/bridge-sdk/chains';
|
|
2
|
+
import { Chains } from '@gibs/bridge-sdk/config';
|
|
3
3
|
import { chainTable } from './chain-table.js';
|
|
4
|
-
import * as _ from 'lodash-es';
|
|
5
4
|
/**
|
|
6
5
|
* The storage key holding the endpoint table.
|
|
7
6
|
*
|
|
@@ -24,7 +23,7 @@ export const ENDPOINTS_STORAGE_KEY = 'rpcs';
|
|
|
24
23
|
* defaults, which is what the three seeded chains always used — the change is
|
|
25
24
|
* the breadth, not the source.
|
|
26
25
|
*/
|
|
27
|
-
const seedFor = (chains) => chains.map((chain) => [Number(chain),
|
|
26
|
+
const seedFor = (chains) => chains.map((chain) => [Number(chain), demoRpcUrlsFor(Number(chain))]);
|
|
28
27
|
/** The bridge's own chains, kept first so a picker built from this reads well. */
|
|
29
28
|
const BRIDGE_CHAIN_IDS = [
|
|
30
29
|
Number(Chains.PLS),
|
|
@@ -34,7 +33,7 @@ const BRIDGE_CHAIN_IDS = [
|
|
|
34
33
|
/**
|
|
35
34
|
* Every chain the application can reach, the bridge's own first.
|
|
36
35
|
*
|
|
37
|
-
* The bridge's three keep taking their urls from `
|
|
36
|
+
* The bridge's three keep taking their urls from `demoRpcUrlsFor`, which is
|
|
38
37
|
* where the product's own node choices live and which must win over viem's
|
|
39
38
|
* generic default for them.
|
|
40
39
|
*/
|
|
@@ -42,7 +41,7 @@ export const productionSeed = [
|
|
|
42
41
|
...seedFor([Chains.PLS, Chains.ETH, Chains.BNB]),
|
|
43
42
|
...chainTable
|
|
44
43
|
.filter((entry) =>
|
|
45
|
-
// The bridge's own three are seeded above, from `
|
|
44
|
+
// The bridge's own three are seeded above, from `demoRpcUrlsFor`, and
|
|
46
45
|
// must not be seeded twice. That map is where the product's node
|
|
47
46
|
// choices live — demoting a rate-limited host there has to take effect,
|
|
48
47
|
// and a table entry added after it would silently win.
|
|
@@ -60,8 +59,34 @@ export const productionSeed = [
|
|
|
60
59
|
export const testnetSeed = seedFor([Chains.V4PLS, Chains.SEP]);
|
|
61
60
|
/** The seed the next load starts from. */
|
|
62
61
|
let seed = productionSeed;
|
|
63
|
-
/**
|
|
64
|
-
|
|
62
|
+
/**
|
|
63
|
+
* Where the table is persisted. `undefined` means "use the browser default,
|
|
64
|
+
* resolved on first use"; null means "nowhere".
|
|
65
|
+
*/
|
|
66
|
+
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
|
+
const browserStorage = () => {
|
|
74
|
+
try {
|
|
75
|
+
return typeof globalThis.localStorage === 'undefined'
|
|
76
|
+
? null
|
|
77
|
+
: globalThis.localStorage;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
/** The persistence target in effect, resolving the default on first call. */
|
|
84
|
+
const activeStorage = () => {
|
|
85
|
+
if (storage === undefined) {
|
|
86
|
+
storage = browserStorage();
|
|
87
|
+
}
|
|
88
|
+
return storage;
|
|
89
|
+
};
|
|
65
90
|
/** The live table, or null while it has not been loaded yet. */
|
|
66
91
|
let value = null;
|
|
67
92
|
const listeners = new Set();
|
|
@@ -105,7 +130,7 @@ export const parse = (entry) => {
|
|
|
105
130
|
}
|
|
106
131
|
const stored = entry.split('\n').map((row) => {
|
|
107
132
|
const [chain, ...list] = row.split(',');
|
|
108
|
-
return [Number(chain),
|
|
133
|
+
return [Number(chain), list.filter((url) => url !== '')];
|
|
109
134
|
});
|
|
110
135
|
return new Map([...seed, ...stored]);
|
|
111
136
|
};
|
|
@@ -117,11 +142,12 @@ export const parse = (entry) => {
|
|
|
117
142
|
* reach a chain at all.
|
|
118
143
|
*/
|
|
119
144
|
const readStored = () => {
|
|
120
|
-
|
|
145
|
+
const target = activeStorage();
|
|
146
|
+
if (!target) {
|
|
121
147
|
return null;
|
|
122
148
|
}
|
|
123
149
|
try {
|
|
124
|
-
return parse(
|
|
150
|
+
return parse(target.getItem(ENDPOINTS_STORAGE_KEY));
|
|
125
151
|
}
|
|
126
152
|
catch (error) {
|
|
127
153
|
console.error('unable to read the stored endpoint list', error);
|
|
@@ -167,7 +193,7 @@ export const setEndpoints = (chain, list) => {
|
|
|
167
193
|
const next = new Map(loaded());
|
|
168
194
|
next.set(chain, list);
|
|
169
195
|
value = next;
|
|
170
|
-
|
|
196
|
+
activeStorage()?.setItem(ENDPOINTS_STORAGE_KEY, stringify());
|
|
171
197
|
emit();
|
|
172
198
|
};
|
|
173
199
|
/** Replaces the url at index `i`; a no-op when the value is unchanged. */
|
|
@@ -201,19 +227,20 @@ export const add = (chain, addition = (urls) => [''].concat(urls)) => {
|
|
|
201
227
|
}
|
|
202
228
|
return !!val;
|
|
203
229
|
});
|
|
204
|
-
|
|
230
|
+
const unchanged = before.length === filteredList.length && before.every((url, index) => url === filteredList[index]);
|
|
231
|
+
if (unchanged) {
|
|
205
232
|
return;
|
|
206
233
|
}
|
|
207
234
|
setEndpoints(chain, filteredList);
|
|
208
235
|
};
|
|
209
236
|
/** Whether `list` already contains the chain's canonical default endpoint. */
|
|
210
237
|
export const hasDefault = (chain, list) => {
|
|
211
|
-
const defaultUrl =
|
|
238
|
+
const defaultUrl = demoRpcUrlsFor(chain)[0];
|
|
212
239
|
if (!defaultUrl)
|
|
213
240
|
return false;
|
|
214
241
|
return list.includes(defaultUrl);
|
|
215
242
|
};
|
|
216
243
|
/** Appends the chain's canonical default endpoints back onto its list. */
|
|
217
244
|
export const restoreDefault = (chain) => {
|
|
218
|
-
add(chain, (l) => l.concat(
|
|
245
|
+
add(chain, (l) => l.concat(demoRpcUrlsFor(chain)));
|
|
219
246
|
};
|
package/dist/token-metadata.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { nativeTokenName, nativeTokenSymbol, toChain } from '@gibs/bridge-sdk/config';
|
|
2
2
|
import { isNativeAsset } from '@gibs/bridge-sdk/ecosystems';
|
|
3
|
-
import * as _ from 'lodash-es';
|
|
4
3
|
import { erc20Abi, erc20Abi_bytes32, hexToString } from 'viem';
|
|
5
4
|
import { clientFromChain } from './client.js';
|
|
6
5
|
import { evmChainsById } from './networks.js';
|
|
@@ -10,6 +9,14 @@ import { evmChainsById } from './networks.js';
|
|
|
10
9
|
* — see the primary loop for what indexing the flat array cost.
|
|
11
10
|
*/
|
|
12
11
|
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
|
+
const splitIntoChunks = (items, size) => Array.from({ length: Math.ceil(items.length / size) }, (_unused, index) => items.slice(index * size, (index + 1) * size));
|
|
13
20
|
const bytes32Whitelist = new Set();
|
|
14
21
|
// In-memory store for token metadata (loaded once, no persistence)
|
|
15
22
|
const tokenMetadataStore = new Map();
|
|
@@ -110,7 +117,7 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
110
117
|
return results;
|
|
111
118
|
}
|
|
112
119
|
// console.log(`Processing ${erc20Tokens.length} ERC20 tokens for chain ${chainId}:`, erc20Tokens)
|
|
113
|
-
const addressChunks =
|
|
120
|
+
const addressChunks = splitIntoChunks(erc20Tokens, TOKENS_PER_MULTICALL);
|
|
114
121
|
const methods = ['symbol', 'name', 'decimals'];
|
|
115
122
|
const addressChunksToCallChunks = (addressChunks, abi) => addressChunks.map((chunk) => chunk.map((address) => methods.map((functionName) => ({
|
|
116
123
|
functionName,
|
|
@@ -135,9 +142,9 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
135
142
|
try {
|
|
136
143
|
const batchResults = await client.multicall({
|
|
137
144
|
allowFailure: true,
|
|
138
|
-
contracts:
|
|
145
|
+
contracts: chunk.flat(),
|
|
139
146
|
});
|
|
140
|
-
|
|
147
|
+
splitIntoChunks(batchResults, 3).forEach((batch, index) => {
|
|
141
148
|
const tokenAddress = chunkAddresses[index];
|
|
142
149
|
const symbol = batch[0].result;
|
|
143
150
|
const name = batch[1].result;
|
|
@@ -164,19 +171,19 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
164
171
|
return results;
|
|
165
172
|
}
|
|
166
173
|
console.log(`Processing ${fallback.length} tokens in fallback with bytes32 ABI for chain ${chainId}:`, fallback);
|
|
167
|
-
const fallbackAddressChunks =
|
|
174
|
+
const fallbackAddressChunks = splitIntoChunks(fallback, TOKENS_PER_MULTICALL);
|
|
168
175
|
const fallbackChunkedCalls = addressChunksToCallChunks(fallbackAddressChunks, () => erc20Abi_bytes32);
|
|
169
176
|
for (const [chunkIndex, chunk] of fallbackChunkedCalls.entries()) {
|
|
170
177
|
// Same pairing rule as the primary loop above.
|
|
171
178
|
const chunkAddresses = fallbackAddressChunks[chunkIndex];
|
|
172
179
|
try {
|
|
173
|
-
console.log(`Executing fallback multicall for chain ${chainId} with ${
|
|
180
|
+
console.log(`Executing fallback multicall for chain ${chainId} with ${chunk.flat().length} contracts`);
|
|
174
181
|
const batchResults = await client.multicall({
|
|
175
182
|
allowFailure: false,
|
|
176
|
-
contracts:
|
|
183
|
+
contracts: chunk.flat(),
|
|
177
184
|
});
|
|
178
185
|
console.log(`Fallback multicall results for chain ${chainId}:`, batchResults.length, 'results');
|
|
179
|
-
|
|
186
|
+
splitIntoChunks(batchResults, 3).forEach((batch, index) => {
|
|
180
187
|
const tokenAddress = chunkAddresses[index];
|
|
181
188
|
const symbol = batch[0];
|
|
182
189
|
const name = batch[1];
|