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