@w3lib/evm-batch-call 0.1.0 → 0.2.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/CHANGELOG.md +32 -0
- package/README.md +103 -12
- package/dist/call.d.ts +8 -2
- package/dist/call.d.ts.map +1 -1
- package/dist/call.js +25 -1
- package/dist/call.js.map +1 -1
- package/dist/chains.d.ts +13 -0
- package/dist/chains.d.ts.map +1 -0
- package/dist/chains.js +35 -0
- package/dist/chains.js.map +1 -0
- package/dist/detect.d.ts +23 -0
- package/dist/detect.d.ts.map +1 -0
- package/dist/detect.js +178 -0
- package/dist/detect.js.map +1 -0
- package/dist/erc20.d.ts +83 -7
- package/dist/erc20.d.ts.map +1 -1
- package/dist/erc20.js +36 -5
- package/dist/erc20.js.map +1 -1
- package/dist/fallback.d.ts +2 -0
- package/dist/fallback.d.ts.map +1 -1
- package/dist/fallback.js +6 -18
- package/dist/fallback.js.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/dist/nft.d.ts +71 -0
- package/dist/nft.d.ts.map +1 -0
- package/dist/nft.js +194 -0
- package/dist/nft.js.map +1 -0
- package/dist/provider.d.ts +93 -12
- package/dist/provider.d.ts.map +1 -1
- package/dist/provider.js +306 -48
- package/dist/provider.js.map +1 -1
- package/dist/shortcuts.d.ts +95 -0
- package/dist/shortcuts.d.ts.map +1 -0
- package/dist/shortcuts.js +175 -0
- package/dist/shortcuts.js.map +1 -0
- package/dist/source.d.ts +21 -1
- package/dist/source.d.ts.map +1 -1
- package/dist/source.js +96 -3
- package/dist/source.js.map +1 -1
- package/dist/tron.d.ts +6 -0
- package/dist/tron.d.ts.map +1 -1
- package/dist/tron.js +16 -1
- package/dist/tron.js.map +1 -1
- package/dist/util.d.ts +6 -0
- package/dist/util.d.ts.map +1 -0
- package/dist/util.js +20 -0
- package/dist/util.js.map +1 -0
- package/package.json +3 -2
- package/src/call.ts +32 -3
- package/src/chains.ts +46 -0
- package/src/detect.ts +193 -0
- package/src/erc20.ts +111 -9
- package/src/fallback.ts +7 -20
- package/src/index.ts +55 -4
- package/src/nft.ts +298 -0
- package/src/provider.ts +416 -54
- package/src/shortcuts.ts +256 -0
- package/src/source.ts +102 -3
- package/src/tron.ts +21 -2
- package/src/util.ts +20 -0
package/src/provider.ts
CHANGED
|
@@ -2,12 +2,47 @@ import { type BigNumberish } from 'ethers'
|
|
|
2
2
|
|
|
3
3
|
import { aggregate, type AggregateContext, type BlockTag, type CallOverrides, type EthersLikeProvider } from './aggregate.js'
|
|
4
4
|
import { Batcher, type BatchOptions } from './batcher.js'
|
|
5
|
-
import { decodeCall, encodeCall, type BoundCall, type Call, type CallRequest, type FailableCall, type RawResult } from './call.js'
|
|
5
|
+
import { asStringOrBytes32, decodeCall, encodeCall, type BoundCall, type Call, type CallRequest, type FailableCall, type RawResult } from './call.js'
|
|
6
6
|
import { Contract, bindCall, type ContractAbi, type ContractRunner } from './contract.js'
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_NATIVE_TOKENS,
|
|
9
|
+
ERC20_ABI,
|
|
10
|
+
formatAmount,
|
|
11
|
+
getCachedTokenMeta,
|
|
12
|
+
setCachedTokenMeta,
|
|
13
|
+
type BalanceToken,
|
|
14
|
+
type Erc20Contract,
|
|
15
|
+
type TokenBalance,
|
|
16
|
+
type TokenAllowance,
|
|
17
|
+
MAX_UINT256,
|
|
18
|
+
UNLIMITED_ALLOWANCE_THRESHOLD,
|
|
19
|
+
DEFAULT_TOKEN_FIELDS,
|
|
20
|
+
type DefaultTokenField,
|
|
21
|
+
type TokenDetails,
|
|
22
|
+
type TokenField,
|
|
23
|
+
} from './erc20.js'
|
|
8
24
|
import { CallFailedError, isExecutionError } from './errors.js'
|
|
9
25
|
import { MULTICALL3_ADDRESS, getMulticall3, type Multicall } from './multicall.js'
|
|
10
|
-
import {
|
|
26
|
+
import { getNativeCurrency } from './chains.js'
|
|
27
|
+
import {
|
|
28
|
+
erc1155Balances,
|
|
29
|
+
nftBalances,
|
|
30
|
+
nftCollections,
|
|
31
|
+
nftOwners,
|
|
32
|
+
nftTokenUris,
|
|
33
|
+
type DefaultNftCollectionField,
|
|
34
|
+
type Erc1155Balance,
|
|
35
|
+
type NftBalance,
|
|
36
|
+
type NftCollection,
|
|
37
|
+
type NftCollectionField,
|
|
38
|
+
type NftCollectionsOptions,
|
|
39
|
+
type NftItem,
|
|
40
|
+
type NftOwner,
|
|
41
|
+
type NftTokenUri,
|
|
42
|
+
type NftTokenUriOptions,
|
|
43
|
+
} from './nft.js'
|
|
44
|
+
import { detectChainId } from './detect.js'
|
|
45
|
+
import { isTronChain, resolveSource, type ProviderSource, type SourceOptions } from './source.js'
|
|
11
46
|
|
|
12
47
|
export type { ProviderSource }
|
|
13
48
|
|
|
@@ -40,8 +75,33 @@ export interface ProviderConfig extends SourceOptions {
|
|
|
40
75
|
chunkSize?: number
|
|
41
76
|
/** `provider.call()` 自动合并的参数 */
|
|
42
77
|
batch?: BatchOptions
|
|
43
|
-
/** `balances()` 里视为主币的地址,默认 0xeeee…eeee
|
|
78
|
+
/** `balances()` 里视为主币的地址,默认 0xeeee…eeee(NATIVE_TOKEN)和零地址 */
|
|
44
79
|
nativeTokens?: readonly string[]
|
|
80
|
+
/** 主币精度,默认按内置链信息表(NATIVE_CURRENCIES),表里没有时 EVM 18、Tron 6 */
|
|
81
|
+
nativeDecimals?: number
|
|
82
|
+
/** 主币 symbol(balances 的 symbol 选项、tokens 用),默认按内置链信息表,表里没有时为 null */
|
|
83
|
+
nativeSymbol?: string
|
|
84
|
+
/** 主币名称(tokens 用),默认按内置链信息表,表里没有时为 null */
|
|
85
|
+
nativeName?: string
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface TokensOptions<F extends TokenField = DefaultTokenField> extends CallOverrides {
|
|
89
|
+
/** 要返回的字段,默认 ['name', 'symbol', 'decimals'] */
|
|
90
|
+
fields?: readonly F[]
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface BalancesOptions extends CallOverrides {
|
|
94
|
+
/** 同时返回 symbol(代币查一次后缓存;主币取 nativeSymbol / 内置链信息表)。默认 false */
|
|
95
|
+
symbol?: boolean
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 构造参数第一个是 chainId 还是节点:数字、数字字符串、0x 十六进制视为 chainId,其余(URL、对象、数组)视为节点 */
|
|
99
|
+
function isChainIdArg(value: unknown): value is number | bigint | string {
|
|
100
|
+
return (
|
|
101
|
+
typeof value === 'number' ||
|
|
102
|
+
typeof value === 'bigint' ||
|
|
103
|
+
(typeof value === 'string' && /^\s*(\d+|0x[0-9a-fA-F]+)\s*$/.test(value))
|
|
104
|
+
)
|
|
45
105
|
}
|
|
46
106
|
|
|
47
107
|
const ETH_BALANCE_INPUTS = [{ name: 'addr', type: 'address' }] as const
|
|
@@ -56,26 +116,123 @@ const ETH_BALANCE_OUTPUTS = [{ name: 'balance', type: 'uint256' }] as const
|
|
|
56
116
|
* ```
|
|
57
117
|
*/
|
|
58
118
|
export class Provider implements ContractRunner {
|
|
59
|
-
|
|
119
|
+
/** 不传 chainId 时在识别完成前为 null */
|
|
120
|
+
#ctx: AggregateContext | null = null
|
|
121
|
+
/** 识别中的 Promise;识别失败后置空,下次使用时重试 */
|
|
122
|
+
#detecting: Promise<AggregateContext> | null = null
|
|
123
|
+
readonly #source: ProviderSource | readonly ProviderSource[] | undefined
|
|
60
124
|
readonly #batcher: Batcher
|
|
61
125
|
readonly #nativeTokens: Set<string>
|
|
126
|
+
readonly #config: ProviderConfig
|
|
62
127
|
|
|
128
|
+
/**
|
|
129
|
+
* 两种写法:
|
|
130
|
+
*
|
|
131
|
+
* ```ts
|
|
132
|
+
* new Provider(window.ethereum) // 只传节点:chainId 从节点识别
|
|
133
|
+
* new Provider([url1, url2], config)
|
|
134
|
+
* new Provider(56) // 只传 chainId:使用内置公共节点
|
|
135
|
+
* new Provider(56, rpc, config) // 都传(与 ethcall 相同),不需要识别
|
|
136
|
+
* ```
|
|
137
|
+
*
|
|
138
|
+
* @param provider 节点:RPC URL、ethers Provider、钱包(window.ethereum / tronWeb)或它们的数组(主节点 + 备用节点)
|
|
139
|
+
* @param config 可选配置
|
|
140
|
+
*/
|
|
141
|
+
constructor(provider: ProviderSource | readonly ProviderSource[], config?: ProviderConfig)
|
|
63
142
|
/**
|
|
64
143
|
* @param chainId 链 ID(接受数字字符串)
|
|
65
|
-
* @param provider
|
|
66
|
-
* 不传则使用内置的公共节点表
|
|
144
|
+
* @param provider 节点,不传则使用内置的公共节点表
|
|
67
145
|
* @param config 可选配置
|
|
68
146
|
*/
|
|
69
|
-
constructor(chainId: number | string, provider?: ProviderSource | readonly ProviderSource[], config
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
147
|
+
constructor(chainId: number | string, provider?: ProviderSource | readonly ProviderSource[], config?: ProviderConfig)
|
|
148
|
+
constructor(
|
|
149
|
+
first: number | string | ProviderSource | readonly ProviderSource[],
|
|
150
|
+
second?: ProviderSource | readonly ProviderSource[] | ProviderConfig,
|
|
151
|
+
third?: ProviderConfig,
|
|
152
|
+
) {
|
|
153
|
+
const hasChainId = isChainIdArg(first)
|
|
154
|
+
const source = (hasChainId ? second : first) as ProviderSource | readonly ProviderSource[] | undefined
|
|
155
|
+
const config = ((hasChainId ? third : second) ?? {}) as ProviderConfig
|
|
156
|
+
this.#config = config
|
|
77
157
|
this.#batcher = new Batcher((requests, overrides) => this.#aggregate(requests, overrides), config.batch)
|
|
78
158
|
this.#nativeTokens = new Set((config.nativeTokens ?? DEFAULT_NATIVE_TOKENS).map((t) => t.toLowerCase()))
|
|
159
|
+
|
|
160
|
+
this.#source = source
|
|
161
|
+
if (hasChainId) {
|
|
162
|
+
this.#ctx = this.#createContext(Number(first), source)
|
|
163
|
+
} else {
|
|
164
|
+
if (source === undefined) {
|
|
165
|
+
throw new Error('Provider requires a chainId or a provider')
|
|
166
|
+
}
|
|
167
|
+
// 提前开始识别;失败时由使用方的调用拿到错误(这里避免未处理的 rejection)
|
|
168
|
+
this.#ensureReady().catch(() => {})
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 只传节点时等 chainId 识别完成后再返回实例,之后 rpc / multicall 等同步属性可以直接用。
|
|
174
|
+
*
|
|
175
|
+
* ```ts
|
|
176
|
+
* const multi = await Provider.create(window.ethereum)
|
|
177
|
+
* multi.rpc // 已就绪
|
|
178
|
+
* ```
|
|
179
|
+
*/
|
|
180
|
+
static async create(
|
|
181
|
+
provider: ProviderSource | readonly ProviderSource[],
|
|
182
|
+
config?: ProviderConfig,
|
|
183
|
+
): Promise<Provider> {
|
|
184
|
+
return new Provider(provider, config).ready()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 取初始化好的上下文;识别失败不会被永久记住,下次调用重新识别(如节点短暂限流) */
|
|
188
|
+
#ensureReady(): Promise<AggregateContext> {
|
|
189
|
+
if (this.#ctx) {
|
|
190
|
+
return Promise.resolve(this.#ctx)
|
|
191
|
+
}
|
|
192
|
+
if (!this.#detecting) {
|
|
193
|
+
const source = this.#source as ProviderSource | readonly ProviderSource[]
|
|
194
|
+
const detecting = detectChainId(source, this.#config.fallback?.timeout).then((id) => {
|
|
195
|
+
this.#ctx = this.#createContext(id, source)
|
|
196
|
+
return this.#ctx
|
|
197
|
+
})
|
|
198
|
+
this.#detecting = detecting
|
|
199
|
+
detecting.catch(() => {
|
|
200
|
+
if (this.#detecting === detecting) {
|
|
201
|
+
this.#detecting = null
|
|
202
|
+
}
|
|
203
|
+
})
|
|
204
|
+
}
|
|
205
|
+
return this.#detecting
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
#createContext(chainId: number, source: ProviderSource | readonly ProviderSource[] | undefined): AggregateContext {
|
|
209
|
+
const config = this.#config
|
|
210
|
+
return {
|
|
211
|
+
provider: resolveSource(chainId, source, config),
|
|
212
|
+
chainId,
|
|
213
|
+
multicall: config.deployless ? null : resolveMulticall(chainId, config.multicall),
|
|
214
|
+
chunkSize: config.chunkSize ?? 500,
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 链 ID(不传 chainId 构造时,会等待从节点识别完成) */
|
|
219
|
+
async getChainId(): Promise<number> {
|
|
220
|
+
return (await this.#ensureReady()).chainId
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 等待初始化完成(只传节点时会先识别 chainId;识别失败在这里抛出) */
|
|
224
|
+
async ready(): Promise<this> {
|
|
225
|
+
await this.#ensureReady()
|
|
226
|
+
return this
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
#nativeCurrency(chainId: number): { decimals: number; symbol: string | null; name: string | null } {
|
|
230
|
+
const known = getNativeCurrency(chainId)
|
|
231
|
+
return {
|
|
232
|
+
decimals: this.#config.nativeDecimals ?? known?.decimals ?? (isTronChain(chainId) ? 6 : 18),
|
|
233
|
+
symbol: this.#config.nativeSymbol ?? known?.symbol ?? null,
|
|
234
|
+
name: this.#config.nativeName ?? known?.name ?? null,
|
|
235
|
+
}
|
|
79
236
|
}
|
|
80
237
|
|
|
81
238
|
/**
|
|
@@ -97,45 +254,244 @@ export class Provider implements ContractRunner {
|
|
|
97
254
|
}
|
|
98
255
|
|
|
99
256
|
/**
|
|
100
|
-
*
|
|
101
|
-
*
|
|
257
|
+
* 批量查余额(含按 decimals 换算后的数值),主币和代币混在一起、一次请求。
|
|
258
|
+
*
|
|
259
|
+
* ```ts
|
|
260
|
+
* const list = await multi.balances(user, [NATIVE_TOKEN, USDT, { address: USDC, decimals: 6 }], { symbol: true })
|
|
261
|
+
* list[1] // { token: USDT, native: false, balance: '1234500000000000000000', decimals: 18, formatted: '1234.5', symbol: 'USDT', success: true }
|
|
262
|
+
* ```
|
|
263
|
+
*
|
|
264
|
+
* - 主币地址见 config.nativeTokens(默认 0xeeee…eeee 和零地址);精度 / symbol 按内置链信息表,可用 nativeDecimals / nativeSymbol 覆盖
|
|
265
|
+
* - decimals、symbol 查到一次后缓存,之后只查 balanceOf;也可以直接传 `{ address, decimals }`
|
|
266
|
+
* - 单个代币失败(非合约地址、非法地址等)不影响其他代币,该项 success 为 false
|
|
102
267
|
*/
|
|
103
|
-
async balances(owner: string, tokens: readonly
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
)
|
|
107
|
-
const
|
|
108
|
-
|
|
268
|
+
async balances(owner: string, tokens: readonly BalanceToken[], options: BalancesOptions = {}): Promise<TokenBalance[]> {
|
|
269
|
+
const { symbol: withSymbol = false, ...overrides } = options
|
|
270
|
+
const { chainId } = await this.#ensureReady()
|
|
271
|
+
const nativeCurrency = this.#nativeCurrency(chainId)
|
|
272
|
+
const items = tokens.map((token) => {
|
|
273
|
+
const resolved = this.#resolveToken(chainId, token, nativeCurrency.decimals)
|
|
274
|
+
const symbol = resolved.native ? nativeCurrency.symbol : getCachedTokenMeta(chainId, resolved.address).symbol
|
|
275
|
+
return { ...resolved, symbol }
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
const calls: Call[] = []
|
|
279
|
+
const plan = items.map(({ address, native, decimals, symbol }) => {
|
|
280
|
+
const balanceIndex = calls.push(native ? this.getEthBalance(owner) : this.erc20(address).balanceOf(owner)) - 1
|
|
281
|
+
const decimalsIndex = decimals === undefined ? calls.push(this.erc20(address).decimals()) - 1 : -1
|
|
282
|
+
const symbolIndex = withSymbol && !native && symbol === undefined ? calls.push(this.#symbolCall(address)) - 1 : -1
|
|
283
|
+
return { balanceIndex, decimalsIndex, symbolIndex }
|
|
284
|
+
})
|
|
285
|
+
const results = await this.tryAll(calls, overrides)
|
|
286
|
+
|
|
287
|
+
return items.map((item, i) => {
|
|
288
|
+
const { balanceIndex, decimalsIndex, symbolIndex } = plan[i] as { balanceIndex: number; decimalsIndex: number; symbolIndex: number }
|
|
289
|
+
const balance = results[balanceIndex] as bigint | null
|
|
290
|
+
const fetchedDecimals = decimalsIndex === -1 ? null : (results[decimalsIndex] as bigint | null)
|
|
291
|
+
const fetchedSymbol = symbolIndex === -1 ? null : (results[symbolIndex] as string | null)
|
|
292
|
+
if (!item.native && (fetchedDecimals !== null || fetchedSymbol !== null)) {
|
|
293
|
+
setCachedTokenMeta(chainId, item.address, {
|
|
294
|
+
...(fetchedDecimals !== null ? { decimals: Number(fetchedDecimals) } : {}),
|
|
295
|
+
...(fetchedSymbol !== null ? { symbol: fetchedSymbol } : {}),
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
const decimals = item.decimals ?? (fetchedDecimals === null ? null : Number(fetchedDecimals))
|
|
299
|
+
const extra = withSymbol ? { symbol: item.symbol ?? fetchedSymbol ?? null } : {}
|
|
300
|
+
if (balance === null || decimals === null) {
|
|
301
|
+
return { token: item.address, native: item.native, balance: '0', decimals: decimals ?? 0, formatted: '0', ...extra, success: false }
|
|
302
|
+
}
|
|
303
|
+
// 结果全是字符串 / 数字 / 布尔 / null,可以直接 JSON.stringify
|
|
304
|
+
return {
|
|
305
|
+
token: item.address,
|
|
306
|
+
native: item.native,
|
|
307
|
+
balance: balance.toString(),
|
|
308
|
+
decimals,
|
|
309
|
+
formatted: formatAmount(balance, decimals),
|
|
310
|
+
...extra,
|
|
311
|
+
success: true,
|
|
312
|
+
}
|
|
313
|
+
})
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* 批量查 ERC20 授权额度(发交易前判断是否需要 approve),一次请求。
|
|
318
|
+
*
|
|
319
|
+
* ```ts
|
|
320
|
+
* const [usdt] = await multi.allowances(user, router, [USDT])
|
|
321
|
+
* usdt // { token: USDT, spender: router, native: false, allowance: '…', decimals: 18, formatted: '100', unlimited: false, success: true }
|
|
322
|
+
* ```
|
|
323
|
+
*
|
|
324
|
+
* - 主币不需要授权:native 为 true,额度视为 MaxUint256、unlimited 为 true,不发请求
|
|
325
|
+
* - decimals 与 balances / tokens 共用缓存;也可以直接传 `{ address, decimals }`
|
|
326
|
+
*/
|
|
327
|
+
async allowances(
|
|
328
|
+
owner: string,
|
|
329
|
+
spender: string,
|
|
330
|
+
tokens: readonly BalanceToken[],
|
|
331
|
+
overrides?: CallOverrides,
|
|
332
|
+
): Promise<TokenAllowance[]> {
|
|
333
|
+
const { chainId } = await this.#ensureReady()
|
|
334
|
+
const nativeDecimals = this.#nativeCurrency(chainId).decimals
|
|
335
|
+
const calls: Call[] = []
|
|
336
|
+
const plan = tokens.map((token) => {
|
|
337
|
+
const { address, native, decimals } = this.#resolveToken(chainId, token, nativeDecimals)
|
|
338
|
+
const allowanceIndex = native ? -1 : calls.push(this.erc20(address).allowance(owner, spender)) - 1
|
|
339
|
+
const decimalsIndex = native || decimals !== undefined ? -1 : calls.push(this.erc20(address).decimals()) - 1
|
|
340
|
+
return { address, native, decimals, allowanceIndex, decimalsIndex }
|
|
341
|
+
})
|
|
342
|
+
const results = calls.length ? await this.tryAll(calls, overrides) : []
|
|
343
|
+
|
|
344
|
+
return plan.map(({ address, native, decimals: known, allowanceIndex, decimalsIndex }) => {
|
|
345
|
+
const allowance = native ? MAX_UINT256 : ((results[allowanceIndex] as bigint | null) ?? null)
|
|
346
|
+
const fetched = decimalsIndex === -1 ? null : ((results[decimalsIndex] as bigint | null) ?? null)
|
|
347
|
+
if (fetched !== null) {
|
|
348
|
+
setCachedTokenMeta(chainId, address, { decimals: Number(fetched) })
|
|
349
|
+
}
|
|
350
|
+
const decimals = known ?? (fetched === null ? null : Number(fetched))
|
|
351
|
+
if (allowance === null || decimals === null) {
|
|
352
|
+
return { token: address, spender, native, allowance: '0', decimals: decimals ?? 0, formatted: '0', unlimited: false, success: false }
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
token: address,
|
|
356
|
+
spender,
|
|
357
|
+
native,
|
|
358
|
+
allowance: allowance.toString(),
|
|
359
|
+
decimals,
|
|
360
|
+
formatted: formatAmount(allowance, decimals),
|
|
361
|
+
unlimited: allowance >= UNLIMITED_ALLOWANCE_THRESHOLD,
|
|
362
|
+
success: true,
|
|
363
|
+
}
|
|
364
|
+
})
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** 批量查 NFT 集合信息(标准 / name / symbol / totalSupply),字段可选 */
|
|
368
|
+
nftCollections<const F extends NftCollectionField = DefaultNftCollectionField>(
|
|
369
|
+
collections: readonly string[],
|
|
370
|
+
options?: NftCollectionsOptions<F>,
|
|
371
|
+
): Promise<NftCollection<F>[]> {
|
|
372
|
+
return nftCollections<F>(this, collections, options)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** 批量查 ERC721 持有数量(balanceOf) */
|
|
376
|
+
nftBalances(owner: string, collections: readonly string[], overrides?: CallOverrides): Promise<NftBalance[]> {
|
|
377
|
+
return nftBalances(this, owner, collections, overrides)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** 批量查 ERC721 持有人(ownerOf),可混合多个集合 */
|
|
381
|
+
nftOwners(items: readonly NftItem[], overrides?: CallOverrides): Promise<NftOwner[]> {
|
|
382
|
+
return nftOwners(this, items, overrides)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** 批量查 NFT 元数据地址:兼容 ERC721 tokenURI 与 ERC1155 uri({id} 按规范替换),可转换 ipfs:// */
|
|
386
|
+
nftTokenUris(items: readonly NftItem[], options?: NftTokenUriOptions): Promise<NftTokenUri[]> {
|
|
387
|
+
return nftTokenUris(this, items, options)
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** 批量查 ERC1155 余额 */
|
|
391
|
+
erc1155Balances(owner: string, items: readonly NftItem[], overrides?: CallOverrides): Promise<Erc1155Balance[]> {
|
|
392
|
+
return erc1155Balances(this, owner, items, overrides)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** symbol() 调用:string 解码失败时按 bytes32 解析(MKR 等老代币) */
|
|
396
|
+
#symbolCall(address: string): Call<string> {
|
|
397
|
+
return asStringOrBytes32(this.erc20(address).symbol())
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** 解析 balances / allowances 的代币参数:是否主币、已知的 decimals(传入的 > 主币配置 / 缓存) */
|
|
401
|
+
#resolveToken(chainId: number, token: BalanceToken, nativeDecimals: number): { address: string; native: boolean; decimals: number | undefined } {
|
|
402
|
+
const address = typeof token === 'string' ? token : token.address
|
|
403
|
+
const native = this.#nativeTokens.has(address.toLowerCase())
|
|
404
|
+
const passed = typeof token === 'string' ? undefined : token.decimals
|
|
405
|
+
const decimals = passed ?? (native ? nativeDecimals : getCachedTokenMeta(chainId, address).decimals)
|
|
406
|
+
return { address, native, decimals }
|
|
109
407
|
}
|
|
110
408
|
|
|
111
409
|
/**
|
|
112
|
-
*
|
|
113
|
-
*
|
|
410
|
+
* 批量查 ERC20 代币详情,一次请求;可以选择返回哪些字段。
|
|
411
|
+
*
|
|
412
|
+
* ```ts
|
|
413
|
+
* await multi.tokens([USDT, NATIVE_TOKEN]) // name / symbol / decimals
|
|
414
|
+
* await multi.tokens([USDT], { fields: ['symbol', 'decimals', 'totalSupply'] })
|
|
415
|
+
* // [{ address: USDT, native: false, symbol: 'USDT', decimals: 18, totalSupply: '…', totalSupplyFormatted: '…', success: true }]
|
|
416
|
+
* ```
|
|
417
|
+
*
|
|
418
|
+
* - name / symbol / decimals 查到一次后缓存(与 balances 共用),totalSupply 每次都查
|
|
419
|
+
* - 主币占位地址不发请求,信息取内置链信息表(可用 nativeName / nativeSymbol / nativeDecimals 覆盖),totalSupply 为 null
|
|
420
|
+
* - symbol / name 兼容返回 bytes32 的老代币(MKR 等)
|
|
421
|
+
* - 读取失败的字段为 null;请求的字段都读到时 success 为 true
|
|
114
422
|
*/
|
|
115
|
-
async
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
423
|
+
async tokens<const F extends TokenField = DefaultTokenField>(
|
|
424
|
+
tokens: readonly string[],
|
|
425
|
+
options: TokensOptions<F> = {},
|
|
426
|
+
): Promise<TokenDetails<F>[]> {
|
|
427
|
+
const { fields = DEFAULT_TOKEN_FIELDS as unknown as readonly F[], ...overrides } = options
|
|
428
|
+
const wanted = new Set<TokenField>(fields)
|
|
429
|
+
const needDecimals = wanted.has('decimals') || wanted.has('totalSupply')
|
|
430
|
+
const { chainId } = await this.#ensureReady()
|
|
431
|
+
const nativeCurrency = this.#nativeCurrency(chainId)
|
|
432
|
+
|
|
433
|
+
const calls: Call[] = []
|
|
434
|
+
const plan = tokens.map((address) => {
|
|
435
|
+
const native = this.#nativeTokens.has(address.toLowerCase())
|
|
436
|
+
const meta = native
|
|
437
|
+
? { name: nativeCurrency.name ?? undefined, symbol: nativeCurrency.symbol ?? undefined, decimals: nativeCurrency.decimals }
|
|
438
|
+
: getCachedTokenMeta(chainId, address)
|
|
439
|
+
const index: Partial<Record<TokenField, number>> = {}
|
|
440
|
+
if (!native) {
|
|
441
|
+
const erc20 = this.erc20(address)
|
|
442
|
+
if (wanted.has('name') && meta.name === undefined) {
|
|
443
|
+
index.name = calls.push(asStringOrBytes32(erc20.name())) - 1
|
|
444
|
+
}
|
|
445
|
+
if (wanted.has('symbol') && meta.symbol === undefined) {
|
|
446
|
+
index.symbol = calls.push(this.#symbolCall(address)) - 1
|
|
447
|
+
}
|
|
448
|
+
if (needDecimals && meta.decimals === undefined) {
|
|
449
|
+
index.decimals = calls.push(erc20.decimals()) - 1
|
|
450
|
+
}
|
|
451
|
+
if (wanted.has('totalSupply')) {
|
|
452
|
+
index.totalSupply = calls.push(erc20.totalSupply()) - 1
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return { address, native, meta, index }
|
|
121
456
|
})
|
|
122
457
|
const results = calls.length ? await this.tryAll(calls, overrides) : []
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
458
|
+
const read = <T>(i: number | undefined): T | null => (i === undefined ? null : ((results[i] as T | null) ?? null))
|
|
459
|
+
|
|
460
|
+
return plan.map(({ address, native, meta, index }) => {
|
|
461
|
+
const name = meta.name ?? read<string>(index.name)
|
|
462
|
+
const symbol = meta.symbol ?? read<string>(index.symbol)
|
|
463
|
+
const fetchedDecimals = read<bigint>(index.decimals)
|
|
464
|
+
const decimals = meta.decimals ?? (fetchedDecimals === null ? null : Number(fetchedDecimals))
|
|
465
|
+
const totalSupply = read<bigint>(index.totalSupply)
|
|
466
|
+
if (!native) {
|
|
467
|
+
setCachedTokenMeta(chainId, address, {
|
|
468
|
+
...(index.name !== undefined && name !== null ? { name } : {}),
|
|
469
|
+
...(index.symbol !== undefined && symbol !== null ? { symbol } : {}),
|
|
470
|
+
...(fetchedDecimals !== null ? { decimals: Number(fetchedDecimals) } : {}),
|
|
471
|
+
})
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const values: Record<TokenField, unknown> = {
|
|
475
|
+
name,
|
|
476
|
+
symbol,
|
|
477
|
+
decimals,
|
|
478
|
+
totalSupply: totalSupply === null ? null : totalSupply.toString(),
|
|
479
|
+
}
|
|
480
|
+
const out: Record<string, unknown> = { address, native }
|
|
481
|
+
let success = true
|
|
482
|
+
for (const field of fields) {
|
|
483
|
+
out[field] = values[field]
|
|
484
|
+
// 主币没有 totalSupply,不算失败
|
|
485
|
+
if (values[field] === null && !(native && field === 'totalSupply')) {
|
|
486
|
+
success = false
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (wanted.has('totalSupply')) {
|
|
490
|
+
out.totalSupplyFormatted = totalSupply === null || decimals === null ? null : formatAmount(totalSupply, decimals)
|
|
491
|
+
}
|
|
492
|
+
out.success = success
|
|
493
|
+
return out as TokenDetails<F>
|
|
137
494
|
})
|
|
138
|
-
return tokens.map((token) => infoByToken.get(token) ?? null)
|
|
139
495
|
}
|
|
140
496
|
|
|
141
497
|
/**
|
|
@@ -144,7 +500,8 @@ export class Provider implements ContractRunner {
|
|
|
144
500
|
*/
|
|
145
501
|
getEthBalance(address: string): BoundCall<bigint> {
|
|
146
502
|
const call: Call<bigint> = {
|
|
147
|
-
|
|
503
|
+
// 地址只用于展示:执行时合约模式会换成实际的 multicall 地址,deployless 时由合约内部处理
|
|
504
|
+
contract: { address: this.#ctx?.multicall?.address ?? MULTICALL3_ADDRESS },
|
|
148
505
|
name: 'getEthBalance',
|
|
149
506
|
inputs: ETH_BALANCE_INPUTS,
|
|
150
507
|
outputs: ETH_BALANCE_OUTPUTS,
|
|
@@ -258,7 +615,8 @@ export class Provider implements ContractRunner {
|
|
|
258
615
|
const merged: StaticCallOverrides = merge(merge({ ...shared }, call.overrides), explicit)
|
|
259
616
|
if (call.kind === 'ethBalance') {
|
|
260
617
|
try {
|
|
261
|
-
|
|
618
|
+
const { provider } = await this.#ensureReady()
|
|
619
|
+
return { success: true, data: (await provider.getBalance(call.params[0], merged.blockTag)) as T }
|
|
262
620
|
} catch (err) {
|
|
263
621
|
return { success: false, error: err instanceof Error ? err : new Error(String(err)) }
|
|
264
622
|
}
|
|
@@ -266,7 +624,8 @@ export class Provider implements ContractRunner {
|
|
|
266
624
|
let returnData: string
|
|
267
625
|
try {
|
|
268
626
|
const request = encodeCall(call, false)
|
|
269
|
-
|
|
627
|
+
const { provider } = await this.#ensureReady()
|
|
628
|
+
returnData = await provider.call({
|
|
270
629
|
to: request.target,
|
|
271
630
|
data: request.callData,
|
|
272
631
|
from: merged.from,
|
|
@@ -289,18 +648,21 @@ export class Provider implements ContractRunner {
|
|
|
289
648
|
}
|
|
290
649
|
}
|
|
291
650
|
|
|
292
|
-
/** 底层连接(多节点时是 FallbackRpc
|
|
651
|
+
/** 底层连接(多节点时是 FallbackRpc)。只传节点构造时,需在 ready() 之后读取 */
|
|
293
652
|
get rpc(): EthersLikeProvider {
|
|
653
|
+
if (!this.#ctx) {
|
|
654
|
+
throw new Error('Provider is still detecting chainId; await provider.ready() first')
|
|
655
|
+
}
|
|
294
656
|
return this.#ctx.provider
|
|
295
657
|
}
|
|
296
658
|
|
|
297
|
-
/** 当前使用的 multicall 合约(null 表示 deployless) */
|
|
659
|
+
/** 当前使用的 multicall 合约(null 表示 deployless;只传节点构造时在 ready() 之前也为 null) */
|
|
298
660
|
get multicall(): Multicall | null {
|
|
299
|
-
return this.#ctx
|
|
661
|
+
return this.#ctx?.multicall ?? null
|
|
300
662
|
}
|
|
301
663
|
|
|
302
|
-
#aggregate(requests: CallRequest[], overrides?: CallOverrides): Promise<RawResult[]> {
|
|
303
|
-
return aggregate(this.#
|
|
664
|
+
async #aggregate(requests: CallRequest[], overrides?: CallOverrides): Promise<RawResult[]> {
|
|
665
|
+
return aggregate(await this.#ensureReady(), requests, overrides)
|
|
304
666
|
}
|
|
305
667
|
}
|
|
306
668
|
|