@w3lib/solana-batch-call 0.1.0 → 0.2.1
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 +41 -0
- package/README.md +120 -18
- package/dist/address.d.ts +7 -1
- package/dist/address.d.ts.map +1 -1
- package/dist/address.js +56 -8
- package/dist/address.js.map +1 -1
- package/dist/client.d.ts +117 -23
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +756 -247
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/layout.d.ts +31 -2
- package/dist/layout.d.ts.map +1 -1
- package/dist/layout.js +68 -8
- package/dist/layout.js.map +1 -1
- package/dist/rpc.d.ts +65 -4
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +320 -42
- package/dist/rpc.js.map +1 -1
- package/dist/shortcuts.d.ts +38 -5
- package/dist/shortcuts.d.ts.map +1 -1
- package/dist/shortcuts.js +169 -12
- package/dist/shortcuts.js.map +1 -1
- package/dist/source.d.ts.map +1 -1
- package/dist/source.js +2 -4
- package/dist/source.js.map +1 -1
- package/dist/types.d.ts +54 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +13 -10
- package/src/address.ts +60 -8
- package/src/client.ts +974 -270
- package/src/index.ts +47 -3
- package/src/layout.ts +90 -8
- package/src/rpc.ts +368 -42
- package/src/shortcuts.ts +223 -16
- package/src/source.ts +2 -4
- package/src/types.ts +59 -3
package/dist/client.js
CHANGED
|
@@ -1,18 +1,86 @@
|
|
|
1
1
|
import { base64 } from '@scure/base';
|
|
2
2
|
import { getAssociatedTokenAddress, getMetadataAddress, isAddress } from './address.js';
|
|
3
3
|
import { NATIVE_MINT, SOL_DECIMALS, SYSTEM_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, clusterOfGenesis, } from './constants.js';
|
|
4
|
-
import {
|
|
5
|
-
import { HttpError, RpcError } from './rpc.js';
|
|
4
|
+
import { formatUnits, parseMetaplexMetadata, parseMint, parseTokenAccount, parseTransferFeeConfig, } from './layout.js';
|
|
5
|
+
import { AllNodesFailedError, HttpError, RpcError, isBehind } from './rpc.js';
|
|
6
6
|
import { NetworkMismatchError, resolveSource } from './source.js';
|
|
7
7
|
import { DEFAULT_TOKEN_FIELDS, } from './types.js';
|
|
8
|
+
/** 节点高度不够时的重试间隔与总时长 */
|
|
9
|
+
const BEHIND_RETRY_INTERVAL = 500;
|
|
10
|
+
const BEHIND_RETRY_TIMEOUT = 10_000;
|
|
8
11
|
const MAX_ACCOUNTS_PER_REQUEST = 100;
|
|
9
12
|
/** 同时进行的 getMultipleAccounts 请求数上限 */
|
|
10
13
|
const MAX_PARALLEL_ACCOUNT_REQUESTS = 3;
|
|
11
14
|
/** #fetchAccounts 里没能读到(节点问题)的账户 */
|
|
12
15
|
const FAILED = Symbol('failed');
|
|
13
|
-
/** 可以降级处理的错误:网络 / HTTP 错误、节点限制(限频、需要 Key
|
|
16
|
+
/** 可以降级处理的错误:网络 / HTTP 错误、节点限制(限频、需要 Key 等)、节点不在期望的网络上、所有节点都失败;其他(参数错误、程序 bug)照常抛出 */
|
|
14
17
|
function isRecoverable(err) {
|
|
15
|
-
return err instanceof HttpError || (err instanceof RpcError && err.nodeFault) || err instanceof NetworkMismatchError;
|
|
18
|
+
return err instanceof HttpError || (err instanceof RpcError && err.nodeFault) || err instanceof NetworkMismatchError || err instanceof AllNodesFailedError;
|
|
19
|
+
}
|
|
20
|
+
/** 查询带上取消:已取消时不执行;中途取消时立即 reject,查询本身继续(结果丢弃) */
|
|
21
|
+
function abortable(signal, run) {
|
|
22
|
+
if (!signal) {
|
|
23
|
+
return run();
|
|
24
|
+
}
|
|
25
|
+
if (signal.aborted) {
|
|
26
|
+
return Promise.reject(signal.reason);
|
|
27
|
+
}
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
const onAbort = () => reject(signal.reason);
|
|
30
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
31
|
+
run()
|
|
32
|
+
.then(resolve, reject)
|
|
33
|
+
.finally(() => signal.removeEventListener('abort', onAbort));
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function sleep(ms, signal) {
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
if (signal?.aborted) {
|
|
39
|
+
reject(signal.reason);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const timer = setTimeout(() => {
|
|
43
|
+
signal?.removeEventListener('abort', onAbort);
|
|
44
|
+
resolve();
|
|
45
|
+
}, ms);
|
|
46
|
+
const onAbort = () => {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
reject(signal?.reason);
|
|
49
|
+
};
|
|
50
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
const TOKEN_PROGRAMS = [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID];
|
|
54
|
+
// 用 Map:普通对象会让 'constructor' 等原型上的名字通过校验
|
|
55
|
+
const PROGRAM_ALIASES = new Map([
|
|
56
|
+
['spl', TOKEN_PROGRAM_ID],
|
|
57
|
+
['token-2022', TOKEN_2022_PROGRAM_ID],
|
|
58
|
+
[TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID],
|
|
59
|
+
[TOKEN_2022_PROGRAM_ID, TOKEN_2022_PROGRAM_ID],
|
|
60
|
+
]);
|
|
61
|
+
/**
|
|
62
|
+
* 简写 / 程序地址转成程序地址(顺序固定为 Token、Token-2022)。
|
|
63
|
+
* 不认识的值和空数组报错,避免拼错或漏选时悄悄过滤掉全部代币
|
|
64
|
+
*/
|
|
65
|
+
function resolvePrograms(tokenPrograms) {
|
|
66
|
+
if (tokenPrograms === undefined) {
|
|
67
|
+
return TOKEN_PROGRAMS;
|
|
68
|
+
}
|
|
69
|
+
if (tokenPrograms.length === 0) {
|
|
70
|
+
throw new Error(`tokenPrograms is empty (expected 'spl' and / or 'token-2022'; omit it to include both)`);
|
|
71
|
+
}
|
|
72
|
+
const wanted = new Set(tokenPrograms.map((value) => {
|
|
73
|
+
const program = PROGRAM_ALIASES.get(value);
|
|
74
|
+
if (!program) {
|
|
75
|
+
throw new Error(`Unknown token program: ${value} (expected 'spl', 'token-2022' or a token program id)`);
|
|
76
|
+
}
|
|
77
|
+
return program;
|
|
78
|
+
}));
|
|
79
|
+
return TOKEN_PROGRAMS.filter((program) => wanted.has(program));
|
|
80
|
+
}
|
|
81
|
+
/** 所属程序已知且不在允许范围内 */
|
|
82
|
+
function isExcluded(tokenProgram, allowed) {
|
|
83
|
+
return tokenProgram !== undefined && !allowed.includes(tokenProgram);
|
|
16
84
|
}
|
|
17
85
|
/** 按 mint 汇总后精度 0、数量 1 的持仓视为 NFT(ownerTokens 与 ownerNfts 共用) */
|
|
18
86
|
function isNftHolding(holding) {
|
|
@@ -31,25 +99,160 @@ const TOKEN_STANDARDS = [
|
|
|
31
99
|
const NAME_TTL = 60 * 60 * 1000;
|
|
32
100
|
const MAX_CACHED_TOKENS = 50_000;
|
|
33
101
|
const tokenMetaCache = new Map();
|
|
102
|
+
// 已知数据为空的钱包账户(系统账户或不存在):ATA 模式下和代币账户放在同一个请求里读,不必单独带 dataSlice 多发一个请求。
|
|
103
|
+
// 按 scope + 地址记,最多 1 万个,超出淘汰最早的;读到不是系统账户(如程序账户)时移除
|
|
104
|
+
const MAX_SMALL_OWNERS = 10_000;
|
|
105
|
+
const smallOwners = new Set();
|
|
106
|
+
function isSmallOwner(scope, owner) {
|
|
107
|
+
return smallOwners.has(`${scope}:${owner}`);
|
|
108
|
+
}
|
|
109
|
+
/** 根据只读 lamports 的结果判断钱包账户是否“数据为空”(dataSlice 读不到数据长度,按所属程序判断:系统账户的数据为空) */
|
|
110
|
+
function learnOwner(scope, owner, account) {
|
|
111
|
+
const key = `${scope}:${owner}`;
|
|
112
|
+
if (account === null || account.owner === SYSTEM_PROGRAM_ID) {
|
|
113
|
+
smallOwners.delete(key);
|
|
114
|
+
smallOwners.add(key);
|
|
115
|
+
if (smallOwners.size > MAX_SMALL_OWNERS) {
|
|
116
|
+
smallOwners.delete(smallOwners.values().next().value);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
smallOwners.delete(key);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
34
123
|
let clientIds = 0;
|
|
124
|
+
/** 缓存写入监听(persistTokenMetaCache 用) */
|
|
125
|
+
const cacheWriteListeners = new Set();
|
|
35
126
|
/** 测试用:清空代币信息缓存 */
|
|
36
127
|
export function resetTokenMetaCache() {
|
|
128
|
+
smallOwners.clear();
|
|
37
129
|
tokenMetaCache.clear();
|
|
38
130
|
}
|
|
131
|
+
const SHARED_SCOPES = new Set(['mainnet', 'devnet', 'testnet']);
|
|
132
|
+
/**
|
|
133
|
+
* 导出代币信息缓存(decimals / 所属程序 / name / symbol),用于持久化:刷新页面后导入,不必重查 decimals。
|
|
134
|
+
* 只导出按网络共享的条目(自定义节点且没指定 cluster 的客户端,缓存只在该客户端内,不导出)。
|
|
135
|
+
* maxEntries:只导出最近写入的这么多条
|
|
136
|
+
*/
|
|
137
|
+
export function exportTokenMetaCache(maxEntries = Number.POSITIVE_INFINITY) {
|
|
138
|
+
const entries = [];
|
|
139
|
+
for (const [key, meta] of tokenMetaCache) {
|
|
140
|
+
if (SHARED_SCOPES.has(key.slice(0, key.indexOf(':')))) {
|
|
141
|
+
const { programUnverified: _, ...exported } = meta;
|
|
142
|
+
entries.push([key, exported]);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return { version: 1, entries: entries.slice(Math.max(0, entries.length - maxEntries)) };
|
|
146
|
+
}
|
|
147
|
+
/** 导入 exportTokenMetaCache() 的结果;格式不对的条目跳过,内存里已有的条目不覆盖 */
|
|
148
|
+
export function importTokenMetaCache(snapshot) {
|
|
149
|
+
const entries = snapshot?.entries;
|
|
150
|
+
if (snapshot?.version !== 1 || !Array.isArray(entries)) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
for (const entry of entries) {
|
|
154
|
+
const meta = validMeta(entry);
|
|
155
|
+
if (meta && !tokenMetaCache.has(entry[0])) {
|
|
156
|
+
tokenMetaCache.set(entry[0], meta);
|
|
157
|
+
if (tokenMetaCache.size > MAX_CACHED_TOKENS) {
|
|
158
|
+
tokenMetaCache.delete(tokenMetaCache.keys().next().value);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function validMeta(entry) {
|
|
164
|
+
if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string') {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
const [key, raw] = entry;
|
|
168
|
+
const colon = key.indexOf(':');
|
|
169
|
+
if (!SHARED_SCOPES.has(key.slice(0, colon)) || !isAddress(key.slice(colon + 1)) || !raw || typeof raw !== 'object') {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
const meta = {};
|
|
173
|
+
if (typeof raw.decimals === 'number' && Number.isInteger(raw.decimals) && raw.decimals >= 0 && raw.decimals <= 255)
|
|
174
|
+
meta.decimals = raw.decimals;
|
|
175
|
+
if (raw.tokenProgram === TOKEN_PROGRAM_ID || raw.tokenProgram === TOKEN_2022_PROGRAM_ID) {
|
|
176
|
+
meta.tokenProgram = raw.tokenProgram;
|
|
177
|
+
meta.programUnverified = true;
|
|
178
|
+
}
|
|
179
|
+
// 写入时间只接受有限值、且不晚于现在(留 1 分钟时钟误差):未来的时间会让 name / symbol 永不过期,截到现在
|
|
180
|
+
if (typeof raw.namesAt === 'number' &&
|
|
181
|
+
Number.isFinite(raw.namesAt) &&
|
|
182
|
+
(typeof raw.name === 'string' || raw.name === null) &&
|
|
183
|
+
(typeof raw.symbol === 'string' || raw.symbol === null)) {
|
|
184
|
+
meta.name = raw.name;
|
|
185
|
+
meta.symbol = raw.symbol;
|
|
186
|
+
meta.namesAt = Math.min(raw.namesAt, Date.now());
|
|
187
|
+
}
|
|
188
|
+
return Object.keys(meta).length ? meta : null;
|
|
189
|
+
}
|
|
39
190
|
/**
|
|
40
|
-
*
|
|
191
|
+
* 把代币信息缓存持久化到同步的键值存储(如 localStorage):调用时读入,之后缓存有写入就防抖(约 1 秒)整体写回。
|
|
192
|
+
* 返回停止函数(会立即写回还没写的变化)。读到格式不对的数据会丢弃;写入失败(如存储已满)忽略。
|
|
41
193
|
*
|
|
42
194
|
* ```ts
|
|
43
|
-
*
|
|
44
|
-
* const sol = new SolanaClient('https://my-rpc.example') // 自己的节点
|
|
45
|
-
* const sol = new SolanaClient([connection, 'https://backup…']) // web3.js Connection + 备用节点
|
|
46
|
-
*
|
|
47
|
-
* await sol.balances(owner, [NATIVE_MINT, USDC])
|
|
48
|
-
* await sol.tokens([USDC, PYUSD], { fields: ['name', 'symbol', 'decimals', 'supply'] })
|
|
195
|
+
* persistTokenMetaCache(localStorage) // 刷新页面后 decimals 不必重查
|
|
49
196
|
* ```
|
|
50
|
-
*
|
|
51
|
-
* 同一 tick 内发起的 RPC 调用会合并成一个 JSON-RPC 批量请求;账户读取按 100 个一组用 getMultipleAccounts。
|
|
52
197
|
*/
|
|
198
|
+
export function persistTokenMetaCache(store, options = {}) {
|
|
199
|
+
const key = options.key ?? 'w3lib:solana-token-meta';
|
|
200
|
+
const maxEntries = options.maxEntries ?? 5000;
|
|
201
|
+
try {
|
|
202
|
+
const raw = store.getItem(key);
|
|
203
|
+
if (raw) {
|
|
204
|
+
importTokenMetaCache(JSON.parse(raw));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
// 格式不对:丢弃
|
|
209
|
+
}
|
|
210
|
+
let timer = null;
|
|
211
|
+
const write = () => {
|
|
212
|
+
timer = null;
|
|
213
|
+
try {
|
|
214
|
+
store.setItem(key, JSON.stringify(exportTokenMetaCache(maxEntries)));
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// 存储已满等:忽略
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const onWrite = () => {
|
|
221
|
+
if (!timer) {
|
|
222
|
+
timer = setTimeout(write, 1000);
|
|
223
|
+
timer.unref?.();
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
cacheWriteListeners.add(onWrite);
|
|
227
|
+
return () => {
|
|
228
|
+
cacheWriteListeners.delete(onWrite);
|
|
229
|
+
if (timer) {
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
write();
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/** jsonParsed 结果里的一个代币账户:节点解析好的直接取;退回 base64 的自己解析(这时没有 decimals,要从 mint 账户补) */
|
|
236
|
+
function readTokenEntry(entry) {
|
|
237
|
+
const data = entry.account?.data;
|
|
238
|
+
if (data && !Array.isArray(data) && typeof data === 'object') {
|
|
239
|
+
const info = data.parsed?.info;
|
|
240
|
+
if (info?.mint && info.tokenAmount?.decimals !== undefined) {
|
|
241
|
+
return { mint: info.mint, amount: BigInt(info.tokenAmount.amount ?? '0'), decimals: info.tokenAmount.decimals };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const encoded = Array.isArray(data) ? (data[1] === 'base64' ? data[0] : undefined) : typeof data === 'string' ? data : undefined;
|
|
245
|
+
if (encoded === undefined) {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
try {
|
|
249
|
+
const parsed = parseTokenAccount(base64.decode(encoded));
|
|
250
|
+
return { mint: parsed.mint, amount: parsed.amount, decimals: undefined };
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
53
256
|
export class SolanaClient {
|
|
54
257
|
transport;
|
|
55
258
|
#genesis;
|
|
@@ -72,171 +275,337 @@ export class SolanaClient {
|
|
|
72
275
|
return this.#cluster ?? clusterOfGenesis(await this.#genesis());
|
|
73
276
|
}
|
|
74
277
|
/** 直接发 JSON-RPC 调用(同样参与自动合并与故障切换) */
|
|
75
|
-
request(method, params) {
|
|
76
|
-
return this.transport.request(method, params);
|
|
278
|
+
request(method, params, options = {}) {
|
|
279
|
+
return abortable(options.signal, () => this.transport.request(method, params));
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* 发一个读账户类的请求:params 最后一项是配置对象,传了 minContextSlot 时带上;
|
|
283
|
+
* 节点高度不够(所有节点都落后)时每 500ms 重试,最多约 10 秒;记录返回的 context.slot(取最小值)
|
|
284
|
+
*/
|
|
285
|
+
async #call(ctx, method, params) {
|
|
286
|
+
const last = params[params.length - 1];
|
|
287
|
+
const sent = ctx.minContextSlot === undefined ? params : [...params.slice(0, -1), { ...last, minContextSlot: ctx.minContextSlot }];
|
|
288
|
+
const started = Date.now();
|
|
289
|
+
for (;;) {
|
|
290
|
+
try {
|
|
291
|
+
const res = await this.transport.request(method, sent);
|
|
292
|
+
const slot = res?.context?.slot;
|
|
293
|
+
if (typeof slot === 'number') {
|
|
294
|
+
ctx.slot = ctx.slot === undefined ? slot : Math.min(ctx.slot, slot);
|
|
295
|
+
}
|
|
296
|
+
return res;
|
|
297
|
+
}
|
|
298
|
+
catch (err) {
|
|
299
|
+
if (ctx.minContextSlot === undefined || !isBehind(err) || Date.now() - started + BEHIND_RETRY_INTERVAL > BEHIND_RETRY_TIMEOUT) {
|
|
300
|
+
throw err;
|
|
301
|
+
}
|
|
302
|
+
await sleep(BEHIND_RETRY_INTERVAL, ctx.signal);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/** 结果项带上 slot(传了 withSlot / minContextSlot,且这次查询发了请求时) */
|
|
307
|
+
#attachSlot(items, ctx, options) {
|
|
308
|
+
if ((!options.withSlot && options.minContextSlot === undefined) || ctx.slot === undefined) {
|
|
309
|
+
return items;
|
|
310
|
+
}
|
|
311
|
+
const slot = ctx.slot;
|
|
312
|
+
return items.map((item) => ({ ...item, slot }));
|
|
77
313
|
}
|
|
78
314
|
/**
|
|
79
315
|
* 批量读取账户(getMultipleAccounts,按 100 个一组,去重),结果与 addresses 一一对应。
|
|
80
316
|
* 账户不存在或地址非法时为 null。
|
|
81
317
|
*/
|
|
82
|
-
|
|
83
|
-
|
|
318
|
+
accounts(addresses, options = {}) {
|
|
319
|
+
return abortable(options.signal, () => this.#accounts(addresses, { signal: options.signal, minContextSlot: options.minContextSlot }));
|
|
320
|
+
}
|
|
321
|
+
async #accounts(addresses, ctx) {
|
|
322
|
+
const fetched = await this.#fetchAccounts(addresses, false, ctx);
|
|
84
323
|
return addresses.map((address) => fetched.get(address) ?? null);
|
|
85
324
|
}
|
|
86
325
|
/**
|
|
87
|
-
* getMultipleAccounts
|
|
88
|
-
*
|
|
326
|
+
* 只读 lamports(主币余额):getMultipleAccounts 带 dataSlice { offset: 0, length: 0 },不读回账户数据——
|
|
327
|
+
* 钱包可能是数据很大的程序账户(上百 KB),整份读回会拖慢甚至超时。结果与 addresses 一一对应,账户不存在或地址非法时为 null
|
|
89
328
|
*/
|
|
90
|
-
async #
|
|
91
|
-
const
|
|
329
|
+
async #lamports(addresses, ctx) {
|
|
330
|
+
const [fetched] = await this.#fetchGroups([{ addresses, lamportsOnly: true }], false, ctx);
|
|
331
|
+
return addresses.map((address) => fetched?.get(address)?.lamports ?? null);
|
|
332
|
+
}
|
|
333
|
+
/** getMultipleAccounts(读账户数据):见 #fetchGroups */
|
|
334
|
+
async #fetchAccounts(addresses, tolerant, ctx) {
|
|
335
|
+
const [fetched] = await this.#fetchGroups([{ addresses, lamportsOnly: false }], tolerant, ctx);
|
|
336
|
+
return fetched;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* getMultipleAccounts:每组去重、按 100 个一组拆分,所有组的请求一起排队,最多同时 3 个(避免大批量时触发节点限频)。
|
|
340
|
+
* lamportsOnly 的组带 dataSlice(长度 0,对同一请求里的所有账户生效,所以只要 lamports 的账户要单独成组)。
|
|
341
|
+
* tolerant 为 true 时,某个请求因节点问题(网络、限频等)失败不抛错:该请求的账户标记为 FAILED,并且不再发后面的请求(节点已经在限频了);
|
|
342
|
+
* 否则第一个错误抛出,后面的请求也不再发。结果按组返回
|
|
343
|
+
*/
|
|
344
|
+
async #fetchGroups(groups, tolerant, ctx) {
|
|
92
345
|
const chunks = [];
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
346
|
+
groups.forEach(({ addresses, lamportsOnly }, group) => {
|
|
347
|
+
const unique = [...new Set(addresses.filter((a) => isAddress(a)))];
|
|
348
|
+
for (let i = 0; i < unique.length; i += MAX_ACCOUNTS_PER_REQUEST) {
|
|
349
|
+
chunks.push({ group, addresses: unique.slice(i, i + MAX_ACCOUNTS_PER_REQUEST), lamportsOnly });
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
const results = groups.map(() => new Map());
|
|
97
353
|
let aborted = false;
|
|
98
354
|
for (let i = 0; i < chunks.length; i += MAX_PARALLEL_ACCOUNT_REQUESTS) {
|
|
99
355
|
const wave = chunks.slice(i, i + MAX_PARALLEL_ACCOUNT_REQUESTS);
|
|
356
|
+
// 已取消的查询不再发后面的请求
|
|
357
|
+
if (ctx.signal?.aborted) {
|
|
358
|
+
throw ctx.signal.reason;
|
|
359
|
+
}
|
|
100
360
|
if (aborted) {
|
|
101
|
-
wave.
|
|
361
|
+
wave.forEach((chunk) => chunk.addresses.forEach((address) => results[chunk.group]?.set(address, FAILED)));
|
|
102
362
|
continue;
|
|
103
363
|
}
|
|
104
|
-
|
|
364
|
+
// 同一批里的请求同时发出(合并成一个 JSON-RPC 批量请求);一个失败时等这一批都结束再抛,后面的批次不再发
|
|
365
|
+
const settled = await Promise.allSettled(wave.map(async (chunk) => {
|
|
366
|
+
const result = results[chunk.group];
|
|
105
367
|
try {
|
|
106
|
-
const res = await this
|
|
107
|
-
chunk,
|
|
108
|
-
{ encoding: 'base64', commitment: this.#commitment },
|
|
368
|
+
const res = await this.#call(ctx, 'getMultipleAccounts', [
|
|
369
|
+
chunk.addresses,
|
|
370
|
+
{ encoding: 'base64', commitment: this.#commitment, ...(chunk.lamportsOnly ? { dataSlice: { offset: 0, length: 0 } } : {}) },
|
|
109
371
|
]);
|
|
110
|
-
chunk.forEach((address, j) => result.set(address, toAccountInfo(address, res?.value?.[j] ?? null)));
|
|
372
|
+
chunk.addresses.forEach((address, j) => result.set(address, toAccountInfo(address, res?.value?.[j] ?? null)));
|
|
111
373
|
}
|
|
112
374
|
catch (err) {
|
|
113
375
|
if (!tolerant || !isRecoverable(err)) {
|
|
114
376
|
throw err;
|
|
115
377
|
}
|
|
116
378
|
aborted = true;
|
|
117
|
-
chunk.forEach((address) => result.set(address, FAILED));
|
|
379
|
+
chunk.addresses.forEach((address) => result.set(address, FAILED));
|
|
118
380
|
}
|
|
119
381
|
}));
|
|
382
|
+
const failed = settled.find((r) => r.status === 'rejected');
|
|
383
|
+
if (failed) {
|
|
384
|
+
throw failed.reason;
|
|
385
|
+
}
|
|
120
386
|
}
|
|
121
|
-
return
|
|
387
|
+
return results;
|
|
122
388
|
}
|
|
123
|
-
/** 批量查多个地址的 SOL
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
389
|
+
/** 批量查多个地址的 SOL 余额(getMultipleAccounts 只读 lamports、不读回账户数据;账户不存在视为 0) */
|
|
390
|
+
solBalances(addresses, options = {}) {
|
|
391
|
+
return abortable(options.signal, async () => {
|
|
392
|
+
const ctx = this.#context(options);
|
|
393
|
+
const balances = await this.#lamports(addresses, ctx);
|
|
394
|
+
const list = addresses.map((address, i) => {
|
|
395
|
+
if (!isAddress(address)) {
|
|
396
|
+
return { address, balance: '0', formatted: '0', success: false, error: 'invalid-address' };
|
|
397
|
+
}
|
|
398
|
+
const lamports = balances[i] ?? 0n;
|
|
399
|
+
return { address, balance: lamports.toString(), formatted: formatUnits(lamports, SOL_DECIMALS), success: true };
|
|
400
|
+
});
|
|
401
|
+
return this.#attachSlot(list, ctx, options);
|
|
132
402
|
});
|
|
133
403
|
}
|
|
404
|
+
#context(options) {
|
|
405
|
+
return { signal: options.signal, minContextSlot: options.minContextSlot };
|
|
406
|
+
}
|
|
134
407
|
/**
|
|
135
408
|
* 批量查余额(主币 SOL + SPL Token + Token-2022),返回原始余额、decimals 和换算后的数值。
|
|
136
409
|
*
|
|
137
|
-
* - 传 mints:本地推导 ATA
|
|
410
|
+
* - 传 mints:本地推导 ATA,与 mint 账户一起用 getMultipleAccounts 读完,免费节点也能用;主币只读 lamports(dataSlice),另成一组同时发出
|
|
411
|
+
* - 传 mints 且 accounts: 'all':每个代币按 mint 过滤查 getTokenAccountsByOwner,统计全部代币账户(含非 ATA)
|
|
138
412
|
* - 不传 mints(或 scan: true):用 getTokenAccountsByOwner 扫描全部代币账户,返回所有余额大于 0 的代币
|
|
413
|
+
* - 失败项(success: false)带 error:invalid-address(mint 地址非法)/ not-found(mint 不存在)/ not-token(不是代币 mint)
|
|
414
|
+
* - tokenPrograms:只返回这些类型的代币,如 ['spl'] 不含 Token-2022(传了 mints 时,结果里去掉不符合的代币)
|
|
415
|
+
* - minContextSlot / withSlot:要求节点高度、返回读取时的 slot,见 SlotOptions
|
|
139
416
|
*/
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
417
|
+
balances(owner, mints, options = {}) {
|
|
418
|
+
return abortable(options.signal, async () => {
|
|
419
|
+
if (!isAddress(owner)) {
|
|
420
|
+
throw new Error(`Invalid owner address: ${owner}`);
|
|
421
|
+
}
|
|
422
|
+
const ctx = this.#context(options);
|
|
423
|
+
const list = await this.#balances(ctx, owner, mints, options, resolvePrograms(options.tokenPrograms));
|
|
424
|
+
return this.#attachSlot(list, ctx, options);
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
#balances(ctx, owner, mints, options, programs) {
|
|
428
|
+
const withSymbol = options.symbol ?? false;
|
|
144
429
|
if (mints === undefined || options.scan) {
|
|
145
|
-
return this.#scanBalances(owner, mints,
|
|
430
|
+
return this.#scanBalances(ctx, owner, mints, withSymbol, programs);
|
|
431
|
+
}
|
|
432
|
+
if (options.accounts === 'all') {
|
|
433
|
+
return this.#mintAccountBalances(ctx, owner, mints, withSymbol, programs);
|
|
146
434
|
}
|
|
147
|
-
return this.#ataBalances(owner, mints,
|
|
435
|
+
return this.#ataBalances(ctx, [{ owner, mints }], withSymbol, programs).then((lists) => lists[0]);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* 多个钱包一次查(如多钱包的持仓列表),结果与 queries 一一对应。
|
|
439
|
+
* ATA 模式(默认)下所有钱包的账户合并成一次(按 100 个一组的)getMultipleAccounts;
|
|
440
|
+
* scan / accounts: 'all' 时每个钱包各自查询(同一 tick 发出,合并成批量请求)。其他选项与 balances() 相同;
|
|
441
|
+
* withSlot 时所有钱包的结果带同一个 slot(整次查询的最小值)。任一 owner 非法时报错
|
|
442
|
+
*
|
|
443
|
+
* ```ts
|
|
444
|
+
* await sol.multiBalances([{ owner: a, mints: [NATIVE_MINT, USDC] }, { owner: b, mints: [USDC] }])
|
|
445
|
+
* ```
|
|
446
|
+
*/
|
|
447
|
+
multiBalances(queries, options = {}) {
|
|
448
|
+
return abortable(options.signal, async () => {
|
|
449
|
+
for (const { owner } of queries) {
|
|
450
|
+
if (!isAddress(owner)) {
|
|
451
|
+
throw new Error(`Invalid owner address: ${owner}`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
const programs = resolvePrograms(options.tokenPrograms);
|
|
455
|
+
const ctx = this.#context(options);
|
|
456
|
+
const lists = options.scan || options.accounts === 'all'
|
|
457
|
+
? await Promise.all(queries.map(({ owner, mints }) => this.#balances(ctx, owner, mints, options, programs)))
|
|
458
|
+
: await this.#ataBalances(ctx, queries, options.symbol ?? false, programs);
|
|
459
|
+
return lists.map((list) => this.#attachSlot(list, ctx, options));
|
|
460
|
+
});
|
|
148
461
|
}
|
|
149
|
-
|
|
462
|
+
/** ATA 模式:所有钱包的 主币账户 / mint / 元数据 / ATA 一起读,结果按钱包分组 */
|
|
463
|
+
async #ataBalances(ctx, queries, withSymbol, allowed) {
|
|
150
464
|
const scope = this.#scope();
|
|
465
|
+
// 要数据的账户(mint、元数据、ATA)一组;钱包账户只要 lamports:已知是普通钱包(系统账户 / 不存在,数据为空)的
|
|
466
|
+
// 放进同一组(一个请求、同一个快照),其余(可能是数据很大的程序账户)单独一组带 dataSlice——同时发出,合并在同一个 JSON-RPC 批量请求里
|
|
151
467
|
const addresses = [];
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
468
|
+
const owners = [];
|
|
469
|
+
const plans = queries.map(({ owner, mints }) => mints.map((mint) => this.#ataPlan(scope, owner, mint, withSymbol, allowed, addresses, owners)));
|
|
470
|
+
const [dataMap, ownerMap] = await this.#fetchGroups([
|
|
471
|
+
{ addresses, lamportsOnly: false },
|
|
472
|
+
{ addresses: owners, lamportsOnly: true },
|
|
473
|
+
], false, ctx);
|
|
474
|
+
// 记下钱包账户是否数据为空:单独读的按结果学习;已放进代币那组的,读到不再是系统账户(如被分配给程序)时移除,下次单独读
|
|
475
|
+
for (const owner of new Set(queries.map((q) => q.owner))) {
|
|
476
|
+
// null(账户不存在)也是结果,不能用 ?? 落到另一组
|
|
477
|
+
const account = ownerMap?.has(owner) ? ownerMap.get(owner) : dataMap?.get(owner);
|
|
478
|
+
if (account !== undefined && account !== FAILED) {
|
|
479
|
+
learnOwner(scope, owner, account);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const accounts = addresses.map((address) => dataMap?.get(address) ?? null);
|
|
483
|
+
const lamportsOf = (owner) => (ownerMap?.has(owner) ? ownerMap.get(owner) : dataMap?.get(owner))?.lamports ?? 0n;
|
|
484
|
+
return plans.map((plan) => plan.flatMap((item) => this.#ataResult(scope, item, accounts, lamportsOf, withSymbol, allowed)));
|
|
485
|
+
}
|
|
486
|
+
#ataPlan(scope, owner, mint, withSymbol, allowed, addresses, owners) {
|
|
487
|
+
if (this.#nativeMints.has(mint)) {
|
|
488
|
+
;
|
|
489
|
+
(isSmallOwner(scope, owner) ? addresses : owners).push(owner);
|
|
490
|
+
return { kind: 'native', mint, owner };
|
|
491
|
+
}
|
|
492
|
+
if (!isAddress(mint)) {
|
|
493
|
+
return { kind: 'invalid', mint };
|
|
494
|
+
}
|
|
495
|
+
const meta = getMeta(scope, mint);
|
|
496
|
+
// 导入的缓存里的所属程序没确认过:按未知处理(记错时不会让余额恒为 0)
|
|
497
|
+
const program = meta.programUnverified ? undefined : meta.tokenProgram;
|
|
498
|
+
if (isExcluded(program, allowed)) {
|
|
499
|
+
return { kind: 'excluded', mint };
|
|
500
|
+
}
|
|
501
|
+
const needMint = meta.decimals === undefined || program === undefined || (withSymbol && meta.symbol === undefined);
|
|
502
|
+
// 所属程序未知时只推导允许的程序的 ATA,读到 mint 账户后再确认
|
|
503
|
+
const programs = program ? [program] : allowed;
|
|
504
|
+
return {
|
|
505
|
+
kind: 'token',
|
|
506
|
+
mint,
|
|
507
|
+
mintIndex: needMint ? addresses.push(mint) - 1 : -1,
|
|
508
|
+
metadataIndex: withSymbol && meta.symbol === undefined ? addresses.push(getMetadataAddress(mint)) - 1 : -1,
|
|
509
|
+
atas: programs.map((program) => ({ program, index: addresses.push(getAssociatedTokenAddress(owner, mint, program)) - 1 })),
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
#ataResult(scope, item, accounts, lamportsOf, withSymbol, allowed) {
|
|
513
|
+
if (item.kind === 'native') {
|
|
514
|
+
const lamports = lamportsOf(item.owner);
|
|
515
|
+
return [
|
|
516
|
+
withSymbolField({ token: item.mint, native: true, balance: lamports.toString(), decimals: SOL_DECIMALS, formatted: formatUnits(lamports, SOL_DECIMALS), tokenProgram: null, success: true }, withSymbol, 'SOL'),
|
|
517
|
+
];
|
|
518
|
+
}
|
|
519
|
+
if (item.kind === 'excluded') {
|
|
520
|
+
return [];
|
|
521
|
+
}
|
|
522
|
+
if (item.kind === 'invalid') {
|
|
523
|
+
return [failedBalance(item.mint, 'invalid-address', null, withSymbol, null)];
|
|
524
|
+
}
|
|
525
|
+
const mintAccount = item.mintIndex === -1 ? null : (accounts[item.mintIndex] ?? null);
|
|
526
|
+
const meta = this.#learn(scope, item.mint, mintAccount, item.metadataIndex === -1 ? null : (accounts[item.metadataIndex] ?? null), item.metadataIndex !== -1 && item.mintIndex !== -1);
|
|
527
|
+
// 代币账户由哪个程序持有就是哪个;mint 账户的 owner 也能确定程序。
|
|
528
|
+
// 所属程序未知时推导了两个程序的 ATA,但一个 mint 只属于一个程序,另一个程序下不可能有这个 mint 的代币账户:找到就结束
|
|
529
|
+
let amount = 0n;
|
|
530
|
+
for (const ata of item.atas) {
|
|
531
|
+
const account = accounts[ata.index];
|
|
532
|
+
if (!account || account.owner !== ata.program) {
|
|
533
|
+
continue;
|
|
155
534
|
}
|
|
156
|
-
|
|
157
|
-
|
|
535
|
+
try {
|
|
536
|
+
amount = parseTokenAccount(account.data).amount;
|
|
158
537
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const programs = meta.tokenProgram ? [meta.tokenProgram] : [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID];
|
|
162
|
-
return {
|
|
163
|
-
mint,
|
|
164
|
-
native: false,
|
|
165
|
-
meta,
|
|
166
|
-
mintIndex: needMint ? addresses.push(mint) - 1 : -1,
|
|
167
|
-
metadataIndex: withSymbol && meta.symbol === undefined ? addresses.push(getMetadataAddress(mint)) - 1 : -1,
|
|
168
|
-
atas: programs.map((program) => ({ program, index: addresses.push(getAssociatedTokenAddress(owner, mint, program)) - 1 })),
|
|
169
|
-
};
|
|
170
|
-
});
|
|
171
|
-
const accounts = await this.accounts(addresses);
|
|
172
|
-
return plan.map((item) => {
|
|
173
|
-
if (item.native) {
|
|
174
|
-
const lamports = accounts[item.owner]?.lamports ?? 0n;
|
|
175
|
-
return withSymbolField({ token: item.mint, native: true, balance: lamports.toString(), decimals: SOL_DECIMALS, formatted: formatAmount(lamports, SOL_DECIMALS), tokenProgram: null, success: true }, withSymbol, 'SOL');
|
|
176
|
-
}
|
|
177
|
-
if ('invalid' in item) {
|
|
178
|
-
return withSymbolField({ token: item.mint, native: false, balance: '0', decimals: 0, formatted: '0', tokenProgram: null, success: false }, withSymbol, null);
|
|
179
|
-
}
|
|
180
|
-
const mintAccount = item.mintIndex === -1 ? null : (accounts[item.mintIndex] ?? null);
|
|
181
|
-
const meta = this.#learn(scope, item.mint, mintAccount, item.metadataIndex === -1 ? null : (accounts[item.metadataIndex] ?? null), item.metadataIndex !== -1 && item.mintIndex !== -1);
|
|
182
|
-
// 代币账户由哪个程序持有就是哪个;mint 账户的 owner 也能确定程序
|
|
183
|
-
let amount = 0n;
|
|
184
|
-
for (const ata of item.atas) {
|
|
185
|
-
const account = accounts[ata.index];
|
|
186
|
-
if (account && account.owner === ata.program) {
|
|
187
|
-
try {
|
|
188
|
-
amount = parseTokenAccount(account.data).amount;
|
|
189
|
-
if (meta.tokenProgram === undefined) {
|
|
190
|
-
setMeta(scope, item.mint, { tokenProgram: ata.program });
|
|
191
|
-
meta.tokenProgram = ata.program;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
catch {
|
|
195
|
-
// 不是代币账户
|
|
196
|
-
}
|
|
197
|
-
}
|
|
538
|
+
catch {
|
|
539
|
+
continue; // 不是代币账户
|
|
198
540
|
}
|
|
199
|
-
if (meta.
|
|
200
|
-
|
|
541
|
+
if (meta.tokenProgram === undefined) {
|
|
542
|
+
setMeta(scope, item.mint, { tokenProgram: ata.program });
|
|
543
|
+
meta.tokenProgram = ata.program;
|
|
201
544
|
}
|
|
202
|
-
|
|
545
|
+
break;
|
|
546
|
+
}
|
|
547
|
+
// 读到 mint 账户后才知道是不允许的程序
|
|
548
|
+
if (isExcluded(meta.tokenProgram, allowed)) {
|
|
549
|
+
return [];
|
|
550
|
+
}
|
|
551
|
+
if (meta.decimals === undefined) {
|
|
552
|
+
// decimals 未知时一定读了 mint 账户:不存在 / 存在但不是 mint
|
|
553
|
+
return [failedBalance(item.mint, mintAccount ? 'not-token' : 'not-found', meta.tokenProgram ?? null, withSymbol, meta.symbol ?? null)];
|
|
554
|
+
}
|
|
555
|
+
return [
|
|
556
|
+
withSymbolField({
|
|
203
557
|
token: item.mint,
|
|
204
558
|
native: false,
|
|
205
559
|
balance: amount.toString(),
|
|
206
560
|
decimals: meta.decimals,
|
|
207
|
-
formatted:
|
|
561
|
+
formatted: formatUnits(amount, meta.decimals),
|
|
208
562
|
tokenProgram: meta.tokenProgram ?? null,
|
|
209
563
|
success: true,
|
|
210
|
-
}, withSymbol, meta.symbol ?? null)
|
|
211
|
-
|
|
564
|
+
}, withSymbol, meta.symbol ?? null),
|
|
565
|
+
];
|
|
212
566
|
}
|
|
213
|
-
/** 扫描持有人的 SOL
|
|
214
|
-
async #scanHoldings(owner) {
|
|
567
|
+
/** 扫描持有人的 SOL 余额和全部代币账户(默认 Token + Token-2022,只请求 programs 里的程序),同一代币的多个账户合计 */
|
|
568
|
+
async #scanHoldings(ctx, owner, programs = TOKEN_PROGRAMS, withSymbol = false) {
|
|
215
569
|
const scope = this.#scope();
|
|
216
|
-
const [lamports, ...
|
|
217
|
-
this
|
|
218
|
-
...
|
|
219
|
-
owner,
|
|
220
|
-
{ programId },
|
|
221
|
-
{ encoding: 'jsonParsed', commitment: this.#commitment },
|
|
222
|
-
])),
|
|
570
|
+
const [lamports, ...results] = await Promise.all([
|
|
571
|
+
this.#call(ctx, 'getBalance', [owner, { commitment: this.#commitment }]),
|
|
572
|
+
...programs.map((programId) => this.#call(ctx, 'getTokenAccountsByOwner', [owner, { programId }, { encoding: 'jsonParsed', commitment: this.#commitment }])),
|
|
223
573
|
]);
|
|
574
|
+
const entries = programs.flatMap((program, i) => (results[i]?.value ?? []).map((entry) => ({ program, entry })));
|
|
575
|
+
const held = await this.#collectHoldings(ctx, scope, entries, withSymbol);
|
|
576
|
+
return { sol: BigInt(lamports.value), held };
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* 把 getTokenAccountsByOwner(jsonParsed)的结果按 mint 汇总。节点解析不了、退回 base64 的账户自己解析,
|
|
580
|
+
* decimals 读 mint 账户补上(不丢弃,也不会把余额算成 0);mint 读不到 decimals 时才跳过
|
|
581
|
+
*/
|
|
582
|
+
async #collectHoldings(ctx, scope, entries, withSymbol = false) {
|
|
583
|
+
const read = entries.flatMap(({ program, entry }) => {
|
|
584
|
+
const token = readTokenEntry(entry);
|
|
585
|
+
return token ? [{ ...token, program: entry.account?.owner || program }] : [];
|
|
586
|
+
});
|
|
587
|
+
read.forEach(({ mint, decimals, program }) => decimals !== undefined && program !== undefined && setMeta(scope, mint, { decimals, tokenProgram: program }));
|
|
588
|
+
// 缺 decimals 或所属程序(节点没给账户 owner)的读 mint 账户补上;需要 symbol 时一起读,后面不必再读一遍
|
|
589
|
+
const unknown = [
|
|
590
|
+
...new Set(read.filter((t) => getMeta(scope, t.mint).decimals === undefined || (t.program === undefined && getMeta(scope, t.mint).tokenProgram === undefined)).map((t) => t.mint)),
|
|
591
|
+
];
|
|
592
|
+
if (unknown.length) {
|
|
593
|
+
// 补读 mint 不受 minContextSlot 约束、不计入扫描的 slot(decimals / 所属程序不会因为刚成交而变化);
|
|
594
|
+
// 节点问题时不让整次扫描失败,读不到的代币跳过
|
|
595
|
+
await this.#loadMeta({ signal: ctx.signal }, scope, unknown, withSymbol, true);
|
|
596
|
+
}
|
|
224
597
|
const held = new Map();
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
continue;
|
|
232
|
-
}
|
|
233
|
-
const prev = held.get(mint);
|
|
234
|
-
const amount = BigInt(info?.tokenAmount?.amount ?? '0');
|
|
235
|
-
held.set(mint, { amount: (prev?.amount ?? 0n) + amount, decimals, program, accounts: (prev?.accounts ?? 0) + 1 });
|
|
236
|
-
setMeta(scope, mint, { decimals, tokenProgram: program });
|
|
598
|
+
for (const { mint, amount, program: entryProgram } of read) {
|
|
599
|
+
const meta = getMeta(scope, mint);
|
|
600
|
+
const decimals = meta.decimals;
|
|
601
|
+
const program = entryProgram ?? (meta.programUnverified ? undefined : meta.tokenProgram);
|
|
602
|
+
if (decimals === undefined || program === undefined) {
|
|
603
|
+
continue;
|
|
237
604
|
}
|
|
238
|
-
|
|
239
|
-
|
|
605
|
+
const prev = held.get(mint);
|
|
606
|
+
held.set(mint, { amount: (prev?.amount ?? 0n) + amount, decimals, program, accounts: (prev?.accounts ?? 0) + 1 });
|
|
607
|
+
}
|
|
608
|
+
return held;
|
|
240
609
|
}
|
|
241
610
|
/**
|
|
242
611
|
* 列出持有人拥有的全部代币(SOL 在第一位),带 name / symbol,适合做资产列表。
|
|
@@ -245,66 +614,136 @@ export class SolanaClient {
|
|
|
245
614
|
* - 默认不含 NFT(精度 0 且数量 1)和余额为 0 的代币账户(如已清空的 ATA),可用 includeNfts / includeZero 打开
|
|
246
615
|
* - accounts 是该代币的代币账户数量;大于 1 时余额为所有账户的合计
|
|
247
616
|
* - 顺序:SOL,然后 SPL Token 的代币,再然后 Token-2022 的代币(各自按节点返回的顺序;没有价格信息,不按价值排序)
|
|
617
|
+
* - tokenPrograms: ['spl'] 时不含 Token-2022 代币
|
|
618
|
+
* - withSlot 的 slot 只算余额扫描(元数据读取不计入)
|
|
248
619
|
*/
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
const { metadata = true, includeNative = true, includeZero = false, includeNfts = false } = options;
|
|
254
|
-
const scope = this.#scope();
|
|
255
|
-
const { sol, held } = await this.#scanHoldings(owner);
|
|
256
|
-
// Wrapped SOL 是独立的代币账户(需要 unwrap 才是 SOL),资产列表里单独列出(native: false)
|
|
257
|
-
const tokens = [...held].filter(([, h]) => (includeZero || h.amount > 0n) && (includeNfts || !isNftHolding(h)));
|
|
258
|
-
const failed = metadata ? await this.#loadMeta(scope, tokens.map(([mint]) => mint), true, true) : new Set();
|
|
259
|
-
const list = tokens.map(([mint, h]) => {
|
|
260
|
-
const item = {
|
|
261
|
-
token: mint,
|
|
262
|
-
native: false,
|
|
263
|
-
balance: h.amount.toString(),
|
|
264
|
-
decimals: h.decimals,
|
|
265
|
-
formatted: formatAmount(h.amount, h.decimals),
|
|
266
|
-
tokenProgram: h.program,
|
|
267
|
-
accounts: h.accounts,
|
|
268
|
-
success: true,
|
|
269
|
-
};
|
|
270
|
-
if (!metadata) {
|
|
271
|
-
return item;
|
|
620
|
+
ownerTokens(owner, options = {}) {
|
|
621
|
+
return abortable(options.signal, async () => {
|
|
622
|
+
if (!isAddress(owner)) {
|
|
623
|
+
throw new Error(`Invalid owner address: ${owner}`);
|
|
272
624
|
}
|
|
273
|
-
const
|
|
274
|
-
const
|
|
275
|
-
|
|
625
|
+
const { metadata = true, includeNative = true, includeZero = false, includeNfts = false } = options;
|
|
626
|
+
const scope = this.#scope();
|
|
627
|
+
const ctx = this.#context(options);
|
|
628
|
+
const { sol, held } = await this.#scanHoldings(ctx, owner, resolvePrograms(options.tokenPrograms), metadata);
|
|
629
|
+
const scanSlot = ctx.slot;
|
|
630
|
+
// Wrapped SOL 是独立的代币账户(需要 unwrap 才是 SOL),资产列表里单独列出(native: false)
|
|
631
|
+
const tokens = [...held].filter(([, h]) => (includeZero || h.amount > 0n) && (includeNfts || !isNftHolding(h)));
|
|
632
|
+
// 元数据不受 minContextSlot 约束(不会因为刚成交而变化)
|
|
633
|
+
const failures = metadata ? await this.#loadMeta({ signal: options.signal }, scope, tokens.map(([mint]) => mint), true, true) : new Map();
|
|
634
|
+
const list = tokens.map(([mint, h]) => {
|
|
635
|
+
const item = {
|
|
636
|
+
token: mint,
|
|
637
|
+
native: false,
|
|
638
|
+
balance: h.amount.toString(),
|
|
639
|
+
decimals: h.decimals,
|
|
640
|
+
formatted: formatUnits(h.amount, h.decimals),
|
|
641
|
+
tokenProgram: h.program,
|
|
642
|
+
accounts: h.accounts,
|
|
643
|
+
success: true,
|
|
644
|
+
};
|
|
645
|
+
if (!metadata) {
|
|
646
|
+
return item;
|
|
647
|
+
}
|
|
648
|
+
const meta = getMeta(scope, mint);
|
|
649
|
+
const status = failures.get(mint) === 'failed' ? 'failed' : meta.name == null && meta.symbol == null ? 'missing' : 'ok';
|
|
650
|
+
return { ...item, name: meta.name ?? null, symbol: meta.symbol ?? null, metadataStatus: status };
|
|
651
|
+
});
|
|
652
|
+
if (includeNative) {
|
|
653
|
+
const sol_ = { token: NATIVE_MINT, native: true, balance: sol.toString(), decimals: SOL_DECIMALS, formatted: formatUnits(sol, SOL_DECIMALS), tokenProgram: null, accounts: 1, success: true };
|
|
654
|
+
list.unshift(metadata ? { ...sol_, name: 'Solana', symbol: 'SOL', metadataStatus: 'ok' } : sol_);
|
|
655
|
+
}
|
|
656
|
+
return this.#attachSlot(list, { slot: scanSlot }, options);
|
|
276
657
|
});
|
|
277
|
-
if (includeNative) {
|
|
278
|
-
const sol_ = { token: NATIVE_MINT, native: true, balance: sol.toString(), decimals: SOL_DECIMALS, formatted: formatAmount(sol, SOL_DECIMALS), tokenProgram: null, accounts: 1, success: true };
|
|
279
|
-
list.unshift(metadata ? { ...sol_, name: 'Solana', symbol: 'SOL', metadataStatus: 'ok' } : sol_);
|
|
280
|
-
}
|
|
281
|
-
return list;
|
|
282
658
|
}
|
|
283
|
-
async #scanBalances(owner, mints, withSymbol) {
|
|
659
|
+
async #scanBalances(ctx, owner, mints, withSymbol, allowed) {
|
|
284
660
|
const scope = this.#scope();
|
|
285
|
-
|
|
661
|
+
// held 里只有允许的程序的代币
|
|
662
|
+
const { sol, held } = await this.#scanHoldings(ctx, owner, allowed, withSymbol);
|
|
286
663
|
// Wrapped SOL(So111…112)默认按原生 SOL 处理:余额列表里只有一项 SOL,不再列出 wSOL 代币账户
|
|
287
|
-
|
|
664
|
+
// 第一项是主币:用 nativeMints 里的地址(nativeMints 不含 So111…112 时 wSOL 作为普通代币列出,不能再拿它当 SOL)
|
|
665
|
+
const nativeLead = this.#nativeMints.has(NATIVE_MINT) ? NATIVE_MINT : this.#nativeMints.values().next().value;
|
|
666
|
+
const targets = mints ?? [
|
|
667
|
+
...(nativeLead === undefined ? [] : [nativeLead]),
|
|
668
|
+
...[...held].filter(([mint, h]) => h.amount > 0n && !this.#nativeMints.has(mint)).map(([mint]) => mint),
|
|
669
|
+
];
|
|
288
670
|
// 没持有的代币(拿不到 decimals)和缺 symbol 的代币:只读 mint / 元数据账户补上,不需要 ATA
|
|
289
|
-
await this.#loadMeta(scope, targets.filter((mint) => !this.#nativeMints.has(mint) && isAddress(mint)), withSymbol);
|
|
290
|
-
return targets.
|
|
671
|
+
const failures = await this.#loadMeta(ctx, scope, targets.filter((mint) => !this.#nativeMints.has(mint) && isAddress(mint)), withSymbol);
|
|
672
|
+
return targets.flatMap((mint) => {
|
|
291
673
|
if (this.#nativeMints.has(mint)) {
|
|
292
|
-
return
|
|
674
|
+
return [
|
|
675
|
+
withSymbolField({ token: mint, native: true, balance: sol.toString(), decimals: SOL_DECIMALS, formatted: formatUnits(sol, SOL_DECIMALS), tokenProgram: null, success: true }, withSymbol, 'SOL'),
|
|
676
|
+
];
|
|
293
677
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
678
|
+
return this.#heldBalance(scope, mint, held.get(mint), failures, withSymbol, allowed);
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* 指定 mints、统计全部代币账户:每个代币一次按 mint 过滤的 getTokenAccountsByOwner(同一 tick 发出,自动合并)。
|
|
683
|
+
* mint 不存在 / 不是代币时节点返回参数错误,按“没持有”处理,再由 #loadMeta 确认原因
|
|
684
|
+
*/
|
|
685
|
+
async #mintAccountBalances(ctx, owner, mints, withSymbol, allowed) {
|
|
686
|
+
const scope = this.#scope();
|
|
687
|
+
// 导入的、未经链上确认的所属程序不用来排除代币(可能记错):照常查询,从链上学到后再按程序过滤
|
|
688
|
+
const queried = [
|
|
689
|
+
...new Set(mints.filter((mint) => {
|
|
297
690
|
const meta = getMeta(scope, mint);
|
|
298
|
-
return
|
|
691
|
+
return !this.#nativeMints.has(mint) && isAddress(mint) && (meta.programUnverified || !isExcluded(meta.tokenProgram, allowed));
|
|
692
|
+
})),
|
|
693
|
+
];
|
|
694
|
+
const [lamports, ...results] = await Promise.all([
|
|
695
|
+
mints.some((mint) => this.#nativeMints.has(mint))
|
|
696
|
+
? this.#call(ctx, 'getBalance', [owner, { commitment: this.#commitment }])
|
|
697
|
+
: Promise.resolve(null),
|
|
698
|
+
...queried.map((mint) => this.#call(ctx, 'getTokenAccountsByOwner', [owner, { mint }, { encoding: 'jsonParsed', commitment: this.#commitment }]).catch((err) => {
|
|
699
|
+
// "Invalid param: could not find mint" 等参数错误:mint 不存在或不是代币;节点问题照常抛出
|
|
700
|
+
if (err instanceof RpcError && !err.nodeFault && err.code === -32602)
|
|
701
|
+
return null;
|
|
702
|
+
throw err;
|
|
703
|
+
})),
|
|
704
|
+
]);
|
|
705
|
+
const held = await this.#collectHoldings(ctx, scope, queried.flatMap((_, i) => (results[i]?.value ?? []).map((entry) => ({ program: entry.account?.owner, entry }))), withSymbol);
|
|
706
|
+
// 没持有的代币补 decimals(同时确认 mint 是否存在),需要时补 symbol
|
|
707
|
+
const failures = await this.#loadMeta(ctx, scope, queried, withSymbol);
|
|
708
|
+
const sol = BigInt(lamports?.value ?? 0);
|
|
709
|
+
return mints.flatMap((mint) => {
|
|
710
|
+
if (this.#nativeMints.has(mint)) {
|
|
711
|
+
return [
|
|
712
|
+
withSymbolField({ token: mint, native: true, balance: sol.toString(), decimals: SOL_DECIMALS, formatted: formatUnits(sol, SOL_DECIMALS), tokenProgram: null, success: true }, withSymbol, 'SOL'),
|
|
713
|
+
];
|
|
299
714
|
}
|
|
300
|
-
return
|
|
715
|
+
return this.#heldBalance(scope, mint, held.get(mint), failures, withSymbol, allowed);
|
|
301
716
|
});
|
|
302
717
|
}
|
|
718
|
+
/** 扫描类查询(scan / accounts: 'all')里单个代币的结果;不允许的程序返回空数组 */
|
|
719
|
+
#heldBalance(scope, mint, h, failures, withSymbol, allowed) {
|
|
720
|
+
if (!isAddress(mint)) {
|
|
721
|
+
return [failedBalance(mint, 'invalid-address', null, withSymbol, null)];
|
|
722
|
+
}
|
|
723
|
+
const meta = getMeta(scope, mint);
|
|
724
|
+
if (!h) {
|
|
725
|
+
// 没持有(或属于不允许的程序):余额为 0;decimals 来自 mint 账户
|
|
726
|
+
if (isExcluded(meta.tokenProgram, allowed)) {
|
|
727
|
+
return [];
|
|
728
|
+
}
|
|
729
|
+
if (meta.decimals === undefined) {
|
|
730
|
+
const failure = failures.get(mint);
|
|
731
|
+
return [failedBalance(mint, failure === 'not-token' ? 'not-token' : 'not-found', meta.tokenProgram ?? null, withSymbol, meta.symbol ?? null)];
|
|
732
|
+
}
|
|
733
|
+
return [withSymbolField({ token: mint, native: false, balance: '0', decimals: meta.decimals, formatted: '0', tokenProgram: meta.tokenProgram ?? null, success: true }, withSymbol, meta.symbol ?? null)];
|
|
734
|
+
}
|
|
735
|
+
if (isExcluded(h.program, allowed)) {
|
|
736
|
+
return [];
|
|
737
|
+
}
|
|
738
|
+
return [
|
|
739
|
+
withSymbolField({ token: mint, native: false, balance: h.amount.toString(), decimals: h.decimals, formatted: formatUnits(h.amount, h.decimals), tokenProgram: h.program, success: true }, withSymbol, meta.symbol ?? null),
|
|
740
|
+
];
|
|
741
|
+
}
|
|
303
742
|
/**
|
|
304
743
|
* 补齐 decimals / 所属程序(以及需要时的 symbol / name):只读缺的 mint 账户和元数据账户。
|
|
305
|
-
* tolerant 为 true
|
|
744
|
+
* 返回没能补上 decimals 的 mint 及原因:failed(tolerant 为 true 时的节点问题,信息保持未知、不写缓存)、not-found、not-token
|
|
306
745
|
*/
|
|
307
|
-
async #loadMeta(scope, mints, withSymbol, tolerant = false) {
|
|
746
|
+
async #loadMeta(ctx, scope, mints, withSymbol, tolerant = false) {
|
|
308
747
|
const plan = [...new Set(mints)].flatMap((mint) => {
|
|
309
748
|
const meta = getMeta(scope, mint);
|
|
310
749
|
const needSymbol = withSymbol && meta.symbol === undefined;
|
|
@@ -313,31 +752,38 @@ export class SolanaClient {
|
|
|
313
752
|
}
|
|
314
753
|
return [{ mint, metadata: needSymbol ? getMetadataAddress(mint) : null }];
|
|
315
754
|
});
|
|
316
|
-
const
|
|
755
|
+
const failures = new Map();
|
|
317
756
|
if (!plan.length) {
|
|
318
|
-
return
|
|
757
|
+
return failures;
|
|
319
758
|
}
|
|
320
|
-
const fetched = await this.#fetchAccounts(plan.flatMap(({ mint, metadata }) => (metadata ? [mint, metadata] : [mint])), tolerant);
|
|
759
|
+
const fetched = await this.#fetchAccounts(plan.flatMap(({ mint, metadata }) => (metadata ? [mint, metadata] : [mint])), tolerant, ctx);
|
|
321
760
|
for (const { mint, metadata } of plan) {
|
|
322
761
|
const mintAccount = fetched.get(mint);
|
|
323
762
|
const metadataAccount = metadata ? fetched.get(metadata) : null;
|
|
324
763
|
// mint 和元数据账户可能落在不同的请求里:任一个没读到都算失败,不能当成“没有元数据”缓存
|
|
325
764
|
if (mintAccount === FAILED || metadataAccount === FAILED) {
|
|
326
|
-
|
|
765
|
+
failures.set(mint, 'failed');
|
|
327
766
|
continue;
|
|
328
767
|
}
|
|
329
|
-
this.#learn(scope, mint, mintAccount ?? null, metadataAccount ?? null, metadata !== null)
|
|
768
|
+
if (this.#learn(scope, mint, mintAccount ?? null, metadataAccount ?? null, metadata !== null).decimals === undefined) {
|
|
769
|
+
failures.set(mint, mintAccount ? 'not-token' : 'not-found');
|
|
770
|
+
}
|
|
330
771
|
}
|
|
331
|
-
return
|
|
772
|
+
return failures;
|
|
332
773
|
}
|
|
333
774
|
/**
|
|
334
775
|
* 批量查代币详情(一次 getMultipleAccounts),可以选择返回哪些字段。
|
|
335
776
|
* name / symbol / uri 优先取 Token-2022 TokenMetadata 扩展,其次 Metaplex 元数据。
|
|
777
|
+
* transferFee:Token-2022 转账手续费,请求时会顺带发一次 getEpochInfo(同一个批量请求里)选出当前生效的配置
|
|
336
778
|
*/
|
|
337
|
-
|
|
779
|
+
tokens(mints, options = {}) {
|
|
780
|
+
return abortable(options.signal, () => this.#tokens(mints, options));
|
|
781
|
+
}
|
|
782
|
+
async #tokens(mints, options) {
|
|
338
783
|
const fields = (options.fields ?? DEFAULT_TOKEN_FIELDS);
|
|
339
784
|
const wanted = new Set(fields);
|
|
340
785
|
const scope = this.#scope();
|
|
786
|
+
const ctx = { signal: options.signal };
|
|
341
787
|
const needsNames = wanted.has('name') || wanted.has('symbol') || wanted.has('uri');
|
|
342
788
|
const addresses = [];
|
|
343
789
|
const plan = mints.map((mint) => {
|
|
@@ -345,11 +791,12 @@ export class SolanaClient {
|
|
|
345
791
|
return { mint, mintIndex: -1, metadataIndex: -1 };
|
|
346
792
|
}
|
|
347
793
|
const meta = getMeta(scope, mint);
|
|
348
|
-
// uri / supply /
|
|
794
|
+
// uri / supply / 权限 / 手续费不缓存,需要时总要读 mint;name / symbol 命中缓存时可以省掉元数据账户
|
|
349
795
|
const cachedOnly = !wanted.has('uri') &&
|
|
350
796
|
!wanted.has('supply') &&
|
|
351
797
|
!wanted.has('mintAuthority') &&
|
|
352
798
|
!wanted.has('freezeAuthority') &&
|
|
799
|
+
!wanted.has('transferFee') &&
|
|
353
800
|
(!wanted.has('decimals') || meta.decimals !== undefined) &&
|
|
354
801
|
(!wanted.has('tokenProgram') || meta.tokenProgram !== undefined) &&
|
|
355
802
|
(!wanted.has('name') || meta.name !== undefined) &&
|
|
@@ -364,35 +811,59 @@ export class SolanaClient {
|
|
|
364
811
|
metadataIndex: needsNames && !namesCached ? addresses.push(getMetadataAddress(mint)) - 1 : -1,
|
|
365
812
|
};
|
|
366
813
|
});
|
|
367
|
-
const accounts =
|
|
814
|
+
const [accounts, epoch] = await Promise.all([
|
|
815
|
+
addresses.length ? this.#accounts(addresses, ctx) : Promise.resolve([]),
|
|
816
|
+
// 手续费按当前 epoch 选新 / 旧配置;和账户读取在同一个批量请求里
|
|
817
|
+
wanted.has('transferFee') && addresses.length
|
|
818
|
+
? this.#call(ctx, 'getEpochInfo', [{ commitment: this.#commitment }]).then((res) => BigInt(res.epoch))
|
|
819
|
+
: Promise.resolve(null),
|
|
820
|
+
]);
|
|
368
821
|
return plan.map(({ mint, mintIndex, metadataIndex }) => {
|
|
369
822
|
const native = this.#nativeMints.has(mint);
|
|
370
823
|
const values = native
|
|
371
|
-
? { exists: true, name: 'Solana', symbol: 'SOL', uri: null, decimals: SOL_DECIMALS, supply: null, tokenProgram: null, mintAuthority: null, freezeAuthority: null }
|
|
372
|
-
: this.#tokenValues(scope, mint, mintIndex === -1 ? null : (accounts[mintIndex] ?? null), metadataIndex === -1 ? null : (accounts[metadataIndex] ?? null), mintIndex !== -1, mintIndex !== -1 && metadataIndex !== -1);
|
|
824
|
+
? { exists: true, name: 'Solana', symbol: 'SOL', uri: null, decimals: SOL_DECIMALS, supply: null, tokenProgram: null, mintAuthority: null, freezeAuthority: null, transferFee: null }
|
|
825
|
+
: this.#tokenValues(scope, mint, mintIndex === -1 ? null : (accounts[mintIndex] ?? null), metadataIndex === -1 ? null : (accounts[metadataIndex] ?? null), mintIndex !== -1, mintIndex !== -1 && metadataIndex !== -1, epoch);
|
|
373
826
|
const out = { address: mint, native };
|
|
374
|
-
let
|
|
827
|
+
let missing;
|
|
375
828
|
for (const field of fields) {
|
|
376
829
|
out[field] = values[field] ?? null;
|
|
377
|
-
// 权限为 null
|
|
378
|
-
const nullable = field === 'mintAuthority' || field === 'freezeAuthority' || (native && (field === 'uri' || field === 'supply' || field === 'tokenProgram'));
|
|
830
|
+
// 权限为 null 表示没有权限、手续费为 null 表示没有手续费,都是有效值;主币没有 uri / supply / tokenProgram
|
|
831
|
+
const nullable = field === 'mintAuthority' || field === 'freezeAuthority' || field === 'transferFee' || (native && (field === 'uri' || field === 'supply' || field === 'tokenProgram'));
|
|
379
832
|
if (out[field] === null && !nullable) {
|
|
380
|
-
|
|
833
|
+
missing ??= field;
|
|
381
834
|
}
|
|
382
835
|
}
|
|
383
836
|
if (wanted.has('supply')) {
|
|
384
837
|
const supply = values.supply;
|
|
385
838
|
const decimals = values.decimals;
|
|
386
|
-
out.supplyFormatted = supply === null || decimals === null ? null :
|
|
839
|
+
out.supplyFormatted = supply === null || decimals === null ? null : formatUnits(BigInt(supply), decimals);
|
|
840
|
+
}
|
|
841
|
+
const error = native
|
|
842
|
+
? undefined
|
|
843
|
+
: !isAddress(mint)
|
|
844
|
+
? 'invalid-address'
|
|
845
|
+
: !values.exists
|
|
846
|
+
? accounts[mintIndex]
|
|
847
|
+
? 'not-token'
|
|
848
|
+
: 'not-found'
|
|
849
|
+
: missing
|
|
850
|
+
? 'missing-field'
|
|
851
|
+
: undefined;
|
|
852
|
+
out.success = error === undefined;
|
|
853
|
+
if (error) {
|
|
854
|
+
out.error = error;
|
|
855
|
+
if (error === 'missing-field') {
|
|
856
|
+
out.errorField = missing;
|
|
857
|
+
}
|
|
387
858
|
}
|
|
388
|
-
out.success = success;
|
|
389
859
|
return out;
|
|
390
860
|
});
|
|
391
861
|
}
|
|
392
|
-
#tokenValues(scope, mint, mintAccount, metadataAccount, fetchedMint, lookedForNames
|
|
862
|
+
#tokenValues(scope, mint, mintAccount, metadataAccount, fetchedMint, lookedForNames, epoch) {
|
|
393
863
|
const meta = this.#learn(scope, mint, mintAccount, metadataAccount, lookedForNames);
|
|
394
864
|
const info = mintAccount ? safeParseMint(mintAccount) : null;
|
|
395
865
|
const uri = info?.metadata?.uri ?? (metadataAccount ? (safeParseMetaplex(metadataAccount)?.uri ?? null) : null);
|
|
866
|
+
const feeConfig = info && mintAccount?.owner === TOKEN_2022_PROGRAM_ID ? parseTransferFeeConfig(mintAccount.data) : null;
|
|
396
867
|
return {
|
|
397
868
|
// 读了 mint 账户就以它为准(不存在则 false);没读说明请求的字段全部命中缓存
|
|
398
869
|
exists: fetchedMint ? info !== null : true,
|
|
@@ -404,77 +875,95 @@ export class SolanaClient {
|
|
|
404
875
|
tokenProgram: meta.tokenProgram ?? null,
|
|
405
876
|
mintAuthority: info?.mintAuthority ?? null,
|
|
406
877
|
freezeAuthority: info?.freezeAuthority ?? null,
|
|
878
|
+
transferFee: feeConfig ? toTransferFeeConfig(feeConfig.older, feeConfig.newer, epoch) : null,
|
|
407
879
|
};
|
|
408
880
|
}
|
|
409
881
|
/** 批量查 NFT 元数据(Metaplex;Token-2022 NFT 取 TokenMetadata 扩展),一次 getMultipleAccounts */
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
882
|
+
nfts(mints, options = {}) {
|
|
883
|
+
return abortable(options.signal, async () => {
|
|
884
|
+
const scope = this.#scope();
|
|
885
|
+
const addresses = [];
|
|
886
|
+
const plan = mints.map((mint) => isAddress(mint) ? { mint, metadataIndex: addresses.push(getMetadataAddress(mint)) - 1, mintIndex: addresses.push(mint) - 1 } : { mint, metadataIndex: -1, mintIndex: -1 });
|
|
887
|
+
const accounts = addresses.length ? await this.#accounts(addresses, { signal: options.signal }) : [];
|
|
888
|
+
return plan.map(({ mint, metadataIndex, mintIndex }) => {
|
|
889
|
+
const metadataAccount = metadataIndex === -1 ? null : (accounts[metadataIndex] ?? null);
|
|
890
|
+
const mintAccount = mintIndex === -1 ? null : (accounts[mintIndex] ?? null);
|
|
891
|
+
this.#learn(scope, mint, mintAccount, metadataAccount, mintIndex !== -1);
|
|
892
|
+
const metaplex = metadataAccount ? safeParseMetaplex(metadataAccount) : null;
|
|
893
|
+
const ext = mintAccount ? (safeParseMint(mintAccount)?.metadata ?? null) : null;
|
|
894
|
+
if (!metaplex && !ext) {
|
|
895
|
+
const error = mintIndex === -1 ? 'invalid-address' : !mintAccount ? 'not-found' : !safeParseMint(mintAccount) ? 'not-token' : 'no-metadata';
|
|
896
|
+
return { mint, name: null, symbol: null, uri: null, collection: null, creators: [], sellerFeeBasisPoints: null, tokenStandard: null, isMutable: null, updateAuthority: null, success: false, error };
|
|
897
|
+
}
|
|
898
|
+
return {
|
|
899
|
+
mint,
|
|
900
|
+
name: ext?.name ?? metaplex?.name ?? null,
|
|
901
|
+
symbol: ext?.symbol ?? metaplex?.symbol ?? null,
|
|
902
|
+
uri: ext?.uri ?? metaplex?.uri ?? null,
|
|
903
|
+
collection: metaplex?.collection ?? null,
|
|
904
|
+
creators: metaplex?.creators ?? [],
|
|
905
|
+
sellerFeeBasisPoints: metaplex?.sellerFeeBasisPoints ?? null,
|
|
906
|
+
tokenStandard: metaplex?.tokenStandard == null ? null : (TOKEN_STANDARDS[metaplex.tokenStandard] ?? null),
|
|
907
|
+
isMutable: metaplex?.isMutable ?? null,
|
|
908
|
+
updateAuthority: metaplex?.updateAuthority ?? null,
|
|
909
|
+
success: true,
|
|
910
|
+
};
|
|
911
|
+
});
|
|
437
912
|
});
|
|
438
913
|
}
|
|
439
|
-
/**
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
const
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
914
|
+
/**
|
|
915
|
+
* 批量查 NFT 持有人:getTokenLargestAccounts(合并成一个批量请求)+ 一次 getMultipleAccounts。
|
|
916
|
+
* 节点拒绝的 mint(不存在 / 不是代币)在同一次 getMultipleAccounts 里读 mint 账户区分原因
|
|
917
|
+
*/
|
|
918
|
+
nftOwners(mints, options = {}) {
|
|
919
|
+
return abortable(options.signal, async () => {
|
|
920
|
+
const ctx = { signal: options.signal };
|
|
921
|
+
const largest = await Promise.all(mints.map((mint) => isAddress(mint)
|
|
922
|
+
? this.#call(ctx, 'getTokenLargestAccounts', [mint, { commitment: this.#commitment }])
|
|
923
|
+
.then((res) => ({ tokenAccount: res.value.find((a) => a.amount !== '0')?.address ?? null, rejected: false }))
|
|
924
|
+
.catch((err) => {
|
|
925
|
+
// mint 不存在 / 不是代币:该项失败;节点问题照常抛出
|
|
926
|
+
if (err instanceof RpcError && !err.nodeFault)
|
|
927
|
+
return { tokenAccount: null, rejected: true };
|
|
928
|
+
throw err;
|
|
929
|
+
})
|
|
930
|
+
: Promise.resolve({ tokenAccount: null, rejected: false })));
|
|
931
|
+
const toRead = largest.flatMap(({ tokenAccount, rejected }, i) => (tokenAccount ? [tokenAccount] : rejected ? [mints[i]] : []));
|
|
932
|
+
const accounts = toRead.length ? await this.#accounts(toRead, ctx) : [];
|
|
933
|
+
const byAddress = new Map(toRead.map((a, i) => [a, accounts[i] ?? null]));
|
|
934
|
+
return mints.map((mint, i) => {
|
|
935
|
+
const { tokenAccount, rejected } = largest[i] ?? { tokenAccount: null, rejected: false };
|
|
936
|
+
if (!isAddress(mint)) {
|
|
937
|
+
return { mint, owner: null, tokenAccount: null, success: false, error: 'invalid-address' };
|
|
462
938
|
}
|
|
463
|
-
|
|
464
|
-
owner
|
|
939
|
+
if (rejected) {
|
|
940
|
+
return { mint, owner: null, tokenAccount: null, success: false, error: byAddress.get(mint) ? 'not-token' : 'not-found' };
|
|
465
941
|
}
|
|
466
|
-
|
|
467
|
-
|
|
942
|
+
const account = tokenAccount ? byAddress.get(tokenAccount) : null;
|
|
943
|
+
let owner = null;
|
|
944
|
+
if (account) {
|
|
945
|
+
try {
|
|
946
|
+
owner = parseTokenAccount(account.data).owner;
|
|
947
|
+
}
|
|
948
|
+
catch {
|
|
949
|
+
owner = null;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
// 没有余额大于 0 的代币账户(供应量为 0 / 已销毁),或代币账户刚被关闭
|
|
953
|
+
return owner ? { mint, owner, tokenAccount, success: true } : { mint, owner: null, tokenAccount: null, success: false, error: 'no-holder' };
|
|
954
|
+
});
|
|
468
955
|
});
|
|
469
956
|
}
|
|
470
957
|
/** 查某地址持有的全部 NFT(扫描代币账户:数量 1、精度 0),再批量读元数据。需要支持 getTokenAccountsByOwner 的节点 */
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
958
|
+
ownerNfts(owner, options = {}) {
|
|
959
|
+
return abortable(options.signal, async () => {
|
|
960
|
+
if (!isAddress(owner)) {
|
|
961
|
+
throw new Error(`Invalid owner address: ${owner}`);
|
|
962
|
+
}
|
|
963
|
+
const { held } = await this.#scanHoldings({ signal: options.signal }, owner);
|
|
964
|
+
const mints = [...held].filter(([, h]) => isNftHolding(h)).map(([mint]) => mint);
|
|
965
|
+
return mints.length ? (await this.nfts(mints, options)).filter((nft) => nft.success) : [];
|
|
966
|
+
});
|
|
478
967
|
}
|
|
479
968
|
#scope() {
|
|
480
969
|
return this.#scopeId;
|
|
@@ -509,6 +998,14 @@ export class SolanaClient {
|
|
|
509
998
|
return getMeta(scope, mint);
|
|
510
999
|
}
|
|
511
1000
|
}
|
|
1001
|
+
function toTransferFee(fee) {
|
|
1002
|
+
return { basisPoints: fee.basisPoints, maximumFee: fee.maximumFee.toString(), epoch: fee.epoch.toString() };
|
|
1003
|
+
}
|
|
1004
|
+
/** 当前生效的配置:epoch >= newer.epoch 用 newer,否则 older;不知道当前 epoch 时按 newer */
|
|
1005
|
+
function toTransferFeeConfig(older, newer, epoch) {
|
|
1006
|
+
const current = epoch === null || epoch >= newer.epoch ? newer : older;
|
|
1007
|
+
return { ...toTransferFee(current), older: toTransferFee(older), newer: toTransferFee(newer) };
|
|
1008
|
+
}
|
|
512
1009
|
function toAccountInfo(address, raw) {
|
|
513
1010
|
if (!raw) {
|
|
514
1011
|
return null;
|
|
@@ -527,7 +1024,9 @@ function safeParseMint(account) {
|
|
|
527
1024
|
return null;
|
|
528
1025
|
}
|
|
529
1026
|
try {
|
|
530
|
-
|
|
1027
|
+
const mint = parseMint(account.data);
|
|
1028
|
+
// 未初始化的 mint(创建和初始化分在两笔交易里,恰好在中间读到):decimals 还是 0,不能当真、更不能永久缓存
|
|
1029
|
+
return mint.isInitialized ? mint : null;
|
|
531
1030
|
}
|
|
532
1031
|
catch {
|
|
533
1032
|
return null;
|
|
@@ -563,13 +1062,23 @@ function setMeta(scope, mint, meta) {
|
|
|
563
1062
|
}
|
|
564
1063
|
const key = `${scope}:${mint}`;
|
|
565
1064
|
const merged = { ...tokenMetaCache.get(key), ...defined };
|
|
1065
|
+
if ('tokenProgram' in defined && !defined.programUnverified) {
|
|
1066
|
+
delete merged.programUnverified; // 从链上学到了所属程序
|
|
1067
|
+
}
|
|
566
1068
|
tokenMetaCache.delete(key); // 重新插入,保持“最近写入在后”的顺序
|
|
567
1069
|
tokenMetaCache.set(key, merged);
|
|
568
1070
|
if (tokenMetaCache.size > MAX_CACHED_TOKENS) {
|
|
569
1071
|
tokenMetaCache.delete(tokenMetaCache.keys().next().value);
|
|
570
1072
|
}
|
|
1073
|
+
for (const listener of cacheWriteListeners) {
|
|
1074
|
+
listener();
|
|
1075
|
+
}
|
|
571
1076
|
}
|
|
572
1077
|
function withSymbolField(balance, withSymbol, symbol) {
|
|
573
1078
|
return withSymbol ? { ...balance, symbol } : balance;
|
|
574
1079
|
}
|
|
1080
|
+
/** 失败项:余额为 0,带原因 */
|
|
1081
|
+
function failedBalance(token, error, tokenProgram, withSymbol, symbol) {
|
|
1082
|
+
return { ...withSymbolField({ token, native: false, balance: '0', decimals: 0, formatted: '0', tokenProgram, success: false }, withSymbol, symbol), error };
|
|
1083
|
+
}
|
|
575
1084
|
//# sourceMappingURL=client.js.map
|