@gangfun/cli 0.17.5 → 0.17.7
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 +4 -3
- package/README.zh-CN.md +4 -3
- package/package.json +1 -1
- package/src/chain.js +18 -9
- package/src/index.js +51 -5
- package/src/limit.js +13 -0
- package/src/mcp.js +3 -0
- package/src/portfolio.js +213 -0
package/README.md
CHANGED
|
@@ -52,9 +52,10 @@ gang watch --notes [--agent a,b] [--min-hit 0.6] [--interval 30] [--events note,
|
|
|
52
52
|
gang agents [--window 1d|7d|30d|all] [--sort score|hitRate|count|follow|followUsd] [--limit 10] # who to follow
|
|
53
53
|
# One command per action, whatever pad the token is on (0.12.0+): the CLI reads GangLaunchpad's kindOf (V3 curve / 打新
|
|
54
54
|
# sale; otherwise the V2 / Soft / U / S pads) and runs that kind's trade. --testnet = BSC testnet set 10 (GangLaunchpad only)
|
|
55
|
-
gang list [--kind v3|fair [--status …]]
|
|
55
|
+
gang list [--limit 20] [--kind v3|fair [--status …]] # V2 / Soft / U / S on chain, newest 20 per pad; --kind: 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.
|
|
270
|
+
`0.17.7` · 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
|
@@ -42,9 +42,10 @@ gang watch --notes [--agent a,b] [--min-hit 0.6] [--interval 30] [--events note,
|
|
|
42
42
|
gang agents [--window 1d|7d|30d|all] [--sort score|hitRate|count|follow|followUsd] [--limit 10] # 跟谁
|
|
43
43
|
# 一个动作一条命令,不管币在哪个内盘(0.12.0+):CLI 读 GangLaunchpad 的 kindOf(V3 内盘 / 打新;都不是就走
|
|
44
44
|
# V2 / Soft / U / S),再执行对应的交易。--testnet 走 BSC 测试网第 10 套(只有 GangLaunchpad)
|
|
45
|
-
gang list [--kind v3|fair [--status …]]
|
|
45
|
+
gang list [--limit 20] [--kind v3|fair [--status …]] # 链上读 V2 / Soft / U / S,每个盘最新 20 个;--kind:从 gang.fun 列
|
|
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.
|
|
234
|
+
`0.17.7` · [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.
|
|
3
|
+
"version": "0.17.7",
|
|
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/chain.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createPublicClient, formatEther, parseEther, encodeFunctionData, decode
|
|
|
2
2
|
import { bsc } from 'viem/chains'
|
|
3
3
|
import { SOFT_ABI, V2_ABI, S_ABI, ERC20_ABI, WBNB_ABI } from './abi.js'
|
|
4
4
|
import { kindOf, padNets, rpcTransport } from './gangpad.js'
|
|
5
|
+
import { mapLimit } from './limit.js'
|
|
5
6
|
|
|
6
7
|
export const ADDR = {
|
|
7
8
|
v2: '0x1B8F3f69DFa0a7F63d308C7EB0Fd38D8b099966E',
|
|
@@ -124,18 +125,26 @@ export async function tokenInfo(token, me) {
|
|
|
124
125
|
return info
|
|
125
126
|
}
|
|
126
127
|
|
|
127
|
-
|
|
128
|
-
|
|
128
|
+
/**
|
|
129
|
+
* `gang list` without --kind: the newest `perPad` tokens of each V2 / Soft / U / S pad, read on chain (the fallback when
|
|
130
|
+
* gang.fun's API is down). Reading every token of every pad took minutes (LaunchpadV2 alone has hundreds), so the
|
|
131
|
+
* newest first, a few reads at a time. → { tokens, pads: [{ pad, total, listed }] }
|
|
132
|
+
*/
|
|
133
|
+
export async function listTokens(me, perPad = 20) {
|
|
134
|
+
const tokens = []
|
|
135
|
+
const pads = []
|
|
129
136
|
for (const pad of PADS) {
|
|
130
137
|
try {
|
|
131
|
-
const n = await read(pad.address, pad.abi, 'tokenCount')
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
138
|
+
const n = Number(await read(pad.address, pad.abi, 'tokenCount'))
|
|
139
|
+
const idx = Array.from({ length: Math.min(n, perPad) }, (_, i) => BigInt(n - 1 - i))
|
|
140
|
+
const addrs = await mapLimit(idx, 8, (i) => read(pad.address, pad.abi, 'allTokens', [i]))
|
|
141
|
+
const infos = await mapLimit(addrs, 8, (a) => tokenInfo(a, me).catch(() => null))
|
|
142
|
+
const listed = infos.filter(Boolean)
|
|
143
|
+
tokens.push(...listed)
|
|
144
|
+
pads.push({ pad: pad.id, total: n, listed: listed.length })
|
|
145
|
+
} catch { pads.push({ pad: pad.id, total: null, listed: 0, error: 'pad unreadable' }) }
|
|
137
146
|
}
|
|
138
|
-
return
|
|
147
|
+
return { tokens, pads }
|
|
139
148
|
}
|
|
140
149
|
|
|
141
150
|
/** LaunchpadV2 curve constants (LaunchpadV2.sol) — unique off-chain path = on-chain math. */
|
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)
|
|
@@ -211,8 +212,9 @@ graduated tokens only).
|
|
|
211
212
|
gang_help (this text + the rules), reads, watch, buy / sell / follow previews,
|
|
212
213
|
execute, and gang_cli for every other command
|
|
213
214
|
gang preflight check sign-in, Developer Mode, tradeAllTokens, Agent ID
|
|
214
|
-
gang list [--kind v3|fair [--status …]]
|
|
215
|
-
V2 / Soft / U / S tokens
|
|
215
|
+
gang list [--limit 20] [--kind v3|fair [--status …]]
|
|
216
|
+
V2 / Soft / U / S tokens read on chain (works without gang.fun), the newest --limit
|
|
217
|
+
per pad; --kind v3 (--status curve|graduated|all) / --kind fair
|
|
216
218
|
(--status minting|launched|all): GangLaunchpad tokens from gang.fun
|
|
217
219
|
gang hot [--limit 10] [--track all|v3|fair|v2|soft] [--include-graduated]
|
|
218
220
|
tokens not yet graduated / launched, ranked by 24h USD volume
|
|
@@ -234,6 +236,10 @@ graduated tokens only).
|
|
|
234
236
|
gang info --token <addr> one token (gang token is the older name). V3: curve, tax setting (taxNote: pool
|
|
235
237
|
only), recipient, what the router still owes it; graduated: swapBack (tax not sold
|
|
236
238
|
yet, the per-block chunk budget, the next chunk). 打新: the sale. V2 / Soft: the curve
|
|
239
|
+
gang portfolio [--from <addr>] every holding in one answer (V3, 打新, V2 / Soft): balance, value now (curve price,
|
|
240
|
+
or what selling it all into the pool pays), cost and unrealized, claimable
|
|
241
|
+
dividend / reward, USD; the wallet's trading record; bonds on the tokens it launched.
|
|
242
|
+
Tokens from gang.fun's index of its curve / sale trades, read on chain (mainnet)
|
|
237
243
|
gang status --token <addr> [--slippage 1]
|
|
238
244
|
my position. V3: balance and dividend (claimable now + tax credited, not sold yet,
|
|
239
245
|
estimate). 打新: my shares; after launch reward on / out, how much I can sell and stay
|
|
@@ -794,6 +800,35 @@ const spendArg = () => {
|
|
|
794
800
|
const amountIo = (io) => (flag('bnb') && !flag('amount')
|
|
795
801
|
? { ...io, opt: (n, d) => (n === 'amount' ? opt('bnb') : opt(n, d)), flag: (n) => (n === 'amount' || flag(n)) }
|
|
796
802
|
: io)
|
|
803
|
+
/**
|
|
804
|
+
* gang portfolio's reads: the `gang status` / `gang bond status` of one token for one wallet, run in-process. The result
|
|
805
|
+
* comes back instead of being printed, and a refusal throws instead of exiting, so one bad token does not end the run.
|
|
806
|
+
*/
|
|
807
|
+
const capturedIo = (token, wallet) => ({
|
|
808
|
+
...PAD_IO,
|
|
809
|
+
opt: (n, d) => (n === 'token' ? token : n === 'from' ? wallet : d),
|
|
810
|
+
flag: (n) => n === 'token' || n === 'from',
|
|
811
|
+
out: (o) => o,
|
|
812
|
+
fail: (msg) => { throw new Error(msg) },
|
|
813
|
+
})
|
|
814
|
+
const captured = (r) => {
|
|
815
|
+
if (r?.success === false) throw new Error(r.error || 'failed')
|
|
816
|
+
return r
|
|
817
|
+
}
|
|
818
|
+
async function portfolioStatus(kind, token, wallet, indexed) {
|
|
819
|
+
if (kind === 'legacy') {
|
|
820
|
+
// an old token none of today's V2 / Soft / U / S reads know (GANG itself, launched on an early Soft pad): the
|
|
821
|
+
// balance alone, from the token
|
|
822
|
+
return tokenInfo(token, wallet).catch(async (e) => {
|
|
823
|
+
if (!/not a Gang token/.test(e.message)) throw e
|
|
824
|
+
return { graduated: indexed.status === 'graduated', myBalanceRaw: (await balanceOf(token, wallet)).toString() }
|
|
825
|
+
})
|
|
826
|
+
}
|
|
827
|
+
const io = { ...capturedIo(token, wallet), notes: padNotes(kind, 'status') }
|
|
828
|
+
return captured(await (kind === 'v3' ? runV3('status', io) : runFair('status', io)))
|
|
829
|
+
}
|
|
830
|
+
const portfolioBond = async (token) => captured(await runBond('status', capturedIo(token, null)))
|
|
831
|
+
|
|
797
832
|
// every result of a routed V3 / 打新 command says which kind ran (V2 / Soft results carry their own kind already)
|
|
798
833
|
const tagKind = (kind) => (o) => out(o && typeof o === 'object' && !('kind' in o) ? { kind, ...o } : o)
|
|
799
834
|
|
|
@@ -870,7 +905,7 @@ function create() {
|
|
|
870
905
|
}
|
|
871
906
|
|
|
872
907
|
// 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',
|
|
908
|
+
const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list', 'hot', 'new', 'near-grad', 'notes', 'agents', 'token', 'info', 'status', 'portfolio', 'quote',
|
|
874
909
|
'buy', 'follow', 'sell', 'claim', 'mint', 'withdraw', 'release', 'upload-logo', 'create', 'execute', 'tx', 'fair', 'v3', 'bond',
|
|
875
910
|
'buyback'])
|
|
876
911
|
// gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
|
|
@@ -1003,7 +1038,12 @@ async function main() {
|
|
|
1003
1038
|
fail('--kind must be v3 or fair (leave it out for the V2 / Soft / U / S tokens)', { got: kind ?? null })
|
|
1004
1039
|
}
|
|
1005
1040
|
const me = bawStatus() === 'CONNECTED' ? bawAddress() : undefined
|
|
1006
|
-
|
|
1041
|
+
const perPad = parseCount('limit', opt('limit', '20'), 1000)
|
|
1042
|
+
const { tokens, pads } = await listTokens(me, perPad)
|
|
1043
|
+
return out({
|
|
1044
|
+
success: true, createPad: padNets('v3').mainnet.pad, perPad, pads, tokens,
|
|
1045
|
+
...(pads.some((p) => p.total > p.listed) && { note: `newest ${perPad} per pad; --limit <n> (up to 1000) lists more` }),
|
|
1046
|
+
})
|
|
1007
1047
|
}
|
|
1008
1048
|
case 'hot':
|
|
1009
1049
|
case 'new':
|
|
@@ -1145,6 +1185,12 @@ async function main() {
|
|
|
1145
1185
|
case 'info':
|
|
1146
1186
|
case 'token': // the older name of gang info
|
|
1147
1187
|
return routed('info')
|
|
1188
|
+
case 'portfolio': {
|
|
1189
|
+
if (flag('testnet')) fail('gang portfolio is mainnet only: gang.fun indexes no testnet trades (gang status --testnet reads one token)')
|
|
1190
|
+
const me = fromArg() || bawAddress()
|
|
1191
|
+
return out(await portfolio({ wallet: me, get: (path) => apiGet(path, undefined, null), statusOf: portfolioStatus, bondOf: portfolioBond })
|
|
1192
|
+
.catch((e) => fail(e.message, retryHint(e))))
|
|
1193
|
+
}
|
|
1148
1194
|
case 'status':
|
|
1149
1195
|
case 'claim':
|
|
1150
1196
|
case 'mint':
|
package/src/limit.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** fn over items, at most `limit` at a time, results in order. */
|
|
2
|
+
export async function mapLimit(items, limit, fn) {
|
|
3
|
+
const out = new Array(items.length)
|
|
4
|
+
let next = 0
|
|
5
|
+
const worker = async () => {
|
|
6
|
+
while (next < items.length) {
|
|
7
|
+
const i = next++
|
|
8
|
+
out[i] = await fn(items[i], i)
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
|
|
12
|
+
return out
|
|
13
|
+
}
|
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 },
|
package/src/portfolio.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
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
|
+
import { mapLimit } from './limit.js'
|
|
12
|
+
|
|
13
|
+
const MAX_LAUNCHES = 100 // bonds are looked up on the newest launches up to this many
|
|
14
|
+
|
|
15
|
+
const num = (v) => (v == null || v === '' ? null : Number(v))
|
|
16
|
+
// display rounding of values (balances stay as read, an agent may sell them): 6 significant digits, no float noise
|
|
17
|
+
const round = (x) => (x == null || !Number.isFinite(x) ? null : Number(x.toPrecision(6)))
|
|
18
|
+
const usd = (x) => (x == null || !Number.isFinite(x) ? null : Math.round(x * 100) / 100)
|
|
19
|
+
const sameAmount = (a, b) => a != null && b != null && Math.abs(a - b) <= Math.max(Math.abs(a), Math.abs(b)) * 1e-9
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
const KIND = { v3: 'v3', fair: 'fair', main: 'legacy', stocks: 'legacy' }
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* One indexed position + its on-chain status → a holding, or null when nothing is left (no balance, no shares, nothing
|
|
26
|
+
* to claim). value: what the holding is worth now in its quote, and `valueBasis` says how it was priced.
|
|
27
|
+
*/
|
|
28
|
+
function holdingOf(p, kind, s) {
|
|
29
|
+
const quoteUsd = num(p.quoteUsd) ?? (num(p.valueUsd) != null && num(p.valueQuote) > 0 ? num(p.valueUsd) / num(p.valueQuote) : null)
|
|
30
|
+
const base = { token: p.address, symbol: p.symbol, kind, track: p.track, quote: p.quoteSymbol }
|
|
31
|
+
let balance = null, shares = null, value = null, valueBasis = null, claimable = null, graduated = false, extra = {}
|
|
32
|
+
// what the index holds for this wallet: tokens bought on the curve minus sold (at graduation for a graduated one)
|
|
33
|
+
const indexed = num(p.balance ?? p.balanceAtGrad)
|
|
34
|
+
|
|
35
|
+
if (kind === 'v3') {
|
|
36
|
+
graduated = !!s.graduated
|
|
37
|
+
balance = num(s.balance)
|
|
38
|
+
if (graduated) {
|
|
39
|
+
value = num(s.poolSellAll?.expectOut) ?? (balance === 0 ? 0 : null)
|
|
40
|
+
valueBasis = s.poolSellAll ? 'selling it all into the pool now, tax included' : null
|
|
41
|
+
} else {
|
|
42
|
+
value = balance != null && num(p.priceQuote) != null ? balance * num(p.priceQuote) : null
|
|
43
|
+
valueBasis = 'last curve price (a sell pays the 1% curve fee on top)'
|
|
44
|
+
}
|
|
45
|
+
if (num(s.dividendPct) > 0) claimable = num(s.dividend?.claimable)
|
|
46
|
+
} else if (kind === 'fair') {
|
|
47
|
+
const pos = s.position || {}
|
|
48
|
+
graduated = !!s.sale?.launched
|
|
49
|
+
shares = num(pos.shares)
|
|
50
|
+
if (!graduated) {
|
|
51
|
+
// before launch the tokens sit in the pad: the position is shares, worth what withdrawing them all pays now
|
|
52
|
+
balance = num(pos.baselineTokens)
|
|
53
|
+
value = num(pos.sellBackAll) ?? (shares ? null : 0)
|
|
54
|
+
valueBasis = 'withdrawing every share now (gang withdraw --all)'
|
|
55
|
+
} else {
|
|
56
|
+
balance = num(pos.balance)
|
|
57
|
+
value = num(pos.poolSellAll?.expectOut) ?? (balance === 0 ? 0 : null)
|
|
58
|
+
valueBasis = pos.poolSellAll ? 'selling it all into the pool now, tax included' : null
|
|
59
|
+
claimable = num(pos.pendingReward)
|
|
60
|
+
extra = {
|
|
61
|
+
reward: pos.reward ?? null,
|
|
62
|
+
...(pos.sellableBeforeOut != null && { sellableBeforeOut: pos.sellableBeforeOut }),
|
|
63
|
+
...(pos.note && { note: pos.note }),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
} else {
|
|
67
|
+
graduated = !!s.graduated
|
|
68
|
+
// myBalance is formatted with thousands separators: the raw wei is the number
|
|
69
|
+
balance = s.myBalanceRaw != null ? Number(BigInt(s.myBalanceRaw)) / 1e18 : null
|
|
70
|
+
if (!graduated && balance != null && num(p.priceQuote) != null) {
|
|
71
|
+
value = balance * num(p.priceQuote)
|
|
72
|
+
valueBasis = 'last curve price (a sell pays the curve fee on top)'
|
|
73
|
+
} else if (balance === 0) {
|
|
74
|
+
value = 0
|
|
75
|
+
} else {
|
|
76
|
+
extra = { valueNote: `not priced: gang sell --token ${p.address} --all previews what the pool pays` }
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// what is held: shares while a 打新 sale is minting (the tokens sit in the pad), tokens otherwise (after launch the
|
|
81
|
+
// shares only record what was minted)
|
|
82
|
+
const minting = kind === 'fair' && !graduated
|
|
83
|
+
const held = minting ? shares : balance
|
|
84
|
+
if (!(held > 0) && !(claimable > 0)) return null
|
|
85
|
+
|
|
86
|
+
// the cost basis covers what the index saw; once the balance moved outside it (a transfer, a PancakeSwap trade) it
|
|
87
|
+
// no longer describes these tokens
|
|
88
|
+
const costComparable = sameAmount(balance, indexed)
|
|
89
|
+
const cost = num(p.costQuote)
|
|
90
|
+
const unrealized = costComparable && value != null && cost != null ? value - cost : null
|
|
91
|
+
const next = []
|
|
92
|
+
if (held > 0) next.push(minting ? `gang withdraw --token ${p.address} --all` : `gang sell --token ${p.address} --all`)
|
|
93
|
+
if (claimable > 0) next.push(`gang claim --token ${p.address}`)
|
|
94
|
+
return {
|
|
95
|
+
...base,
|
|
96
|
+
status: minting ? 'minting' : graduated ? (kind === 'fair' ? 'launched' : 'graduated') : 'curve',
|
|
97
|
+
balance, ...(shares != null && { shares }),
|
|
98
|
+
value: round(value), valueUsd: quoteUsd != null && value != null ? usd(value * quoteUsd) : null, valueBasis,
|
|
99
|
+
cost: round(cost), avgPrice: num(p.avgPrice),
|
|
100
|
+
unrealized: round(unrealized), unrealizedUsd: quoteUsd != null && unrealized != null ? usd(unrealized * quoteUsd) : null,
|
|
101
|
+
...(!costComparable && {
|
|
102
|
+
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',
|
|
103
|
+
}),
|
|
104
|
+
realized: round(num(p.realizedQuote)), realizedUsd: num(p.realizedUsd),
|
|
105
|
+
claimable: round(claimable), claimableUsd: quoteUsd != null && claimable != null ? usd(claimable * quoteUsd) : null,
|
|
106
|
+
quoteUsd,
|
|
107
|
+
...extra,
|
|
108
|
+
link: `https://gang.fun/token/${p.address}`,
|
|
109
|
+
next,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* A holding the wallet bonded (its own active bond): selling below the bonded X loses the bond, so the holding says how
|
|
115
|
+
* much can go and `next` sells at most that (gang sell refuses more without --break-bond anyway).
|
|
116
|
+
*/
|
|
117
|
+
function withBond(h, b) {
|
|
118
|
+
// the bond's own headroom (creator balance − X, exact; negative once broken), so the amount never rounds up past it
|
|
119
|
+
const free = b.headroomTokens == null ? null : String(b.headroomTokens).startsWith('-') ? '0' : String(b.headroomTokens)
|
|
120
|
+
const rest = h.next.filter((c) => !c.startsWith('gang sell '))
|
|
121
|
+
return {
|
|
122
|
+
...h,
|
|
123
|
+
bonded: {
|
|
124
|
+
holdTokens: num(b.holdTokens), sellableKeepingBond: num(free), deadline: b.deadline ?? null,
|
|
125
|
+
note: 'selling below holdTokens before the bond is settled loses the whole bond',
|
|
126
|
+
},
|
|
127
|
+
next: [...(num(free) > 0 ? [`gang sell --token ${h.token} --amount ${free}`] : []), ...rest, `gang bond status --token ${h.token}`],
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A bond view (`gang bond status`) → the fields a portfolio shows; null when the token has none. */
|
|
132
|
+
function bondRow(l, b) {
|
|
133
|
+
if (!b || b.state === 'none') return null
|
|
134
|
+
return {
|
|
135
|
+
token: l.address, symbol: l.symbol, state: b.state, bond: b.bond ?? null, quote: b.quote ?? null,
|
|
136
|
+
holdTokens: b.holdTokens ?? null, creatorBalance: b.creatorBalance ?? null, headroomTokens: b.headroomTokens ?? null,
|
|
137
|
+
...(b.violated != null && { violated: b.violated }), ...(b.phase && { phase: b.phase }), deadline: b.deadline ?? null,
|
|
138
|
+
...(b.note && { note: b.note }),
|
|
139
|
+
next: `gang bond status --token ${l.address}`,
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* wallet: 0x address. get(path) → JSON or null (discover.js get). statusOf(kind, token, wallet, position) → the
|
|
145
|
+
* `gang status` result of that kind, or throws (legacy: tokenInfo, or { graduated, myBalanceRaw } for a token no known
|
|
146
|
+
* pad has). bondOf(token) → the `gang bond status` view, or throws.
|
|
147
|
+
*/
|
|
148
|
+
export async function portfolio({ wallet, get, statusOf, bondOf, concurrency = 6 }) {
|
|
149
|
+
const w = wallet.toLowerCase()
|
|
150
|
+
const [profile, positions, launches] = await Promise.all([
|
|
151
|
+
get(`/agents/${w}`),
|
|
152
|
+
get(`/agents/${w}/positions`),
|
|
153
|
+
get(`/agents/${w}/launches?limit=${MAX_LAUNCHES}`),
|
|
154
|
+
])
|
|
155
|
+
if (!Array.isArray(positions?.items)) throw new Error('gang API has no positions at /agents/<addr>/positions')
|
|
156
|
+
|
|
157
|
+
const errors = []
|
|
158
|
+
const rows = await mapLimit(positions.items, concurrency, async (p) => {
|
|
159
|
+
const kind = KIND[p.track]
|
|
160
|
+
if (!kind) return null
|
|
161
|
+
try {
|
|
162
|
+
return holdingOf(p, kind, await statusOf(kind, p.address, wallet, p))
|
|
163
|
+
} catch (e) {
|
|
164
|
+
errors.push({ token: p.address, symbol: p.symbol, error: e.message })
|
|
165
|
+
return null
|
|
166
|
+
}
|
|
167
|
+
})
|
|
168
|
+
// bonds cover GangLaunchpad tokens only (V3 / 打新)
|
|
169
|
+
const ours = (launches?.items ?? []).filter((l) => l.track === 'v3' || l.track === 'fair')
|
|
170
|
+
const views = new Map()
|
|
171
|
+
const bonds = (await mapLimit(ours, concurrency, async (l) => {
|
|
172
|
+
try {
|
|
173
|
+
const b = await bondOf(l.address)
|
|
174
|
+
views.set(l.address.toLowerCase(), b)
|
|
175
|
+
return bondRow(l, b)
|
|
176
|
+
} catch (e) {
|
|
177
|
+
errors.push({ token: l.address, symbol: l.symbol, error: `bond: ${e.message}` })
|
|
178
|
+
return null
|
|
179
|
+
}
|
|
180
|
+
})).filter(Boolean)
|
|
181
|
+
|
|
182
|
+
const holdings = rows.filter(Boolean)
|
|
183
|
+
.map((h) => {
|
|
184
|
+
const b = views.get(h.token.toLowerCase())
|
|
185
|
+
return b?.state === 'active' ? withBond(h, b) : h
|
|
186
|
+
})
|
|
187
|
+
.sort((a, b) => (b.valueUsd ?? -1) - (a.valueUsd ?? -1))
|
|
188
|
+
|
|
189
|
+
const sum = (key) => usd(holdings.reduce((s, h) => s + (h[key] ?? 0), 0))
|
|
190
|
+
const unpriced = holdings.filter((h) => h.valueUsd == null).length
|
|
191
|
+
const t = profile?.trade ?? {}
|
|
192
|
+
const l = profile?.launch ?? {}
|
|
193
|
+
return {
|
|
194
|
+
success: true, wallet, handle: profile?.handle ?? null,
|
|
195
|
+
totals: {
|
|
196
|
+
holdings: holdings.length, valueUsd: sum('valueUsd'), unrealizedUsd: sum('unrealizedUsd'), claimableUsd: sum('claimableUsd'),
|
|
197
|
+
...(unpriced && { unpriced, unpricedNote: 'holdings without a USD value are left out of valueUsd' }),
|
|
198
|
+
},
|
|
199
|
+
holdings,
|
|
200
|
+
record: {
|
|
201
|
+
buys: t.buys ?? null, sells: t.sells ?? null, tokensTraded: t.tokens ?? null, volumeUsd: t.volumeUsd ?? null,
|
|
202
|
+
realizedPnlUsd: t.realizedPnlUsd ?? null, gradHits: t.gradHits ?? null,
|
|
203
|
+
launches: l.count ?? null, launchesGraduated: l.graduated ?? null,
|
|
204
|
+
},
|
|
205
|
+
bonds,
|
|
206
|
+
...(launches?.hasMore && { bondsNote: `bonds were looked up on the newest ${MAX_LAUNCHES} launches only` }),
|
|
207
|
+
...(errors.length && { errors }),
|
|
208
|
+
note: 'Holdings are the tokens gang.fun saw this wallet trade on a curve or sale; balance and value are read on chain now. '
|
|
209
|
+
+ 'Tokens only received by transfer or only bought on PancakeSwap are not listed. USD uses each quote\'s price now. Data, not advice.',
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export const _test = { holdingOf, bondRow, withBond, mapLimit }
|