@gangfun/cli 0.17.4 → 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 +5 -4
- package/README.zh-CN.md +5 -4
- package/package.json +1 -1
- package/src/bond.js +3 -3
- package/src/buyback.js +3 -3
- package/src/chain.js +4 -4
- package/src/fair.js +3 -3
- package/src/gangpad.js +62 -3
- package/src/index.js +44 -4
- package/src/launch.js +3 -3
- package/src/mcp.js +3 -0
- package/src/portfolio.js +224 -0
- package/src/v3.js +3 -3
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`, … |
|
|
@@ -251,7 +252,7 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
|
|
|
251
252
|
|
|
252
253
|
| Var | Meaning |
|
|
253
254
|
|---|---|
|
|
254
|
-
| `GANG_RPC_URL` | BSC HTTP RPC |
|
|
255
|
+
| `GANG_RPC_URL` | BSC HTTP RPC: one URL, or a comma-separated list tried in order. Unset: five public nodes (BNB Chain's dataseed nodes, then PublicNode); a call that fails on one (rate limit, timeout) moves to the next, and later calls start at the one that answered (0.17.5+). A revert is never retried on another node |
|
|
255
256
|
| `GANG_LOGO_API` | Logo upload endpoint (default `https://gang.fun/api/logos`) |
|
|
256
257
|
| `GANG_CDN_BASE` | CDN serving uploads as `<base>/ipfs/<cid>` (default `https://cdn.gang.fun`) |
|
|
257
258
|
| `GANG_API` | Indexer API for discovery and note publishing (default `https://gang.fun/api`) |
|
|
@@ -260,10 +261,10 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
|
|
|
260
261
|
| `GANG_UPDATE_CHECK` | `0` turns off the once-a-day check for a newer CLI on npm (cached in `~/.gang/update.json`) |
|
|
261
262
|
| `GANG_UPDATE_URL` | Where that check asks, default `https://registry.npmjs.org/@gangfun/cli/latest`; set an npm mirror's `…/@gangfun/cli/latest` if npmjs is slow or blocked |
|
|
262
263
|
| `GANG_PAD` / `GANG_TESTNET_PAD` | Override the merged GangLaunchpad (mainnet / testnet) behind V3 and 打新 (defaults: mainnet `0x15CF…4365`, testnet set 10 `0xFebF…5BB1`). Old names `GANG_V3_PAD` / `GANG_FAIR_PAD`, `GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` still work as aliases |
|
|
263
|
-
| `GANG_TESTNET_RPC_URL` | Testnet RPC; old names `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` still work |
|
|
264
|
+
| `GANG_TESTNET_RPC_URL` | Testnet RPC, one URL or a comma list (unset: PublicNode, then BNB Chain's testnet nodes); old names `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` still work |
|
|
264
265
|
| `GANG_BOND` / `GANG_TESTNET_BOND` | GangBond (creator bonds, `gang bond`). Defaults: mainnet `0xe92d…14E4` (since 2026-10-29, CLI 0.16.2+), testnet `0xd6a8…1086` |
|
|
265
266
|
| `GANG_ROUTER` / `GANG_TESTNET_ROUTER` | GangRouter proxy (native-BNB V3 buys / mints, and every PancakeSwap trade of a graduated token); old name `GANG_ROUTER_TESTNET` still works. Defaults: mainnet `0xE040…79C4`, testnet set 10 `0x6bB6…C9F6` |
|
|
266
267
|
|
|
267
268
|
## Version
|
|
268
269
|
|
|
269
|
-
`0.17.
|
|
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` 等 |
|
|
@@ -215,7 +216,7 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
|
|
|
215
216
|
|
|
216
217
|
| 变量 | 含义 |
|
|
217
218
|
|---|---|
|
|
218
|
-
| `GANG_RPC_URL` | BSC RPC |
|
|
219
|
+
| `GANG_RPC_URL` | BSC RPC:填一个地址,或用逗号分隔的多个地址(按顺序使用)。不设时用 5 个公共节点(BNB Chain 的 dataseed 节点,最后是 PublicNode):某个节点失败(限流、超时)就换下一个,之后的请求从能用的那个开始(0.17.5+)。合约 revert 不会换节点重试 |
|
|
219
220
|
| `GANG_LOGO_API` | Logo 上传 API(默认 `https://gang.fun/api/logos`) |
|
|
220
221
|
| `GANG_CDN_BASE` | 上传文件的 CDN,地址为 `<base>/ipfs/<cid>`(默认 `https://cdn.gang.fun`) |
|
|
221
222
|
| `GANG_API` | indexer API,发现命令和公开附言都用它(默认 `https://gang.fun/api`) |
|
|
@@ -224,10 +225,10 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
|
|
|
224
225
|
| `GANG_UPDATE_CHECK` | 设为 `0` 关闭每天一次的新版本检查(查 npm,缓存在 `~/.gang/update.json`) |
|
|
225
226
|
| `GANG_UPDATE_URL` | 新版本检查查询的地址,默认 `https://registry.npmjs.org/@gangfun/cli/latest`;npmjs 慢或打不开时,可以换成 npm 镜像的 `…/@gangfun/cli/latest` |
|
|
226
227
|
| `GANG_PAD` / `GANG_TESTNET_PAD` | 覆盖合并后的内盘合约 GangLaunchpad(主网 / 测试网),V3 和打新共用(默认:主网 `0x15CF…4365`,测试网第 10 套 `0xFebF…5BB1`)。旧名 `GANG_V3_PAD` / `GANG_FAIR_PAD`、`GANG_V3_TESTNET_PAD` / `GANG_FAIR_TESTNET_PAD` 仍可用(别名) |
|
|
227
|
-
| `GANG_TESTNET_RPC_URL` | 测试网 RPC
|
|
228
|
+
| `GANG_TESTNET_RPC_URL` | 测试网 RPC,可填一个或逗号分隔的多个(不设时先用 PublicNode,再用 BNB Chain 的测试网节点);旧名 `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` 仍可用 |
|
|
228
229
|
| `GANG_BOND` / `GANG_TESTNET_BOND` | GangBond(押金承诺,`gang bond`)。默认:主网 `0xe92d…14E4`(2026-10-29 起,CLI 0.16.2+),测试网 `0xd6a8…1086` |
|
|
229
230
|
| `GANG_ROUTER` / `GANG_TESTNET_ROUTER` | GangRouter 代理(用原生 BNB 买 V3 / 打新,以及已毕业币的所有外盘买卖);旧名 `GANG_ROUTER_TESTNET` 仍可用。默认:主网 `0xE040…79C4`,测试网第 10 套 `0x6bB6…C9F6` |
|
|
230
231
|
|
|
231
232
|
## 版本
|
|
232
233
|
|
|
233
|
-
`0.17.
|
|
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.
|
|
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/bond.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { createPublicClient,
|
|
1
|
+
import { createPublicClient, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseUnits, isAddress, zeroAddress } from 'viem'
|
|
2
2
|
import { decimalsOf, fundingStep as fund, parseAmount, parseIntIn, parseNum, revertOf as revertIn, step, units, GAS_RESERVE } from './steps.js'
|
|
3
|
-
import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, padNets } from './gangpad.js'
|
|
3
|
+
import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, padNets, rpcTransport } from './gangpad.js'
|
|
4
4
|
import { bawAddress } from './baw.js'
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -115,7 +115,7 @@ function bondCtx(testnet) {
|
|
|
115
115
|
if (!net.pad) throw new Error(NOT_ON_MAINNET)
|
|
116
116
|
const bond = bondAddress(testnet)
|
|
117
117
|
if (!bond) throw new Error(`GangBond is not deployed on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version: set ${testnet ? 'GANG_TESTNET_BOND' : 'GANG_BOND'} to its address`)
|
|
118
|
-
const client = createPublicClient({ chain: net.chain, transport:
|
|
118
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
119
119
|
return { ...net, bond, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
120
120
|
}
|
|
121
121
|
|
package/src/buyback.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { createPublicClient,
|
|
2
|
-
import { padNets, NOT_ON_MAINNET } from './gangpad.js'
|
|
1
|
+
import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, hexToString, isAddress, zeroAddress } from 'viem'
|
|
2
|
+
import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
3
3
|
import { walletFor } from './fair.js'
|
|
4
4
|
import { parseNum, revertOf as revertIn, step } from './steps.js'
|
|
5
5
|
|
|
@@ -122,7 +122,7 @@ export async function splitterOf(read, addr) {
|
|
|
122
122
|
function buybackCtx(testnet) {
|
|
123
123
|
const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
|
|
124
124
|
if (!net.pad) throw new Error(NOT_ON_MAINNET)
|
|
125
|
-
const client = createPublicClient({ chain: net.chain, transport:
|
|
125
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
126
126
|
return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
127
127
|
}
|
|
128
128
|
|
package/src/chain.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createPublicClient,
|
|
1
|
+
import { createPublicClient, formatEther, parseEther, encodeFunctionData, decodeEventLog, isAddress, zeroAddress } from 'viem'
|
|
2
2
|
import { bsc } from 'viem/chains'
|
|
3
3
|
import { SOFT_ABI, V2_ABI, S_ABI, ERC20_ABI, WBNB_ABI } from './abi.js'
|
|
4
|
-
import { kindOf, padNets } from './gangpad.js'
|
|
4
|
+
import { kindOf, padNets, rpcTransport } from './gangpad.js'
|
|
5
5
|
|
|
6
6
|
export const ADDR = {
|
|
7
7
|
v2: '0x1B8F3f69DFa0a7F63d308C7EB0Fd38D8b099966E',
|
|
@@ -12,11 +12,11 @@ export const ADDR = {
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
export const CONFIG = {
|
|
15
|
-
rpc: process.env.GANG_RPC_URL || 'https://bsc-dataseed.binance.org',
|
|
16
15
|
chainId: '56',
|
|
17
16
|
}
|
|
18
17
|
|
|
19
|
-
|
|
18
|
+
// GANG_RPC_URL or the public nodes (gangpad.js), shared with the GangLaunchpad clients
|
|
19
|
+
export const client = createPublicClient({ chain: bsc, transport: rpcTransport(padNets('v3').mainnet.rpcs) })
|
|
20
20
|
export const fmt = (wei) => formatEther(wei)
|
|
21
21
|
export const fmtTok = (units) => Number(formatEther(units)).toLocaleString('en-US', { maximumFractionDigits: 2 })
|
|
22
22
|
export { parseEther, encodeFunctionData, isAddress, zeroAddress }
|
package/src/fair.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { createPublicClient,
|
|
1
|
+
import { createPublicClient, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseEther, parseUnits, isAddress, zeroAddress } from 'viem'
|
|
2
2
|
import { bawAddress } from './baw.js'
|
|
3
3
|
import { defaultRefPool, dividendOf, fundingStep as fund, parseAmount, parseIntIn, parseNum, poolSellQuote, POOL_SELL_HINT, revertOf as revertIn, ROUTER_ABI, ROUTER_HINTS, routerDeadline, step, swapBackState, units, viaRouter, GAS_RESERVE } from './steps.js'
|
|
4
4
|
import { API } from './discover.js'
|
|
5
5
|
import { UA } from './version.js'
|
|
6
|
-
import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets } from './gangpad.js'
|
|
6
|
+
import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
|
|
7
7
|
import { poolPayBnb, poolTrade } from './pool.js'
|
|
8
8
|
import { bondAddress, bondGuard } from './bond.js'
|
|
9
9
|
|
|
@@ -111,7 +111,7 @@ export const FAIR_EVENT_ABIS = [PAD_ABI, VAULT_ABI]
|
|
|
111
111
|
export function fairCtx(testnet) {
|
|
112
112
|
const net = FAIR_NETS[testnet ? 'testnet' : 'mainnet']
|
|
113
113
|
if (!net.pad) throw new Error(NOT_ON_MAINNET)
|
|
114
|
-
const client = createPublicClient({ chain: net.chain, transport:
|
|
114
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
115
115
|
return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
116
116
|
}
|
|
117
117
|
|
package/src/gangpad.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { parseAbi } from 'viem'
|
|
1
|
+
import { createTransport, http, parseAbi } from 'viem'
|
|
2
2
|
import { bsc, bscTestnet } from 'viem/chains'
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -12,6 +12,7 @@ import { bsc, bscTestnet } from 'viem/chains'
|
|
|
12
12
|
* testnet: GANG_TESTNET_PAD (aliases GANG_V3_TESTNET_PAD / GANG_FAIR_TESTNET_PAD),
|
|
13
13
|
* GANG_TESTNET_ROUTER (alias GANG_ROUTER_TESTNET),
|
|
14
14
|
* GANG_TESTNET_RPC_URL (aliases GANG_V3_TESTNET_RPC_URL / GANG_FAIR_TESTNET_RPC_URL)
|
|
15
|
+
* An RPC variable takes one URL or a comma-separated list; set, it replaces the public nodes below.
|
|
15
16
|
*/
|
|
16
17
|
|
|
17
18
|
// the current testnet set (set 10, 2026-10-27: §23 aggregator entries); the name is kept from set 8
|
|
@@ -29,6 +30,64 @@ const TESTNET_SET7 = {
|
|
|
29
30
|
router: '0x9dBb3D25Ff5c8107814fBD96A88D6eD015dfA279',
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
// Public BSC nodes, tried in this order (2026-10-30: each answered eth_call with revert data, tx and receipt reads).
|
|
34
|
+
// Several operators, so one node's rate limit or outage does not stop a preview.
|
|
35
|
+
export const MAINNET_RPCS = [
|
|
36
|
+
'https://bsc-dataseed.binance.org', 'https://bsc-dataseed.bnbchain.org', 'https://bsc-dataseed1.defibit.io',
|
|
37
|
+
'https://bsc-dataseed1.ninicoin.io', 'https://bsc-rpc.publicnode.com',
|
|
38
|
+
]
|
|
39
|
+
// publicnode first: the data-seed nodes keep little state and answer `missing trie node` sooner
|
|
40
|
+
export const TESTNET_RPCS = [
|
|
41
|
+
'https://bsc-testnet-rpc.publicnode.com', 'https://bsc-testnet.bnbchain.org',
|
|
42
|
+
'https://data-seed-prebsc-1-s1.bnbchain.org:8545', 'https://data-seed-prebsc-2-s1.bnbchain.org:8545',
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
/** An RPC variable's value → its URLs (one, or a comma-separated list), or null when unset / empty. */
|
|
46
|
+
export const rpcList = (v) => {
|
|
47
|
+
const urls = (v ?? '').split(',').map((s) => s.trim()).filter(Boolean)
|
|
48
|
+
return urls.length ? urls : null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// what every node would answer alike: the contract's revert, gas or funds the call lacks. Thrown at once, not retried
|
|
52
|
+
const SAME_ON_EVERY_NODE = /execution reverted|gas required exceeds allowance|insufficient funds/i
|
|
53
|
+
const sameOnEveryNode = (e) => e?.code === 3 || SAME_ON_EVERY_NODE.test(e?.details ?? '')
|
|
54
|
+
// list → the index of the node that answered last; the next call (of any client on that list) starts there
|
|
55
|
+
const lastGood = new Map()
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* viem transport over a list of nodes. A call goes to the node that answered last and moves down the list when it
|
|
59
|
+
* fails (rate limit, timeout, the node's own error), so a dead node costs one timeout, not one per call. A revert is the
|
|
60
|
+
* contract's answer and is thrown as it is. One URL: plain http with viem's retries, as before. (viem's fallback()
|
|
61
|
+
* starts every call at the first node, and its ranking keeps a timer that holds the process open.)
|
|
62
|
+
*/
|
|
63
|
+
export function rpcTransport(urls) {
|
|
64
|
+
if (urls.length === 1) return http(urls[0])
|
|
65
|
+
const key = urls.join(',')
|
|
66
|
+
const nodes = urls.map((u) => http(u, { retryCount: 0, timeout: 8_000 }))
|
|
67
|
+
return ({ chain }) => {
|
|
68
|
+
const live = nodes.map((n) => n({ chain }))
|
|
69
|
+
return createTransport({
|
|
70
|
+
key: 'gang', name: 'Gang RPC', type: 'gang', retryCount: 1,
|
|
71
|
+
async request({ method, params }) {
|
|
72
|
+
const first = lastGood.get(key) ?? 0
|
|
73
|
+
let error
|
|
74
|
+
for (let k = 0; k < live.length; k++) {
|
|
75
|
+
const i = (first + k) % live.length
|
|
76
|
+
try {
|
|
77
|
+
const r = await live[i].request({ method, params })
|
|
78
|
+
lastGood.set(key, i)
|
|
79
|
+
return r
|
|
80
|
+
} catch (e) {
|
|
81
|
+
if (sameOnEveryNode(e)) throw e
|
|
82
|
+
error = e
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
throw error
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
32
91
|
const env = (...names) => {
|
|
33
92
|
for (const n of names) if (process.env[n]) return process.env[n]
|
|
34
93
|
return null
|
|
@@ -43,7 +102,7 @@ export function padNets(kind) {
|
|
|
43
102
|
mainnet: {
|
|
44
103
|
chainId: '56', chain: bsc,
|
|
45
104
|
pad: env('GANG_PAD', `GANG_${alias}_PAD`) || MAINNET_GANG.pad || null,
|
|
46
|
-
|
|
105
|
+
rpcs: rpcList(env('GANG_RPC_URL')) || MAINNET_RPCS,
|
|
47
106
|
wbnb: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', explorer: 'https://bscscan.com',
|
|
48
107
|
router: env('GANG_ROUTER') || MAINNET_GANG.router || null,
|
|
49
108
|
},
|
|
@@ -51,7 +110,7 @@ export function padNets(kind) {
|
|
|
51
110
|
chainId: '97', chain: bscTestnet,
|
|
52
111
|
pad: env('GANG_TESTNET_PAD', `GANG_${alias}_TESTNET_PAD`) || set.pad,
|
|
53
112
|
router: env('GANG_TESTNET_ROUTER', 'GANG_ROUTER_TESTNET') || set.router || null,
|
|
54
|
-
|
|
113
|
+
rpcs: rpcList(env('GANG_TESTNET_RPC_URL', `GANG_${alias}_TESTNET_RPC_URL`)) || TESTNET_RPCS,
|
|
55
114
|
wbnb: '0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd', explorer: 'https://testnet.bscscan.com',
|
|
56
115
|
},
|
|
57
116
|
}
|
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
|
|
@@ -396,8 +401,8 @@ A buy / sell / create preview without --note says so in agentNote.hint (also gan
|
|
|
396
401
|
update: { current, latest, cmd, skill } (npm is asked at most once a day in the background; GANG_UPDATE_CHECK=0 turns it
|
|
397
402
|
off, GANG_UPDATE_URL points it at an npm mirror).
|
|
398
403
|
|
|
399
|
-
env: GANG_RPC_URL
|
|
400
|
-
GANG_UPDATE_CHECK, GANG_UPDATE_URL,
|
|
404
|
+
env: GANG_RPC_URL (one URL or a comma list; unset: five public BSC nodes, the next one tried when one fails),
|
|
405
|
+
GANG_LOGO_API, GANG_API (default ${API}), GANG_NOTES_DIR (default ~/.gang/notes), GANG_UPDATE_CHECK, GANG_UPDATE_URL,
|
|
401
406
|
GANG_PAD / GANG_TESTNET_PAD (the one GangLaunchpad behind both gang v3 and gang fair; old names GANG_V3_PAD / GANG_FAIR_PAD
|
|
402
407
|
and GANG_V3_TESTNET_PAD / GANG_FAIR_TESTNET_PAD still work as aliases), GANG_TESTNET_RPC_URL (aliases
|
|
403
408
|
GANG_V3_TESTNET_RPC_URL / GANG_FAIR_TESTNET_RPC_URL), GANG_ROUTER / GANG_TESTNET_ROUTER (alias GANG_ROUTER_TESTNET; GangRouter
|
|
@@ -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/launch.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto'
|
|
2
2
|
import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
3
3
|
import { dirname, join } from 'node:path'
|
|
4
|
-
import { createPublicClient,
|
|
4
|
+
import { createPublicClient, parseAbi, formatUnits, encodeFunctionData, isAddress, zeroAddress } from 'viem'
|
|
5
5
|
import { DIR } from './notes.js'
|
|
6
|
-
import { padNets, NOT_ON_MAINNET } from './gangpad.js'
|
|
6
|
+
import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
7
7
|
import { bondAddress, BOND_ABI } from './bond.js'
|
|
8
8
|
import { walletFor } from './fair.js'
|
|
9
9
|
import { parseAmount, parseIntIn, step } from './steps.js'
|
|
@@ -154,7 +154,7 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
|
|
|
154
154
|
buyback = { bps: buybackBpsOf(fail, opt('buyback')), factory, payee }
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
-
const client = createPublicClient({ chain: net.chain, transport:
|
|
157
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
158
158
|
const read = (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args })
|
|
159
159
|
const me = walletFor({ chainId: net.chainId }, opt('from'))
|
|
160
160
|
const key = [net.chainId, net.pad, me.toLowerCase(), kind, name, symbol].join('|')
|
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,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 }
|
package/src/v3.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { createPublicClient,
|
|
1
|
+
import { createPublicClient, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseUnits, isAddress, zeroAddress } from 'viem'
|
|
2
2
|
import { decimalsOf, defaultRefPool, dividendOf, VAULT_ABI, fundingStep as fund, parseAmount, parseNum, poolSellQuote, POOL_SELL_HINT, revertOf as revertIn, ROUTER_ABI as GANG_ROUTER_ABI, ROUTER_HINTS, routerDeadline, step, swapBackState, units, viaRouter, GAS_RESERVE } from './steps.js'
|
|
3
3
|
import { API } from './discover.js'
|
|
4
4
|
import { UA } from './version.js'
|
|
5
5
|
import { walletFor } from './fair.js'
|
|
6
|
-
import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets } from './gangpad.js'
|
|
6
|
+
import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
|
|
7
7
|
import { poolPayBnb, poolTrade } from './pool.js'
|
|
8
8
|
import { bondGuard } from './bond.js'
|
|
9
9
|
import { splitterOf } from './buyback.js'
|
|
@@ -98,7 +98,7 @@ export const V3_EVENT_ABIS = [PAD_ABI, TAX_ROUTER_ABI, VAULT_ABI]
|
|
|
98
98
|
export function v3Ctx(testnet) {
|
|
99
99
|
const net = V3_NETS[testnet ? 'testnet' : 'mainnet']
|
|
100
100
|
if (!net.pad) throw new Error(NOT_ON_MAINNET)
|
|
101
|
-
const client = createPublicClient({ chain: net.chain, transport:
|
|
101
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
102
102
|
return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
103
103
|
}
|
|
104
104
|
|