@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.
- package/crossing-simulator/package.json +6 -0
- package/dist/chain-read.js +0 -14
- package/dist/chain-table.js +0 -12
- package/dist/cjs/chain-read.js +0 -14
- package/dist/cjs/chain-table.js +0 -12
- package/dist/cjs/client.js +0 -66
- package/dist/cjs/crossing-simulator.d.ts +32 -0
- package/dist/cjs/crossing-simulator.js +28 -0
- package/dist/cjs/endpoints.js +1 -109
- package/dist/cjs/image.js +0 -117
- package/dist/cjs/index.js +0 -15
- package/dist/cjs/networks.js +0 -61
- package/dist/cjs/token-metadata.d.ts +48 -1
- package/dist/cjs/token-metadata.js +35 -59
- package/dist/client.js +0 -66
- package/dist/crossing-simulator.d.ts +32 -0
- package/dist/crossing-simulator.js +23 -0
- package/dist/endpoints.js +1 -109
- package/dist/image.js +0 -117
- package/dist/index.js +0 -15
- package/dist/networks.js +0 -61
- package/dist/token-metadata.d.ts +48 -1
- package/dist/token-metadata.js +32 -60
- package/package.json +31 -3
package/dist/cjs/networks.js
CHANGED
|
@@ -3,25 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.isSupportedEvmChain = exports.evmChainsById = exports.evmChains = void 0;
|
|
4
4
|
const chain_names_1 = require("@gibs/bridge-sdk/chain-names");
|
|
5
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
6
|
const toViemChain = (entry) => ({
|
|
26
7
|
id: entry.id,
|
|
27
8
|
name: entry.name,
|
|
@@ -30,54 +11,12 @@ const toViemChain = (entry) => ({
|
|
|
30
11
|
...(entry.explorer === null
|
|
31
12
|
? {}
|
|
32
13
|
: { 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
14
|
...(entry.multicall3 === null
|
|
45
15
|
? {}
|
|
46
16
|
: { contracts: { multicall3: { address: entry.multicall3 } } }),
|
|
47
17
|
});
|
|
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
18
|
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
19
|
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
20
|
(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
21
|
const isSupportedEvmChain = (chainId) => exports.evmChainsById.has(chainId);
|
|
83
22
|
exports.isSupportedEvmChain = isSupportedEvmChain;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { TokenMetadata } from '@gibs/bridge-sdk/types';
|
|
1
|
+
import type { Token, TokenMetadata } from '@gibs/bridge-sdk/types';
|
|
2
2
|
import type { Hex } from 'viem';
|
|
3
3
|
export type ChainScopedAddress = `${number}:${Hex}`;
|
|
4
4
|
export declare function getStoreKey(chainId: number, tokenAddress: string): ChainScopedAddress;
|
|
@@ -19,3 +19,50 @@ export declare function getStoreSize(): number;
|
|
|
19
19
|
export declare function getTokenAddressFromBridge(bridge: any): string;
|
|
20
20
|
export declare function getTokenChainIdFromBridge(bridge: any): number;
|
|
21
21
|
export declare function getBridgeTokenMetadata(bridge: any): TokenMetadata | null;
|
|
22
|
+
/** What {@link readDecimalsOnChain} needs to find one token. */
|
|
23
|
+
export type DecimalsReadTarget = {
|
|
24
|
+
chainId: number;
|
|
25
|
+
address: Hex;
|
|
26
|
+
};
|
|
27
|
+
/** Asks a chain how many decimals one token has. See {@link readDecimalsOnChain}. */
|
|
28
|
+
export type ReadDecimals = (target: DecimalsReadTarget) => Promise<number>;
|
|
29
|
+
/**
|
|
30
|
+
* Reads `decimals()` from the token contract and keeps the answer for the session.
|
|
31
|
+
*
|
|
32
|
+
* A failed read is forgotten at once, so the next caller asks again. An answer
|
|
33
|
+
* that is not a whole number from 0 to 255 is a failure too: it means the
|
|
34
|
+
* address is not a token.
|
|
35
|
+
*
|
|
36
|
+
* @param target - the chain and token address to read
|
|
37
|
+
* @returns the decimals the contract reports
|
|
38
|
+
*/
|
|
39
|
+
export declare const readDecimalsOnChain: ReadDecimals;
|
|
40
|
+
/**
|
|
41
|
+
* Whether the chain, not a list, is the authority for this token's decimals.
|
|
42
|
+
*
|
|
43
|
+
* Three kinds of token have no chain read: a native coin (its decimals are
|
|
44
|
+
* chain configuration and are already known), a token on a chain this client
|
|
45
|
+
* cannot build a client for (Solana, Bitcoin), and an address that is not an
|
|
46
|
+
* Ethereum-style address. Those keep the decimals they carry.
|
|
47
|
+
*
|
|
48
|
+
* @param token - the token to test
|
|
49
|
+
* @returns true when `decimals()` must be read from the contract
|
|
50
|
+
*/
|
|
51
|
+
export declare const decimalsComeFromChain: (token: Pick<Token, "chainId" | "address">) => boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Returns the token with the decimals the chain reports.
|
|
54
|
+
*
|
|
55
|
+
* WHY THIS EXISTS. A token list is a claim about a contract, and some lists
|
|
56
|
+
* carry the wrong `decimals` (gib.show listed ALI with 8 where the contract
|
|
57
|
+
* says 18). Every amount the reader types, every balance and every dollar
|
|
58
|
+
* figure is scaled by that number. This asks the contract, once, for the ONE
|
|
59
|
+
* token the reader selected. It never walks a whole list.
|
|
60
|
+
*
|
|
61
|
+
* A failed read rejects. It does NOT fall back to the list value: a number the
|
|
62
|
+
* list may have wrong is worse than no number.
|
|
63
|
+
*
|
|
64
|
+
* @param token - the token, with whatever decimals its source carried
|
|
65
|
+
* @param readDecimals - how to ask the chain; defaults to the session-cached read
|
|
66
|
+
* @returns the same token carrying the chain's decimals
|
|
67
|
+
*/
|
|
68
|
+
export declare const withChainDecimals: <TokenShape extends Pick<Token, "chainId" | "address" | "decimals">>(token: TokenShape, readDecimals?: ReadDecimals) => Promise<TokenShape>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.withChainDecimals = exports.decimalsComeFromChain = exports.readDecimalsOnChain = void 0;
|
|
3
4
|
exports.getStoreKey = getStoreKey;
|
|
4
5
|
exports.parseChainScopedAddress = parseChainScopedAddress;
|
|
5
6
|
exports.parseTokenKey = parseTokenKey;
|
|
@@ -11,31 +12,17 @@ exports.getTokenChainIdFromBridge = getTokenChainIdFromBridge;
|
|
|
11
12
|
exports.getBridgeTokenMetadata = getBridgeTokenMetadata;
|
|
12
13
|
const config_1 = require("@gibs/bridge-sdk/config");
|
|
13
14
|
const ecosystems_1 = require("@gibs/bridge-sdk/ecosystems");
|
|
15
|
+
const erc20_1 = require("@gibs/common/erc20");
|
|
14
16
|
const viem_1 = require("viem");
|
|
15
17
|
const client_js_1 = require("./client.js");
|
|
16
18
|
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
19
|
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
20
|
const splitIntoChunks = (items, size) => Array.from({ length: Math.ceil(items.length / size) }, (_unused, index) => items.slice(index * size, (index + 1) * size));
|
|
31
21
|
const bytes32Whitelist = new Set();
|
|
32
|
-
// In-memory store for token metadata (loaded once, no persistence)
|
|
33
22
|
const tokenMetadataStore = new Map();
|
|
34
|
-
// Generate store key
|
|
35
23
|
function getStoreKey(chainId, tokenAddress) {
|
|
36
24
|
return `${chainId}:${tokenAddress.toLowerCase()}`;
|
|
37
25
|
}
|
|
38
|
-
// Parse a ChainScopedAddress into its components
|
|
39
26
|
function parseChainScopedAddress(key) {
|
|
40
27
|
const [chainIdStr, address] = key.split(':');
|
|
41
28
|
const chainId = parseInt(chainIdStr ?? '', 10);
|
|
@@ -50,7 +37,6 @@ function parseChainScopedAddress(key) {
|
|
|
50
37
|
address: address,
|
|
51
38
|
};
|
|
52
39
|
}
|
|
53
|
-
// Parse a string key (chainId:address format) into its components with proper types
|
|
54
40
|
function parseTokenKey(key) {
|
|
55
41
|
const [chainIdStr, address] = key.split(':');
|
|
56
42
|
const chainId = parseInt(chainIdStr ?? '', 10);
|
|
@@ -60,21 +46,17 @@ function parseTokenKey(key) {
|
|
|
60
46
|
if (!address) {
|
|
61
47
|
throw new Error(`Invalid address in token key: ${address}`);
|
|
62
48
|
}
|
|
63
|
-
// Ensure address is properly formatted as Hex
|
|
64
49
|
const hexAddress = address.startsWith('0x') ? address : `0x${address}`;
|
|
65
50
|
return {
|
|
66
51
|
chainId,
|
|
67
52
|
address: hexAddress,
|
|
68
53
|
};
|
|
69
54
|
}
|
|
70
|
-
// Get native token metadata
|
|
71
55
|
function getNativeTokenMetadata(chainId) {
|
|
72
56
|
const chain = networks_js_1.evmChainsById.get(chainId);
|
|
73
|
-
// Safely get native token info from SDK
|
|
74
57
|
let name = chain?.nativeCurrency?.name || 'Ether';
|
|
75
58
|
let symbol = chain?.nativeCurrency?.symbol || 'ETH';
|
|
76
59
|
const decimals = chain?.nativeCurrency?.decimals || 18;
|
|
77
|
-
// Try to get more specific info from SDK if available
|
|
78
60
|
try {
|
|
79
61
|
const chainKey = (0, config_1.toChain)(chainId);
|
|
80
62
|
const sdkName = config_1.nativeTokenName[chainKey];
|
|
@@ -87,29 +69,21 @@ function getNativeTokenMetadata(chainId) {
|
|
|
87
69
|
}
|
|
88
70
|
}
|
|
89
71
|
catch {
|
|
90
|
-
// Fallback to viem chain info
|
|
91
72
|
}
|
|
92
73
|
return { name, symbol, decimals };
|
|
93
74
|
}
|
|
94
|
-
// Batch fetch token metadata for multiple tokens on the same chain
|
|
95
75
|
async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
96
76
|
const results = new Map();
|
|
97
77
|
if (tokenAddresses.length === 0)
|
|
98
78
|
return results;
|
|
99
|
-
// Get the chain and client
|
|
100
79
|
const chain = networks_js_1.evmChainsById.get(chainId);
|
|
101
80
|
if (!chain) {
|
|
102
81
|
throw new Error(`Chain not found for chainId: ${chainId}`);
|
|
103
82
|
}
|
|
104
83
|
const client = (0, client_js_1.clientFromChain)(chainId);
|
|
105
|
-
// Separate native tokens from ERC20 tokens
|
|
106
84
|
const nativeTokens = [];
|
|
107
85
|
const erc20Tokens = [];
|
|
108
86
|
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
87
|
if ((0, ecosystems_1.isNativeAsset)(address, 'evm')) {
|
|
114
88
|
nativeTokens.push(address);
|
|
115
89
|
}
|
|
@@ -117,17 +91,13 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
117
91
|
erc20Tokens.push(address);
|
|
118
92
|
}
|
|
119
93
|
});
|
|
120
|
-
// Handle native tokens
|
|
121
94
|
const nativeMetadata = getNativeTokenMetadata(chainId);
|
|
122
95
|
nativeTokens.forEach((address) => {
|
|
123
96
|
results.set(address.toLowerCase(), nativeMetadata);
|
|
124
97
|
});
|
|
125
|
-
// Handle ERC20 tokens with batch multicall
|
|
126
98
|
if (erc20Tokens.length === 0) {
|
|
127
|
-
// console.log(`No ERC20 tokens to process for chain ${chainId}`)
|
|
128
99
|
return results;
|
|
129
100
|
}
|
|
130
|
-
// console.log(`Processing ${erc20Tokens.length} ERC20 tokens for chain ${chainId}:`, erc20Tokens)
|
|
131
101
|
const addressChunks = splitIntoChunks(erc20Tokens, TOKENS_PER_MULTICALL);
|
|
132
102
|
const methods = ['symbol', 'name', 'decimals'];
|
|
133
103
|
const addressChunksToCallChunks = (addressChunks, abi) => addressChunks.map((chunk) => chunk.map((address) => methods.map((functionName) => ({
|
|
@@ -137,18 +107,9 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
137
107
|
allowFailure: true,
|
|
138
108
|
args: [],
|
|
139
109
|
}))));
|
|
140
|
-
// Try with standard ERC20 ABI first
|
|
141
110
|
const chunkedCalls = addressChunksToCallChunks(addressChunks, (address) => bytes32Whitelist.has(getStoreKey(chainId, address)) ? viem_1.erc20Abi_bytes32 : viem_1.erc20Abi);
|
|
142
111
|
const fallback = [];
|
|
143
112
|
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
113
|
const chunkAddresses = addressChunks[chunkIndex];
|
|
153
114
|
try {
|
|
154
115
|
const batchResults = await client.multicall({
|
|
@@ -160,7 +121,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
160
121
|
const symbol = batch[0].result;
|
|
161
122
|
const name = batch[1].result;
|
|
162
123
|
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
124
|
if (name && symbol && !isNaN(decimals)) {
|
|
165
125
|
results.set(tokenAddress.toLowerCase(), { name, symbol, decimals });
|
|
166
126
|
}
|
|
@@ -172,9 +132,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
172
132
|
}
|
|
173
133
|
catch (error) {
|
|
174
134
|
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
135
|
fallback.push(...chunkAddresses);
|
|
179
136
|
}
|
|
180
137
|
}
|
|
@@ -185,7 +142,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
185
142
|
const fallbackAddressChunks = splitIntoChunks(fallback, TOKENS_PER_MULTICALL);
|
|
186
143
|
const fallbackChunkedCalls = addressChunksToCallChunks(fallbackAddressChunks, () => viem_1.erc20Abi_bytes32);
|
|
187
144
|
for (const [chunkIndex, chunk] of fallbackChunkedCalls.entries()) {
|
|
188
|
-
// Same pairing rule as the primary loop above.
|
|
189
145
|
const chunkAddresses = fallbackAddressChunks[chunkIndex];
|
|
190
146
|
try {
|
|
191
147
|
console.log(`Executing fallback multicall for chain ${chainId} with ${chunk.flat().length} contracts`);
|
|
@@ -199,8 +155,8 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
199
155
|
const symbol = batch[0];
|
|
200
156
|
const name = batch[1];
|
|
201
157
|
const decimals = Number(batch[2]);
|
|
202
|
-
const symbolString = (0,
|
|
203
|
-
const nameString = (0,
|
|
158
|
+
const symbolString = (0, erc20_1.decodeBytes32Text)({ value: symbol, fallback: (0, erc20_1.shortAddressLabel)(tokenAddress) });
|
|
159
|
+
const nameString = (0, erc20_1.decodeBytes32Text)({ value: name, fallback: (0, erc20_1.shortAddressLabel)(tokenAddress) });
|
|
204
160
|
console.log(`Fallback token ${tokenAddress} results:`, {
|
|
205
161
|
symbolString,
|
|
206
162
|
nameString,
|
|
@@ -211,7 +167,6 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
211
167
|
symbol: symbolString,
|
|
212
168
|
decimals,
|
|
213
169
|
});
|
|
214
|
-
// Add to bytes32 whitelist for future optimization
|
|
215
170
|
bytes32Whitelist.add(getStoreKey(chainId, tokenAddress));
|
|
216
171
|
});
|
|
217
172
|
}
|
|
@@ -221,14 +176,11 @@ async function batchFetchTokenMetadata(chainId, tokenAddresses) {
|
|
|
221
176
|
}
|
|
222
177
|
return results;
|
|
223
178
|
}
|
|
224
|
-
// Get token metadata synchronously (from store only)
|
|
225
179
|
function getTokenMetadata(chainId, tokenAddress) {
|
|
226
180
|
const storeKey = getStoreKey(chainId, tokenAddress);
|
|
227
181
|
return tokenMetadataStore.get(storeKey) || null;
|
|
228
182
|
}
|
|
229
|
-
// Load token metadata for multiple tokens (called once on page load)
|
|
230
183
|
async function loadTokenMetadata(tokens) {
|
|
231
|
-
// Group tokens by chain ID for batching
|
|
232
184
|
const tokensByChain = new Map();
|
|
233
185
|
tokens.forEach(({ chainId, address }) => {
|
|
234
186
|
if (!tokensByChain.has(chainId)) {
|
|
@@ -236,18 +188,13 @@ async function loadTokenMetadata(tokens) {
|
|
|
236
188
|
}
|
|
237
189
|
tokensByChain.get(chainId).push(address);
|
|
238
190
|
});
|
|
239
|
-
// Batch fetch for each chain
|
|
240
191
|
const batchPromises = Array.from(tokensByChain.entries()).map(async ([chainId, addresses]) => {
|
|
241
192
|
try {
|
|
242
|
-
// console.log(`Loading token metadata for chain ${chainId} (${addresses.length} tokens):`, addresses)
|
|
243
193
|
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
194
|
results.forEach((metadata, address) => {
|
|
247
195
|
if (metadata) {
|
|
248
196
|
const storeKey = getStoreKey(chainId, address);
|
|
249
197
|
tokenMetadataStore.set(storeKey, metadata);
|
|
250
|
-
// console.log(`Stored metadata for ${storeKey}:`, metadata)
|
|
251
198
|
}
|
|
252
199
|
});
|
|
253
200
|
}
|
|
@@ -257,11 +204,9 @@ async function loadTokenMetadata(tokens) {
|
|
|
257
204
|
});
|
|
258
205
|
await Promise.allSettled(batchPromises);
|
|
259
206
|
}
|
|
260
|
-
// Get store size
|
|
261
207
|
function getStoreSize() {
|
|
262
208
|
return tokenMetadataStore.size;
|
|
263
209
|
}
|
|
264
|
-
// Utility functions for bridge transactions
|
|
265
210
|
function getTokenAddressFromBridge(bridge) {
|
|
266
211
|
return (bridge.originationToken?.address ||
|
|
267
212
|
bridge.destinationToken?.address ||
|
|
@@ -283,3 +228,34 @@ function getBridgeTokenMetadata(bridge) {
|
|
|
283
228
|
return null;
|
|
284
229
|
return getTokenMetadata(chainId, address);
|
|
285
230
|
}
|
|
231
|
+
const decimalsReads = new Map();
|
|
232
|
+
const readDecimalsOnChain = ({ chainId, address }) => {
|
|
233
|
+
const key = getStoreKey(chainId, address);
|
|
234
|
+
const known = decimalsReads.get(key);
|
|
235
|
+
if (known)
|
|
236
|
+
return known;
|
|
237
|
+
const pending = (0, client_js_1.clientFromChain)(chainId)
|
|
238
|
+
.readContract({ address, abi: viem_1.erc20Abi, functionName: 'decimals' })
|
|
239
|
+
.then((answer) => {
|
|
240
|
+
const decimals = Number(answer);
|
|
241
|
+
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 255) {
|
|
242
|
+
throw new Error(`Token ${address} on chain ${chainId} reported decimals ${String(answer)}`);
|
|
243
|
+
}
|
|
244
|
+
return decimals;
|
|
245
|
+
});
|
|
246
|
+
decimalsReads.set(key, pending);
|
|
247
|
+
pending.catch(() => decimalsReads.delete(key));
|
|
248
|
+
return pending;
|
|
249
|
+
};
|
|
250
|
+
exports.readDecimalsOnChain = readDecimalsOnChain;
|
|
251
|
+
const decimalsComeFromChain = (token) => networks_js_1.evmChainsById.has(token.chainId) &&
|
|
252
|
+
(0, viem_1.isAddress)(token.address, { strict: false }) &&
|
|
253
|
+
!(0, ecosystems_1.isNativeAsset)(token.address, 'evm');
|
|
254
|
+
exports.decimalsComeFromChain = decimalsComeFromChain;
|
|
255
|
+
const withChainDecimals = async (token, readDecimals = exports.readDecimalsOnChain) => {
|
|
256
|
+
if (!(0, exports.decimalsComeFromChain)(token))
|
|
257
|
+
return token;
|
|
258
|
+
const decimals = await readDecimals({ chainId: token.chainId, address: token.address });
|
|
259
|
+
return decimals === token.decimals ? token : { ...token, decimals };
|
|
260
|
+
};
|
|
261
|
+
exports.withChainDecimals = withChainDecimals;
|
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) });
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createCrossingSimulator } from '@gibs/bridge-sdk/crossing-simulation';
|
|
2
|
+
import type { PublicClient } from 'viem';
|
|
3
|
+
/**
|
|
4
|
+
* The node that answers a crossing simulation, by chain id.
|
|
5
|
+
*
|
|
6
|
+
* WHY NOT THE CHAIN'S NORMAL NODES. A simulation needs `eth_simulateV1`, and
|
|
7
|
+
* the nodes this application reads with are chosen for plain reads. A node that
|
|
8
|
+
* lacks the method answers an error, and the simulator then reports
|
|
9
|
+
* "unavailable": no tax check, and no first crossing. A node that is known to
|
|
10
|
+
* serve the method keeps the check working. `ethereum-rpc.publicnode.com` was
|
|
11
|
+
* measured to serve it on 2026-10-21.
|
|
12
|
+
*
|
|
13
|
+
* Only Ethereum is listed because only the Ethereum entry can make a first
|
|
14
|
+
* crossing. A chain with no entry here has no simulation.
|
|
15
|
+
*/
|
|
16
|
+
export declare const simulationEndpoints: Readonly<Record<number, string>>;
|
|
17
|
+
/**
|
|
18
|
+
* A client on the simulation node for one chain, built once.
|
|
19
|
+
*
|
|
20
|
+
* @param chainId - the chain whose entry mediator is simulated
|
|
21
|
+
* @returns the client, or null when no simulation node is listed for the chain
|
|
22
|
+
*/
|
|
23
|
+
export declare const simulationClientOrNull: (chainId: number) => PublicClient | null;
|
|
24
|
+
/**
|
|
25
|
+
* The one simulator the whole interface shares. The route search and the
|
|
26
|
+
* warning beside the Output ask the same question for the same token and
|
|
27
|
+
* amount. A shared cache answers the second asker without a second request,
|
|
28
|
+
* and the shared pacing keeps the node from being asked in a burst.
|
|
29
|
+
*
|
|
30
|
+
* @returns the shared simulator
|
|
31
|
+
*/
|
|
32
|
+
export declare const sharedCrossingSimulator: () => ReturnType<typeof createCrossingSimulator>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createCrossingSimulator } from '@gibs/bridge-sdk/crossing-simulation';
|
|
2
|
+
import { clientFromChain as buildClient } from '@gibs/common/client';
|
|
3
|
+
import { rpcBatchSetting } from './client.js';
|
|
4
|
+
import { evmChainsById } from './networks.js';
|
|
5
|
+
export const simulationEndpoints = {
|
|
6
|
+
1: 'https://ethereum-rpc.publicnode.com',
|
|
7
|
+
};
|
|
8
|
+
const simulationClients = new Map();
|
|
9
|
+
export const simulationClientOrNull = (chainId) => {
|
|
10
|
+
const cached = simulationClients.get(chainId);
|
|
11
|
+
if (cached !== undefined)
|
|
12
|
+
return cached;
|
|
13
|
+
const url = simulationEndpoints[chainId];
|
|
14
|
+
const chain = evmChainsById.get(chainId);
|
|
15
|
+
const client = url === undefined || chain === undefined ? null : buildClient({ chain, urls: [url], batch: rpcBatchSetting(chainId) });
|
|
16
|
+
simulationClients.set(chainId, client);
|
|
17
|
+
return client;
|
|
18
|
+
};
|
|
19
|
+
let sharedSimulator;
|
|
20
|
+
export const sharedCrossingSimulator = () => {
|
|
21
|
+
sharedSimulator ??= createCrossingSimulator({ clientForChain: simulationClientOrNull });
|
|
22
|
+
return sharedSimulator;
|
|
23
|
+
};
|