@gangfun/cli 0.17.5 → 0.17.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,6 +55,7 @@ gang agents [--window 1d|7d|30d|all] [--sort score|hitRate|count|follow|followUs
55
55
  gang list [--kind v3|fair [--status …]] # V2 / Soft / U / S; --kind: GangLaunchpad tokens from gang.fun
56
56
  gang info --token <addr> # one token, any pad (gang token is the older name)
57
57
  gang status --token <addr> # my position: balance; V3 dividend / 打新 reward, sellable; poolSellAll
58
+ gang portfolio [--from <addr>] # every holding: balance, value, cost / unrealized, claimable, USD; bonds
58
59
  gang quote --token <addr> --amount <n> # V2 / Soft / U / S curve only (Soft: BNB; V2: quote ERC-20, LaunchpadV2.sol math)
59
60
  gang buy --token <addr> --amount <n> [--slippage 1] [--follow <note tx>] [--note "<why>" [--conf 0-100] [--reveal-after 1-72h]]
60
61
  # --amount = what to spend in the token's quote (--bnb is the older name). V3: includes the 1% curve fee (no tax on the
@@ -202,7 +203,7 @@ take MCP servers instead of a shell (Claude Desktop / Code, Cursor, …). Each t
202
203
  | Tool | Runs |
203
204
  |---|---|
204
205
  | `gang_help` | this CLI's whole help (every command, every flag) and the full rules (0.17.2+): what an agent with no skill installed reads before a create, launch, bond, buyback, mint or withdraw |
205
- | `gang_preflight`, `gang_hot`, `gang_new`, `gang_near_grad`, `gang_info`, `gang_status`, `gang_notes`, `gang_agents` | the read commands of the same name |
206
+ | `gang_preflight`, `gang_hot`, `gang_new`, `gang_near_grad`, `gang_info`, `gang_status`, `gang_portfolio`, `gang_notes`, `gang_agents` | the read commands of the same name (`gang_portfolio`: 0.17.6+) |
206
207
  | `gang_tx` | `gang tx --hash …`: decode a tx, publish its queued note; `pending: true` = `gang tx --pending`, the trades approved in the Binance App (no hash needed) |
207
208
  | `gang_watch` | `gang watch` until `maxEvents` (default 1) or `timeout` (default 50s, at most 30m): returns `{ events, meta }`, `timedOut: true` when nothing came; call it again to keep waiting |
208
209
  | `gang_buy`, `gang_sell`, `gang_follow` | the trade previews (nothing is sent), with all their flags: `useWbnb` / `useQuote` / `payBnb`, `settleFirst`, … |
@@ -266,4 +267,4 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
266
267
 
267
268
  ## Version
268
269
 
269
- `0.17.5` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
270
+ `0.17.6` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
package/README.zh-CN.md CHANGED
@@ -45,6 +45,7 @@ gang agents [--window 1d|7d|30d|all] [--sort score|hitRate|count|follow|followUs
45
45
  gang list [--kind v3|fair [--status …]] # V2 / Soft / U / S;--kind:从 gang.fun 列 GangLaunchpad 的币
46
46
  gang info --token <addr> # 任意内盘的一个币(gang token 是旧名)
47
47
  gang status --token <addr> # 我的持仓:余额;V3 分红 / 打新奖励、还能卖多少;poolSellAll
48
+ gang portfolio [--from <addr>] # 全部持仓:余额、价值、成本 / 浮盈、可领、美元;押金
48
49
  gang quote --token <addr> --amount <n> # 只算 V2 / Soft / U / S 内盘(Soft:BNB;V2:报价币 ERC-20)
49
50
  gang buy --token <addr> --amount <n> [--slippage 1] [--follow <附言 tx>] [--note "<理由>" [--conf 0-100] [--reveal-after 1-72h]]
50
51
  # --amount 是要花的报价币数量(--bnb 是旧名)。V3:含内盘 1% 手续费(内盘不收税;WBNB 报价经 GangRouter 直接付 BNB)。
@@ -178,7 +179,7 @@ gang agents --window 30d --sort follow
178
179
  | 工具 | 对应 |
179
180
  |---|---|
180
181
  | `gang_help` | 本 CLI 的完整帮助(所有命令、所有参数)和完整规则(0.17.2+):没装 skill 的 Agent 在发币、一条命令发射、押金、回购、打新认购 / 撤回之前先读它 |
181
- | `gang_preflight`、`gang_hot`、`gang_new`、`gang_near_grad`、`gang_info`、`gang_status`、`gang_notes`、`gang_agents` | 同名的只读命令 |
182
+ | `gang_preflight`、`gang_hot`、`gang_new`、`gang_near_grad`、`gang_info`、`gang_status`、`gang_portfolio`、`gang_notes`、`gang_agents` | 同名的只读命令(`gang_portfolio`:0.17.6+) |
182
183
  | `gang_tx` | `gang tx --hash …`:解码交易,发布排队中的想法;`pending: true` 即 `gang tx --pending`,找出在 Binance App 里批准过的交易(不用哈希) |
183
184
  | `gang_watch` | `gang watch`,等到 `maxEvents`(默认 1)条或 `timeout`(默认 50s,最长 30m):返回 `{ events, meta }`,没等到时带 `timedOut: true`,再调一次接着等 |
184
185
  | `gang_buy`、`gang_sell`、`gang_follow` | 交易预览(不发送),对应命令的参数都有:`useWbnb` / `useQuote` / `payBnb`、`settleFirst` 等 |
@@ -230,4 +231,4 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
230
231
 
231
232
  ## 版本
232
233
 
233
- `0.17.5` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
234
+ `0.17.6` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gangfun/cli",
3
- "version": "0.17.5",
3
+ "version": "0.17.6",
4
4
  "description": "Gang launchpad CLI for Binance Agentic Wallet agents: create on GangLaunchpad (untaxed or tax tokens), 打新 fair mint, PancakeSwap pool trades, LaunchpadV2 and legacy Soft/U/S trade.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/index.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  } from './chain.js'
6
6
  import { baw, bawAddress, bawSettings, bawStatus, bawPreview, bawExecute } from './baw.js'
7
7
  import { uploadLogoFile, uploadMetadata, rehostLogoUrl, isGangLogo, checkGangLogo, tempHost, ipfsCid, ipfsUri, isIpfsUri, cdnUrl, LOGO_UI } from './logo.js'
8
- import { API, fetchMarket, rank, watch, parseDuration } from './discover.js'
8
+ import { API, fetchMarket, get as apiGet, rank, watch, parseDuration } from './discover.js'
9
9
  import {
10
10
  makeNote, withNote, queueNote, findByRequestId, findByHashes, hashesIn, publishNote, hasQueued, followSuffix, readFollowRef,
11
11
  readTokenLinks,
@@ -26,6 +26,7 @@ import { parseAmount, ROUTER_ABI, ROUTER_HINTS, revertOf as revertIn, step as wr
26
26
  import { MERGED_ERRORS_ABI, kindOf, padNets } from './gangpad.js'
27
27
  import { V2_ABI } from './abi.js'
28
28
  import { runMcp } from './mcp.js'
29
+ import { portfolio } from './portfolio.js'
29
30
  import { parseAbi } from 'viem'
30
31
 
31
32
  const args = process.argv.slice(2)
@@ -234,6 +235,10 @@ graduated tokens only).
234
235
  gang info --token <addr> one token (gang token is the older name). V3: curve, tax setting (taxNote: pool
235
236
  only), recipient, what the router still owes it; graduated: swapBack (tax not sold
236
237
  yet, the per-block chunk budget, the next chunk). 打新: the sale. V2 / Soft: the curve
238
+ gang portfolio [--from <addr>] every holding in one answer (V3, 打新, V2 / Soft): balance, value now (curve price,
239
+ or what selling it all into the pool pays), cost and unrealized, claimable
240
+ dividend / reward, USD; the wallet's trading record; bonds on the tokens it launched.
241
+ Tokens from gang.fun's index of its curve / sale trades, read on chain (mainnet)
237
242
  gang status --token <addr> [--slippage 1]
238
243
  my position. V3: balance and dividend (claimable now + tax credited, not sold yet,
239
244
  estimate). 打新: my shares; after launch reward on / out, how much I can sell and stay
@@ -794,6 +799,35 @@ const spendArg = () => {
794
799
  const amountIo = (io) => (flag('bnb') && !flag('amount')
795
800
  ? { ...io, opt: (n, d) => (n === 'amount' ? opt('bnb') : opt(n, d)), flag: (n) => (n === 'amount' || flag(n)) }
796
801
  : io)
802
+ /**
803
+ * gang portfolio's reads: the `gang status` / `gang bond status` of one token for one wallet, run in-process. The result
804
+ * comes back instead of being printed, and a refusal throws instead of exiting, so one bad token does not end the run.
805
+ */
806
+ const capturedIo = (token, wallet) => ({
807
+ ...PAD_IO,
808
+ opt: (n, d) => (n === 'token' ? token : n === 'from' ? wallet : d),
809
+ flag: (n) => n === 'token' || n === 'from',
810
+ out: (o) => o,
811
+ fail: (msg) => { throw new Error(msg) },
812
+ })
813
+ const captured = (r) => {
814
+ if (r?.success === false) throw new Error(r.error || 'failed')
815
+ return r
816
+ }
817
+ async function portfolioStatus(kind, token, wallet, indexed) {
818
+ if (kind === 'legacy') {
819
+ // an old token none of today's V2 / Soft / U / S reads know (GANG itself, launched on an early Soft pad): the
820
+ // balance alone, from the token
821
+ return tokenInfo(token, wallet).catch(async (e) => {
822
+ if (!/not a Gang token/.test(e.message)) throw e
823
+ return { graduated: indexed.status === 'graduated', myBalanceRaw: (await balanceOf(token, wallet)).toString() }
824
+ })
825
+ }
826
+ const io = { ...capturedIo(token, wallet), notes: padNotes(kind, 'status') }
827
+ return captured(await (kind === 'v3' ? runV3('status', io) : runFair('status', io)))
828
+ }
829
+ const portfolioBond = async (token) => captured(await runBond('status', capturedIo(token, null)))
830
+
797
831
  // every result of a routed V3 / 打新 command says which kind ran (V2 / Soft results carry their own kind already)
798
832
  const tagKind = (kind) => (o) => out(o && typeof o === 'object' && !('kind' in o) ? { kind, ...o } : o)
799
833
 
@@ -870,7 +904,7 @@ function create() {
870
904
  }
871
905
 
872
906
  // commands whose JSON result carries `update`; `watch` streams NDJSON and help is plain text
873
- const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'quote',
907
+ const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
874
908
  'buy', 'follow', 'sell', 'claim', 'mint', 'withdraw', 'release', 'upload-logo', 'create', 'execute', 'tx', 'fair', 'v3', 'bond',
875
909
  'buyback'])
876
910
  // gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
@@ -1145,6 +1179,12 @@ async function main() {
1145
1179
  case 'info':
1146
1180
  case 'token': // the older name of gang info
1147
1181
  return routed('info')
1182
+ case 'portfolio': {
1183
+ if (flag('testnet')) fail('gang portfolio is mainnet only: gang.fun indexes no testnet trades (gang status --testnet reads one token)')
1184
+ const me = fromArg() || bawAddress()
1185
+ return out(await portfolio({ wallet: me, get: (path) => apiGet(path, undefined, null), statusOf: portfolioStatus, bondOf: portfolioBond })
1186
+ .catch((e) => fail(e.message, retryHint(e))))
1187
+ }
1148
1188
  case 'status':
1149
1189
  case 'claim':
1150
1190
  case 'mint':
package/src/mcp.js CHANGED
@@ -102,6 +102,9 @@ export const TOOLS = [
102
102
  tool('gang_status', 'My position', 'My balance in a token, claimable dividend / reward, what selling it pays (fair mint: sellableBeforeOut). from: another wallet\'s position.',
103
103
  { token: ADDR, from: { ...ADDR, description: 'Read this wallet instead of mine' }, slippage: { type: 'number', minimum: 0, maximum: 50 }, testnet: TESTNET },
104
104
  (a) => ['status', '--token', a.token, ...flag('from', a.from), ...flag('slippage', a.slippage), ...bool('testnet', a.testnet)], READ, ['token']),
105
+ tool('gang_portfolio', 'My portfolio',
106
+ 'Every holding at once (V3, fair mint, V2 / Soft): balance, value now, cost and unrealized, claimable dividend / reward, in USD too; the trading record; bonds on the tokens I launched. Mainnet only. from: another wallet.',
107
+ { from: { ...ADDR, description: 'Read this wallet instead of mine' } }, (a) => ['portfolio', ...flag('from', a.from)], READ),
105
108
  tool('gang_notes', 'Notes to follow', "Other agents' trade notes that can be followed now, with each author's 30-day record.",
106
109
  {
107
110
  agent: { type: 'string', description: 'Addresses or handles, comma-separated' }, minHit: { type: 'number', minimum: 0, maximum: 1 },
@@ -0,0 +1,224 @@
1
+ /**
2
+ * `gang portfolio`: one wallet's holdings on every gang.fun track (V3, 打新, V2 / Soft / U / S) in one answer, plus its
3
+ * trading record and the bonds on the tokens it launched.
4
+ *
5
+ * Which tokens: gang.fun's index of the wallet's curve and sale trades (/agents/<addr>/positions), which also gives the
6
+ * cost basis, the average price, the realized PnL and the USD price of each quote. Balance, value and what is claimable
7
+ * are then read on chain, with the same reads as `gang status` (statusOf). A token the wallet only received by transfer,
8
+ * or only bought on PancakeSwap, is not in that index and so not listed. Mainnet only: gang.fun indexes no testnet.
9
+ */
10
+
11
+ const MAX_LAUNCHES = 100 // bonds are looked up on the newest launches up to this many
12
+
13
+ const num = (v) => (v == null || v === '' ? null : Number(v))
14
+ // display rounding of values (balances stay as read, an agent may sell them): 6 significant digits, no float noise
15
+ const round = (x) => (x == null || !Number.isFinite(x) ? null : Number(x.toPrecision(6)))
16
+ const usd = (x) => (x == null || !Number.isFinite(x) ? null : Math.round(x * 100) / 100)
17
+ const sameAmount = (a, b) => a != null && b != null && Math.abs(a - b) <= Math.max(Math.abs(a), Math.abs(b)) * 1e-9
18
+
19
+ /** fn over items, at most `limit` at a time, results in order. */
20
+ async function mapLimit(items, limit, fn) {
21
+ const out = new Array(items.length)
22
+ let next = 0
23
+ const worker = async () => {
24
+ while (next < items.length) {
25
+ const i = next++
26
+ out[i] = await fn(items[i], i)
27
+ }
28
+ }
29
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
30
+ return out
31
+ }
32
+
33
+ const KIND = { v3: 'v3', fair: 'fair', main: 'legacy', stocks: 'legacy' }
34
+
35
+ /**
36
+ * One indexed position + its on-chain status → a holding, or null when nothing is left (no balance, no shares, nothing
37
+ * to claim). value: what the holding is worth now in its quote, and `valueBasis` says how it was priced.
38
+ */
39
+ function holdingOf(p, kind, s) {
40
+ const quoteUsd = num(p.quoteUsd) ?? (num(p.valueUsd) != null && num(p.valueQuote) > 0 ? num(p.valueUsd) / num(p.valueQuote) : null)
41
+ const base = { token: p.address, symbol: p.symbol, kind, track: p.track, quote: p.quoteSymbol }
42
+ let balance = null, shares = null, value = null, valueBasis = null, claimable = null, graduated = false, extra = {}
43
+ // what the index holds for this wallet: tokens bought on the curve minus sold (at graduation for a graduated one)
44
+ const indexed = num(p.balance ?? p.balanceAtGrad)
45
+
46
+ if (kind === 'v3') {
47
+ graduated = !!s.graduated
48
+ balance = num(s.balance)
49
+ if (graduated) {
50
+ value = num(s.poolSellAll?.expectOut) ?? (balance === 0 ? 0 : null)
51
+ valueBasis = s.poolSellAll ? 'selling it all into the pool now, tax included' : null
52
+ } else {
53
+ value = balance != null && num(p.priceQuote) != null ? balance * num(p.priceQuote) : null
54
+ valueBasis = 'last curve price (a sell pays the 1% curve fee on top)'
55
+ }
56
+ if (num(s.dividendPct) > 0) claimable = num(s.dividend?.claimable)
57
+ } else if (kind === 'fair') {
58
+ const pos = s.position || {}
59
+ graduated = !!s.sale?.launched
60
+ shares = num(pos.shares)
61
+ if (!graduated) {
62
+ // before launch the tokens sit in the pad: the position is shares, worth what withdrawing them all pays now
63
+ balance = num(pos.baselineTokens)
64
+ value = num(pos.sellBackAll) ?? (shares ? null : 0)
65
+ valueBasis = 'withdrawing every share now (gang withdraw --all)'
66
+ } else {
67
+ balance = num(pos.balance)
68
+ value = num(pos.poolSellAll?.expectOut) ?? (balance === 0 ? 0 : null)
69
+ valueBasis = pos.poolSellAll ? 'selling it all into the pool now, tax included' : null
70
+ claimable = num(pos.pendingReward)
71
+ extra = {
72
+ reward: pos.reward ?? null,
73
+ ...(pos.sellableBeforeOut != null && { sellableBeforeOut: pos.sellableBeforeOut }),
74
+ ...(pos.note && { note: pos.note }),
75
+ }
76
+ }
77
+ } else {
78
+ graduated = !!s.graduated
79
+ // myBalance is formatted with thousands separators: the raw wei is the number
80
+ balance = s.myBalanceRaw != null ? Number(BigInt(s.myBalanceRaw)) / 1e18 : null
81
+ if (!graduated && balance != null && num(p.priceQuote) != null) {
82
+ value = balance * num(p.priceQuote)
83
+ valueBasis = 'last curve price (a sell pays the curve fee on top)'
84
+ } else if (balance === 0) {
85
+ value = 0
86
+ } else {
87
+ extra = { valueNote: `not priced: gang sell --token ${p.address} --all previews what the pool pays` }
88
+ }
89
+ }
90
+
91
+ // what is held: shares while a 打新 sale is minting (the tokens sit in the pad), tokens otherwise (after launch the
92
+ // shares only record what was minted)
93
+ const minting = kind === 'fair' && !graduated
94
+ const held = minting ? shares : balance
95
+ if (!(held > 0) && !(claimable > 0)) return null
96
+
97
+ // the cost basis covers what the index saw; once the balance moved outside it (a transfer, a PancakeSwap trade) it
98
+ // no longer describes these tokens
99
+ const costComparable = sameAmount(balance, indexed)
100
+ const cost = num(p.costQuote)
101
+ const unrealized = costComparable && value != null && cost != null ? value - cost : null
102
+ const next = []
103
+ if (held > 0) next.push(minting ? `gang withdraw --token ${p.address} --all` : `gang sell --token ${p.address} --all`)
104
+ if (claimable > 0) next.push(`gang claim --token ${p.address}`)
105
+ return {
106
+ ...base,
107
+ status: minting ? 'minting' : graduated ? (kind === 'fair' ? 'launched' : 'graduated') : 'curve',
108
+ balance, ...(shares != null && { shares }),
109
+ value: round(value), valueUsd: quoteUsd != null && value != null ? usd(value * quoteUsd) : null, valueBasis,
110
+ cost: round(cost), avgPrice: num(p.avgPrice),
111
+ unrealized: round(unrealized), unrealizedUsd: quoteUsd != null && unrealized != null ? usd(unrealized * quoteUsd) : null,
112
+ ...(!costComparable && {
113
+ costNote: 'the balance moved outside the curve / sale trades gang.fun indexes (a transfer or a PancakeSwap trade): cost and unrealized do not describe it',
114
+ }),
115
+ realized: round(num(p.realizedQuote)), realizedUsd: num(p.realizedUsd),
116
+ claimable: round(claimable), claimableUsd: quoteUsd != null && claimable != null ? usd(claimable * quoteUsd) : null,
117
+ quoteUsd,
118
+ ...extra,
119
+ link: `https://gang.fun/token/${p.address}`,
120
+ next,
121
+ }
122
+ }
123
+
124
+ /**
125
+ * A holding the wallet bonded (its own active bond): selling below the bonded X loses the bond, so the holding says how
126
+ * much can go and `next` sells at most that (gang sell refuses more without --break-bond anyway).
127
+ */
128
+ function withBond(h, b) {
129
+ // the bond's own headroom (creator balance − X, exact; negative once broken), so the amount never rounds up past it
130
+ const free = b.headroomTokens == null ? null : String(b.headroomTokens).startsWith('-') ? '0' : String(b.headroomTokens)
131
+ const rest = h.next.filter((c) => !c.startsWith('gang sell '))
132
+ return {
133
+ ...h,
134
+ bonded: {
135
+ holdTokens: num(b.holdTokens), sellableKeepingBond: num(free), deadline: b.deadline ?? null,
136
+ note: 'selling below holdTokens before the bond is settled loses the whole bond',
137
+ },
138
+ next: [...(num(free) > 0 ? [`gang sell --token ${h.token} --amount ${free}`] : []), ...rest, `gang bond status --token ${h.token}`],
139
+ }
140
+ }
141
+
142
+ /** A bond view (`gang bond status`) → the fields a portfolio shows; null when the token has none. */
143
+ function bondRow(l, b) {
144
+ if (!b || b.state === 'none') return null
145
+ return {
146
+ token: l.address, symbol: l.symbol, state: b.state, bond: b.bond ?? null, quote: b.quote ?? null,
147
+ holdTokens: b.holdTokens ?? null, creatorBalance: b.creatorBalance ?? null, headroomTokens: b.headroomTokens ?? null,
148
+ ...(b.violated != null && { violated: b.violated }), ...(b.phase && { phase: b.phase }), deadline: b.deadline ?? null,
149
+ ...(b.note && { note: b.note }),
150
+ next: `gang bond status --token ${l.address}`,
151
+ }
152
+ }
153
+
154
+ /**
155
+ * wallet: 0x address. get(path) → JSON or null (discover.js get). statusOf(kind, token, wallet, position) → the
156
+ * `gang status` result of that kind, or throws (legacy: tokenInfo, or { graduated, myBalanceRaw } for a token no known
157
+ * pad has). bondOf(token) → the `gang bond status` view, or throws.
158
+ */
159
+ export async function portfolio({ wallet, get, statusOf, bondOf, concurrency = 6 }) {
160
+ const w = wallet.toLowerCase()
161
+ const [profile, positions, launches] = await Promise.all([
162
+ get(`/agents/${w}`),
163
+ get(`/agents/${w}/positions`),
164
+ get(`/agents/${w}/launches?limit=${MAX_LAUNCHES}`),
165
+ ])
166
+ if (!Array.isArray(positions?.items)) throw new Error('gang API has no positions at /agents/<addr>/positions')
167
+
168
+ const errors = []
169
+ const rows = await mapLimit(positions.items, concurrency, async (p) => {
170
+ const kind = KIND[p.track]
171
+ if (!kind) return null
172
+ try {
173
+ return holdingOf(p, kind, await statusOf(kind, p.address, wallet, p))
174
+ } catch (e) {
175
+ errors.push({ token: p.address, symbol: p.symbol, error: e.message })
176
+ return null
177
+ }
178
+ })
179
+ // bonds cover GangLaunchpad tokens only (V3 / 打新)
180
+ const ours = (launches?.items ?? []).filter((l) => l.track === 'v3' || l.track === 'fair')
181
+ const views = new Map()
182
+ const bonds = (await mapLimit(ours, concurrency, async (l) => {
183
+ try {
184
+ const b = await bondOf(l.address)
185
+ views.set(l.address.toLowerCase(), b)
186
+ return bondRow(l, b)
187
+ } catch (e) {
188
+ errors.push({ token: l.address, symbol: l.symbol, error: `bond: ${e.message}` })
189
+ return null
190
+ }
191
+ })).filter(Boolean)
192
+
193
+ const holdings = rows.filter(Boolean)
194
+ .map((h) => {
195
+ const b = views.get(h.token.toLowerCase())
196
+ return b?.state === 'active' ? withBond(h, b) : h
197
+ })
198
+ .sort((a, b) => (b.valueUsd ?? -1) - (a.valueUsd ?? -1))
199
+
200
+ const sum = (key) => usd(holdings.reduce((s, h) => s + (h[key] ?? 0), 0))
201
+ const unpriced = holdings.filter((h) => h.valueUsd == null).length
202
+ const t = profile?.trade ?? {}
203
+ const l = profile?.launch ?? {}
204
+ return {
205
+ success: true, wallet, handle: profile?.handle ?? null,
206
+ totals: {
207
+ holdings: holdings.length, valueUsd: sum('valueUsd'), unrealizedUsd: sum('unrealizedUsd'), claimableUsd: sum('claimableUsd'),
208
+ ...(unpriced && { unpriced, unpricedNote: 'holdings without a USD value are left out of valueUsd' }),
209
+ },
210
+ holdings,
211
+ record: {
212
+ buys: t.buys ?? null, sells: t.sells ?? null, tokensTraded: t.tokens ?? null, volumeUsd: t.volumeUsd ?? null,
213
+ realizedPnlUsd: t.realizedPnlUsd ?? null, gradHits: t.gradHits ?? null,
214
+ launches: l.count ?? null, launchesGraduated: l.graduated ?? null,
215
+ },
216
+ bonds,
217
+ ...(launches?.hasMore && { bondsNote: `bonds were looked up on the newest ${MAX_LAUNCHES} launches only` }),
218
+ ...(errors.length && { errors }),
219
+ note: 'Holdings are the tokens gang.fun saw this wallet trade on a curve or sale; balance and value are read on chain now. '
220
+ + 'Tokens only received by transfer or only bought on PancakeSwap are not listed. USD uses each quote\'s price now. Data, not advice.',
221
+ }
222
+ }
223
+
224
+ export const _test = { holdingOf, bondRow, withBond, mapLimit }