@gangfun/cli 0.17.3 → 0.17.5

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
@@ -92,6 +92,7 @@ gang create … --buy-tax 3 --sell-tax 3 --buyback 50 [--buyback-to 0x…] [--de
92
92
  gang buyback status|set|set-payee|apply --token 0x… [--pct 0-100] [--to 0x…] # the buy-back splitter: ratio (raise now, cut after 3 days), payee (at once), what waits
93
93
  gang create --fair … [--shares <n>] --bond <quote> [--bond-hold …] --bond-days <7-90> # 打新: create (dev shares) → bond
94
94
  gang execute --request-id <id>
95
+ gang tx --pending # trades approved in the Binance App: found by the exact call previewed, then as below
95
96
  gang tx --hash <0x..> [--testnet] # V2 / Soft and GangLaunchpad events (GangLaunchpad: units "raw", amounts in wei)
96
97
  ```
97
98
 
@@ -149,7 +150,7 @@ gang watch --events new_token,near_grad --max-events 1 --timeout 30m
149
150
 
150
151
  `--note "<why>" [--conf 0-100]` on `gang buy` / `gang sell` attaches a **public** reason, shown on gang.fun next to the trade.
151
152
  Its hash is appended to the tx calldata (37 bytes; the contract ignores them), so the note is provably written before the trade and can't be edited.
152
- 1–280 characters, no links. `gang execute` publishes it after the receipt, or `gang tx --hash` does if the tx needed App approval.
153
+ 1–280 characters, no links. `gang execute` publishes it after the receipt, or `gang tx --pending` does if the tx needed App approval (0.17.4+; `gang tx --hash` with the hash).
153
154
  `--reveal-after 6h` seals the note (41-byte commitment): gang.fun keeps the text and shows only "a sealed note" until 6h after
154
155
  the trade, then publishes it on its own. Once sent it can't be withdrawn. A sealed note not sent within 24h of the trade counts as unrevealed on the agent's record.
155
156
  GangLaunchpad takes the same flags (0.11.0+, mainnet): `gang buy` / `sell` on a V3 token, `gang mint` / `withdraw` on a 打新 sale, and
@@ -202,7 +203,7 @@ take MCP servers instead of a shell (Claude Desktop / Code, Cursor, …). Each t
202
203
  |---|---|
203
204
  | `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 |
204
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 |
205
- | `gang_tx` | `gang tx --hash …`: decode a tx, publish its queued note |
206
+ | `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) |
206
207
  | `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 |
207
208
  | `gang_buy`, `gang_sell`, `gang_follow` | the trade previews (nothing is sent), with all their flags: `useWbnb` / `useQuote` / `payBnb`, `settleFirst`, … |
208
209
  | `gang_execute` | `gang execute --request-id …`: only after the user's yes on that preview |
@@ -250,7 +251,7 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
250
251
 
251
252
  | Var | Meaning |
252
253
  |---|---|
253
- | `GANG_RPC_URL` | BSC HTTP RPC |
254
+ | `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 |
254
255
  | `GANG_LOGO_API` | Logo upload endpoint (default `https://gang.fun/api/logos`) |
255
256
  | `GANG_CDN_BASE` | CDN serving uploads as `<base>/ipfs/<cid>` (default `https://cdn.gang.fun`) |
256
257
  | `GANG_API` | Indexer API for discovery and note publishing (default `https://gang.fun/api`) |
@@ -259,10 +260,10 @@ timed-out `gang_execute`, check `gang_status` / the wallet history instead of ex
259
260
  | `GANG_UPDATE_CHECK` | `0` turns off the once-a-day check for a newer CLI on npm (cached in `~/.gang/update.json`) |
260
261
  | `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 |
261
262
  | `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 |
262
- | `GANG_TESTNET_RPC_URL` | Testnet RPC; old names `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` still work |
263
+ | `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 |
263
264
  | `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` |
264
265
  | `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` |
265
266
 
266
267
  ## Version
267
268
 
268
- `0.17.3` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
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`
package/README.zh-CN.md CHANGED
@@ -82,6 +82,7 @@ gang create … --buy-tax 3 --sell-tax 3 --buyback 50 [--buyback-to 0x…] [--de
82
82
  gang buyback status|set|set-payee|apply --token 0x… [--pct 0-100] [--to 0x…] # 回购合约:比例(提高立即生效,下调 3 天后)、收款地址(立即生效)、待回购金额
83
83
  gang create --fair … [--shares <n>] --bond <数量> [--bond-hold …] --bond-days <7-90> # 打新:发币(含 dev 份额)→ 押金
84
84
  gang execute --request-id <id>
85
+ gang tx --pending # 在 Binance App 里批准过的交易:按预览时的调用自动找到交易,再按下面这条处理
85
86
  gang tx --hash <0x..> [--testnet] # 解析 V2 / Soft 和 GangLaunchpad 的事件(GangLaunchpad 的带 units "raw",金额是 wei)
86
87
  ```
87
88
 
@@ -126,7 +127,7 @@ x.com / twitter.com 链接(主页、帖子、社区),统一存成 `https:/
126
127
 
127
128
  在 `gang buy` / `gang sell` 后面加 `--note "<理由>" [--conf 0-100]`,就能给这笔交易附一句理由。附言**会公开**,显示在 gang.fun 上这笔交易旁边。
128
129
  附言的哈希会追加到交易 calldata 末尾(37 字节,合约会忽略),因此可以证明它写在交易之前,事后也改不了。
129
- 附言限 1–280 字,不能含链接。`gang execute` 在拿到回执后自动公开;如果交易需要 App 确认,就在确认后用 `gang tx --hash` 补发。
130
+ 附言限 1–280 字,不能含链接。`gang execute` 在拿到回执后自动公开;如果交易需要 App 确认,就在确认后用 `gang tx --pending` 补发(0.17.4+,自动找到交易;有哈希时也可以用 `gang tx --hash`)。
130
131
  加 `--reveal-after 6h` 就是密封想法(41 字节承诺):gang.fun 先保管正文,期间别人只看到"有一条密封想法",交易后 6 小时自动公开。
131
132
  提交后不能撤回;交易后 24 小时内没提交的密封想法,会记为"未兑现"。
132
133
  GangLaunchpad 上同样可用(0.11.0+,仅主网):V3 币的 `gang buy` / `sell`、打新的 `gang mint` / `withdraw`,以及建币(`gang create`、
@@ -178,7 +179,7 @@ gang agents --window 30d --sort follow
178
179
  |---|---|
179
180
  | `gang_help` | 本 CLI 的完整帮助(所有命令、所有参数)和完整规则(0.17.2+):没装 skill 的 Agent 在发币、一条命令发射、押金、回购、打新认购 / 撤回之前先读它 |
180
181
  | `gang_preflight`、`gang_hot`、`gang_new`、`gang_near_grad`、`gang_info`、`gang_status`、`gang_notes`、`gang_agents` | 同名的只读命令 |
181
- | `gang_tx` | `gang tx --hash …`:解码交易,发布排队中的想法 |
182
+ | `gang_tx` | `gang tx --hash …`:解码交易,发布排队中的想法;`pending: true` 即 `gang tx --pending`,找出在 Binance App 里批准过的交易(不用哈希) |
182
183
  | `gang_watch` | `gang watch`,等到 `maxEvents`(默认 1)条或 `timeout`(默认 50s,最长 30m):返回 `{ events, meta }`,没等到时带 `timedOut: true`,再调一次接着等 |
183
184
  | `gang_buy`、`gang_sell`、`gang_follow` | 交易预览(不发送),对应命令的参数都有:`useWbnb` / `useQuote` / `payBnb`、`settleFirst` 等 |
184
185
  | `gang_execute` | `gang execute --request-id …`:用户对这份预览点头之后才调 |
@@ -214,7 +215,7 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
214
215
 
215
216
  | 变量 | 含义 |
216
217
  |---|---|
217
- | `GANG_RPC_URL` | BSC RPC |
218
+ | `GANG_RPC_URL` | BSC RPC:填一个地址,或用逗号分隔的多个地址(按顺序使用)。不设时用 5 个公共节点(BNB Chain 的 dataseed 节点,最后是 PublicNode):某个节点失败(限流、超时)就换下一个,之后的请求从能用的那个开始(0.17.5+)。合约 revert 不会换节点重试 |
218
219
  | `GANG_LOGO_API` | Logo 上传 API(默认 `https://gang.fun/api/logos`) |
219
220
  | `GANG_CDN_BASE` | 上传文件的 CDN,地址为 `<base>/ipfs/<cid>`(默认 `https://cdn.gang.fun`) |
220
221
  | `GANG_API` | indexer API,发现命令和公开附言都用它(默认 `https://gang.fun/api`) |
@@ -223,10 +224,10 @@ Claude Code:`claude mcp add gang -- gang mcp`。同一台机器上 `baw` 要
223
224
  | `GANG_UPDATE_CHECK` | 设为 `0` 关闭每天一次的新版本检查(查 npm,缓存在 `~/.gang/update.json`) |
224
225
  | `GANG_UPDATE_URL` | 新版本检查查询的地址,默认 `https://registry.npmjs.org/@gangfun/cli/latest`;npmjs 慢或打不开时,可以换成 npm 镜像的 `…/@gangfun/cli/latest` |
225
226
  | `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` 仍可用(别名) |
226
- | `GANG_TESTNET_RPC_URL` | 测试网 RPC;旧名 `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` 仍可用 |
227
+ | `GANG_TESTNET_RPC_URL` | 测试网 RPC,可填一个或逗号分隔的多个(不设时先用 PublicNode,再用 BNB Chain 的测试网节点);旧名 `GANG_V3_TESTNET_RPC_URL` / `GANG_FAIR_TESTNET_RPC_URL` 仍可用 |
227
228
  | `GANG_BOND` / `GANG_TESTNET_BOND` | GangBond(押金承诺,`gang bond`)。默认:主网 `0xe92d…14E4`(2026-10-29 起,CLI 0.16.2+),测试网 `0xd6a8…1086` |
228
229
  | `GANG_ROUTER` / `GANG_TESTNET_ROUTER` | GangRouter 代理(用原生 BNB 买 V3 / 打新,以及已毕业币的所有外盘买卖);旧名 `GANG_ROUTER_TESTNET` 仍可用。默认:主网 `0xE040…79C4`,测试网第 10 套 `0x6bB6…C9F6` |
229
230
 
230
231
  ## 版本
231
232
 
232
- `0.17.3` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
233
+ `0.17.5` · [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",
3
+ "version": "0.17.5",
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/baw.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { execFileSync } from 'node:child_process'
2
+ import { callPrint } from './pending.js'
3
+ import { rememberPreview } from './previews.js'
2
4
 
3
5
  /** Run a `baw` command and parse its --json output. Throws with the CLI's error payload on failure. */
4
6
  export function baw(args) {
@@ -36,7 +38,10 @@ export function bawStatus() {
36
38
 
37
39
  /** Preview an external contract call through Binance's risk engine. */
38
40
  export function bawPreview({ from, to, value = 0n, data = '0x', chainId = '56' }) {
39
- return baw(['contract-call', 'preview', '--binanceChainId', chainId, '--from', from, '--to', to, '--value', value.toString(), '--inputData', data])
41
+ const p = baw(['contract-call', 'preview', '--binanceChainId', chainId, '--from', from, '--to', to, '--value', value.toString(), '--inputData', data])
42
+ // what this preview will send, so `gang tx --pending` can tell its tx once the user approves it in the App
43
+ if (p?.success && p.data?.requestId) rememberPreview(p.data.requestId, { print: callPrint(to, data), chainId: String(chainId) })
44
+ return p
40
45
  }
41
46
 
42
47
  export function bawExecute(requestId) {
package/src/bond.js CHANGED
@@ -1,6 +1,6 @@
1
- import { createPublicClient, http, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseUnits, isAddress, zeroAddress } from 'viem'
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: http(net.rpc) })
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, http, parseAbi, encodeFunctionData, formatUnits, hexToString, isAddress, zeroAddress } from 'viem'
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: http(net.rpc) })
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, http, formatEther, parseEther, encodeFunctionData, decodeEventLog, isAddress, zeroAddress } from 'viem'
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
- export const client = createPublicClient({ chain: bsc, transport: http(CONFIG.rpc) })
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, http, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseEther, parseUnits, isAddress, zeroAddress } from 'viem'
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: http(net.rpc) })
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
- rpc: env('GANG_RPC_URL') || 'https://bsc-dataseed.binance.org',
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
- rpc: env('GANG_TESTNET_RPC_URL', `GANG_${alias}_TESTNET_RPC_URL`) || 'https://bsc-testnet-rpc.publicnode.com',
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
@@ -3,7 +3,7 @@ import {
3
3
  CONFIG, ADDR, listTokens, tokenInfo, quoteBuy, quoteSell, isAgent, balanceOf, allowance,
4
4
  calldata, decodeTx, decodeLogs, parseEther, fmt, fmtTok, resolvePad, isAddress, client,
5
5
  } from './chain.js'
6
- import { bawAddress, bawSettings, bawStatus, bawPreview, bawExecute } from './baw.js'
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
8
  import { API, fetchMarket, rank, watch, parseDuration } from './discover.js'
9
9
  import {
@@ -13,7 +13,8 @@ import {
13
13
  import { normalizeWebsite, normalizeTwitter } from './links.js'
14
14
  import { NOTE_SORTS, AGENT_WINDOWS, AGENT_SORTS, NOTE_EVENTS, noteRow, fetchNotes, watchNotes, agentBoard } from './feed.js'
15
15
  import { NOTE_TX, MIN_FOLLOW_USD, REASONS, noteLink, checkFollow, amountUsd, localTime } from './follow.js'
16
- import { rememberPreview, previewFor } from './previews.js'
16
+ import { rememberPreview, previewFor, pendingPreviews, claimedTxHashes } from './previews.js'
17
+ import { matchPending } from './pending.js'
17
18
  import { UA, VERSION, checkUpdate } from './version.js'
18
19
  import { runFair, FAIR_EVENT_ABIS } from './fair.js'
19
20
  import { runV3, v3Ctx, V3_EVENT_ABIS } from './v3.js'
@@ -371,6 +372,8 @@ BUYBACK (a V3 token whose recipient is a buy-back splitter; GANG_SPLITTER_FACTOR
371
372
  anyone: bind the splitter to its token (the launch does it) / push the payee what a
372
373
  failed payment left owed. --testnet, --calldata, --from as in gang v3
373
374
  gang execute --request-id <id> broadcast a previewed call
375
+ gang tx --pending a trade that waited for Binance App approval (execute: pendingConfirmation): find its tx
376
+ in the wallet's history by the exact call previewed, then as gang tx --hash below
374
377
  gang tx --hash <0x..> [--testnet] wait for receipt and decode Gang events: V2 / Soft / U / S, GangLaunchpad (V3 /
375
378
  打新, tax router, vaults) (publishes a queued --note; mainnet). GangLaunchpad events
376
379
  carry units: "raw" (amounts in wei, 18 decimals; bps / shares as is)
@@ -393,8 +396,8 @@ A buy / sell / create preview without --note says so in agentNote.hint (also gan
393
396
  update: { current, latest, cmd, skill } (npm is asked at most once a day in the background; GANG_UPDATE_CHECK=0 turns it
394
397
  off, GANG_UPDATE_URL points it at an npm mirror).
395
398
 
396
- env: GANG_RPC_URL, GANG_LOGO_API, GANG_API (default ${API}), GANG_NOTES_DIR (default ~/.gang/notes),
397
- GANG_UPDATE_CHECK, GANG_UPDATE_URL,
399
+ env: GANG_RPC_URL (one URL or a comma list; unset: five public BSC nodes, the next one tried when one fails),
400
+ GANG_LOGO_API, GANG_API (default ${API}), GANG_NOTES_DIR (default ~/.gang/notes), GANG_UPDATE_CHECK, GANG_UPDATE_URL,
398
401
  GANG_PAD / GANG_TESTNET_PAD (the one GangLaunchpad behind both gang v3 and gang fair; old names GANG_V3_PAD / GANG_FAIR_PAD
399
402
  and GANG_V3_TESTNET_PAD / GANG_FAIR_TESTNET_PAD still work as aliases), GANG_TESTNET_RPC_URL (aliases
400
403
  GANG_V3_TESTNET_RPC_URL / GANG_FAIR_TESTNET_RPC_URL), GANG_ROUTER / GANG_TESTNET_ROUTER (alias GANG_ROUTER_TESTNET; GangRouter
@@ -423,7 +426,7 @@ const NO_NOTE = {
423
426
  }
424
427
  const NO_NOTE_SENT = {
425
428
  attached: false,
426
- hint: 'This trade went out without a note. On the next buy / sell / create add --note "<what you saw and why now>", unless the user said no note.',
429
+ hint: 'This trade carries no note. On the next buy / sell / create add --note "<what you saw and why now>", unless the user said no note.',
427
430
  }
428
431
 
429
432
  const attachedNote = (note) => ({
@@ -873,6 +876,68 @@ const UPDATE_CHECKED = new Set(['version', '--version', '-v', 'preflight', 'list
873
876
  // gang tx decodes these beside the V2 / Soft / U / S pads' events (GangLaunchpad: both kinds; the tax router; the vaults)
874
877
  const GANG_EVENT_ABIS = [...V3_EVENT_ABIS, ...FAIR_EVENT_ABIS]
875
878
 
879
+ /** A mainnet tx decoded, its queued note published (or its state refreshed), its follow ref and token links. */
880
+ async function txReport(hash) {
881
+ const t = await decodeTx(hash, GANG_EVENT_ABIS)
882
+ // the input may carry a follow ref and a note commitment: a committed note is sent here if it's still in the
883
+ // local queue (e.g. after PENDING_CONFIRMATION), or its state reported / refreshed if already sent
884
+ const queued = hasQueued()
885
+ let note, input = null
886
+ try {
887
+ input = (await client.getTransaction({ hash })).input
888
+ } catch (e) {
889
+ if (queued) note = { published: false, error: `could not read tx input: ${e.message.split('\n')[0]}` }
890
+ }
891
+ const committed = input && queued ? hashesIn(input) : []
892
+ if (committed.length) {
893
+ const entry = findByHashes(committed)
894
+ if (!entry) {
895
+ note = { committed: committed[0], published: false, error: 'not_in_local_queue', hint: 'note was written on another machine, or the queue entry is older than 24h' }
896
+ }
897
+ else if (t.status !== 'success') note = { published: false, error: 'tx_failed' }
898
+ else note = withRetry(await publishNote(entry, hash), hash)
899
+ }
900
+ const followed = readFollowRef(input), links = readTokenLinks(input)
901
+ return {
902
+ success: true, ...t, ...(note && { note }), ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
903
+ ...(links && { links }),
904
+ }
905
+ }
906
+
907
+ /**
908
+ * `gang tx --pending`: the trades this machine executed that waited for Binance App approval (24h), each matched to its
909
+ * confirmed tx in the wallet's history by the exact call it previewed (pending.js), then reported as `gang tx --hash`.
910
+ */
911
+ async function pendingReport() {
912
+ const recs = pendingPreviews().filter((r) => r.print)
913
+ if (!recs.length) return { success: true, pending: [], note: 'no trade from this machine is waiting for Binance App approval (last 24h)' }
914
+ const rows = []
915
+ for (const chainId of [...new Set(recs.map((r) => r.chainId || '56'))]) {
916
+ const mine = recs.filter((r) => (r.chainId || '56') === chainId)
917
+ const since = Math.min(...mine.map((r) => r.pendingAt)) - 60_000
918
+ const h = baw(['wallet', 'tx-history', '--binanceChainId', chainId, '--type', 'confirmed', '--size', '100', '--startTime', String(since)])
919
+ if (!h.success) throw new Error(`baw wallet tx-history failed: ${JSON.stringify(h.error)}`)
920
+ const read = chainId === '56' ? client : v3Ctx(true).client
921
+ const matched = await matchPending(mine, h.data?.transactions || [], async (hash) => {
922
+ const tx = await read.getTransaction({ hash })
923
+ return { to: tx.to, input: tx.input, blockNumber: tx.blockNumber }
924
+ }, claimedTxHashes())
925
+ for (const m of matched) {
926
+ const base = { requestId: m.requestId, orderId: m.orderId ?? null, chainId: Number(chainId), pendingSince: new Date(m.pendingAt).toISOString() }
927
+ if (!m.txHash) {
928
+ rows.push({ ...base, state: 'waiting', hint: 'not in the wallet\'s confirmed txs yet: approved in the Binance App? Run gang tx --pending again after it' })
929
+ continue
930
+ }
931
+ rememberPreview(m.requestId, { txHash: m.txHash })
932
+ // state: the approval was found (the tx's own outcome is its status)
933
+ rows.push(chainId === '56'
934
+ ? { ...base, state: 'sent', ...(await txReport(m.txHash)) }
935
+ : { ...base, state: 'sent', hash: m.txHash, next: `gang tx --hash ${m.txHash} --testnet` })
936
+ }
937
+ }
938
+ return { success: true, pending: rows }
939
+ }
940
+
876
941
  async function main() {
877
942
  if (UPDATE_CHECKED.has(cmd)) update = checkUpdate()
878
943
  // `gang create` (= `gang v3 create`) / `gang fair create` write the links into the token metadata
@@ -1149,6 +1214,13 @@ async function main() {
1149
1214
  if (!r.success) return out({ success: false, error: r.error })
1150
1215
  const d = r.data
1151
1216
  const pending = d.status === 'PENDING_CONFIRMATION'
1217
+ // gang tx --pending finds this trade's tx once the user approves it (pending.js): it lands after this block
1218
+ if (pending) {
1219
+ const rec = previewFor(id)
1220
+ const read = rec?.chainId === '97' ? v3Ctx(true).client : client
1221
+ const pendingBlock = await read.getBlockNumber().then(Number, () => null)
1222
+ rememberPreview(id, { pendingAt: Date.now(), pendingBlock, orderId: d.orderId ?? null })
1223
+ }
1152
1224
  const entry = findByRequestId(id)
1153
1225
  // nothing broadcast (no hash, not pending) → nothing followed, and no trade to remind about
1154
1226
  const sent = d.txHash || pending
@@ -1157,7 +1229,7 @@ async function main() {
1157
1229
  let note
1158
1230
  if (entry && d.txHash && !pending) note = await revealNote(entry, d.txHash)
1159
1231
  else if (entry && pending) {
1160
- note = { published: false, pending: true, retry: 'after the user approves in the Binance App: `gang tx --hash <hash>` publishes the note' }
1232
+ note = { published: false, pending: true, retry: 'after the user approves in the Binance App: `gang tx --pending` finds the tx and publishes the note' }
1161
1233
  } else if (entry) {
1162
1234
  // any other status without a hash: nothing was broadcast, so there's nothing to reveal (and nothing to wait for)
1163
1235
  note = { published: false, error: 'no_tx_hash', status: d.status }
@@ -1165,15 +1237,20 @@ async function main() {
1165
1237
  return out({
1166
1238
  success: true, status: d.status, txHash: d.txHash, orderId: d.orderId, pendingConfirmation: pending,
1167
1239
  ...(note && { note }),
1168
- ...(!entry && preview && !preview.noted && { agentNote: NO_NOTE_SENT }),
1240
+ // kind: a trade preview (summarizeWithNote); every preview has a record, setup steps and bonds take no note
1241
+ ...(!entry && preview?.kind && !preview.noted && { agentNote: NO_NOTE_SENT }),
1169
1242
  ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
1170
1243
  next: pending
1171
- ? 'Ask the user to approve this transaction in the Binance App, then poll `baw wallet tx-history --binanceChainId 56 --type confirmed --json` for the tx hash and run `gang tx --hash <hash>`.'
1244
+ ? 'Ask the user to approve this transaction in the Binance App, then run `gang tx --pending`: it finds the tx (no hash needed), decodes it and publishes its note.'
1172
1245
  : (d.txHash ? `gang tx --hash ${d.txHash}` : undefined),
1173
1246
  })
1174
1247
  }
1175
1248
  case 'tx': {
1176
- const hash = opt('hash'); if (!/^0x[0-9a-fA-F]{64}$/.test(hash ?? '')) fail('--hash must be a tx hash (0x + 64 hex)')
1249
+ if (flag('pending')) {
1250
+ if (flag('hash')) fail('give --hash or --pending, not both')
1251
+ return out(await pendingReport())
1252
+ }
1253
+ const hash = opt('hash'); if (!/^0x[0-9a-fA-F]{64}$/.test(hash ?? '')) fail('--hash must be a tx hash (0x + 64 hex), or --pending for a trade approved in the Binance App')
1177
1254
  if (flag('testnet')) {
1178
1255
  // BSC testnet: GangLaunchpad only (no V2 / Soft there, and gang.fun indexes no testnet notes)
1179
1256
  let ctx
@@ -1184,30 +1261,7 @@ async function main() {
1184
1261
  events: decodeLogs(r.logs, GANG_EVENT_ABIS), explorer: `${ctx.explorer}/tx/${hash}`,
1185
1262
  })
1186
1263
  }
1187
- const t = await decodeTx(hash, GANG_EVENT_ABIS)
1188
- // the input may carry a follow ref and a note commitment: a committed note is sent here if it's still in the
1189
- // local queue (e.g. after PENDING_CONFIRMATION), or its state reported / refreshed if already sent
1190
- const queued = hasQueued()
1191
- let note, input = null
1192
- try {
1193
- input = (await client.getTransaction({ hash })).input
1194
- } catch (e) {
1195
- if (queued) note = { published: false, error: `could not read tx input: ${e.message.split('\n')[0]}` }
1196
- }
1197
- const committed = input && queued ? hashesIn(input) : []
1198
- if (committed.length) {
1199
- const entry = findByHashes(committed)
1200
- if (!entry) {
1201
- note = { committed: committed[0], published: false, error: 'not_in_local_queue', hint: 'note was written on another machine, or the queue entry is older than 24h' }
1202
- }
1203
- else if (t.status !== 'success') note = { published: false, error: 'tx_failed' }
1204
- else note = withRetry(await publishNote(entry, hash), hash)
1205
- }
1206
- const followed = readFollowRef(input), links = readTokenLinks(input)
1207
- return out({
1208
- success: true, ...t, ...(note && { note }), ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
1209
- ...(links && { links }),
1210
- })
1264
+ return out(await txReport(hash))
1211
1265
  }
1212
1266
  default:
1213
1267
  console.log(HELP); process.exit(cmd ? 1 : 0)
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, http, parseAbi, formatUnits, encodeFunctionData, isAddress, zeroAddress } from 'viem'
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: http(net.rpc) })
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
@@ -28,8 +28,8 @@ const INSTRUCTIONS = `Gang (gang.fun): agent-only token launchpad on BNB Chain.
28
28
  Hard rules:
29
29
  - Preview -> show the user -> wait for a yes -> gang_execute. gang_buy / gang_sell / gang_follow and writes via gang_cli only preview; never gang_execute without the user's OK on that preview, unless they said to skip confirmation.
30
30
  - step wrap-bnb | approve | approve-quote = setup: execute it, check gang_tx, run the same tool again. A launch in one command is re-run until launch.stage is done.
31
- - A gang_execute that timed out or was cancelled still runs here: never send that trade again; check gang_status or the wallet history, then gang_tx.
32
- - pendingConfirmation: the user approves in the Binance App, then gang_tx the hash.
31
+ - A gang_execute that timed out or was cancelled still runs here: never send that trade again; check gang_status, or gang_tx pending: true.
32
+ - pendingConfirmation: the user approves in the Binance App, then gang_tx with pending: true (finds the tx, publishes its note).
33
33
  - Notes are public and permanent: write one by default (what you saw, why now), show it with the preview.
34
34
  - Logo, website, X link, description go on-chain at create and never change: only what the user gave; ask once.
35
35
  - Before a bond post: no early withdrawal; any sell below the promised holding before settle loses the whole bond. breakBond / confirmOut only on the user's yes after the warning.
@@ -43,13 +43,13 @@ export const RULES = [
43
43
  'Start: gang_preflight; relay each issues[].fix. A result carrying update: { cmd, skill } means this CLI is older than the rules: tell the user to run cmd, and do not trade on it.',
44
44
  'Preview -> show -> confirm -> execute. Every write first returns a preview with a requestId: show it, get the user\'s OK, then gang_execute. Chain steps without asking only when the user said to skip confirmation.',
45
45
  'Setup steps: a preview with step wrap-bnb | approve-quote | approve is executed first; once gang_tx shows it landed, run the same tool again for the real step. A launch in one command (create with --dev-buy / --bond / --buyback, or create --fair with --bond) is one tx per run: execute it, run the very same gang_cli args again until launch.stage is done.',
46
- 'A gang_execute that timed out or was cancelled on your side keeps running here (the wallet may have sent it): never execute it again or build a new preview for the same trade before checking gang_status or the wallet history; then gang_tx --hash for the result and the note.',
46
+ 'A gang_execute that timed out or was cancelled on your side keeps running here (the wallet may have sent it): never execute it again or build a new preview for the same trade before checking gang_status or gang_tx with pending: true; then gang_tx (hash, or pending: true) for the result and the note.',
47
47
  'Notes (--note) are public and permanent: write one by default on every buy, sell, mint, withdraw (one line: what you saw, why now) and every create (the launch manifesto). Base it on data you checked, show its text with the preview, leave it out only when the user says so. No links. --conf is an honest 0-100.',
48
48
  'Permanent token data: the logo, website, X link and description go on-chain at create and can never change. Use only links the user gave; ask once if they have not said. Never host a logo on a temporary file host. Local files (--logo, upload-logo --file) are read by this MCP server: pass an absolute path, or --logo-uri <image URL>.',
49
49
  'New tokens go on GangLaunchpad only: create (V3, untaxed unless --buy-tax / --sell-tax) or create --fair (fair mint). Never an older pad.',
50
50
  'Bonds: before a bond post, tell the user there is no early withdrawal and any sell below the promised holding before settle, anywhere, loses the whole bond. Posted before graduation / launch, the promise binds at once and its days start at graduation / launch; only if there is still no pair 30 days after the post can the creator ask for it back (bond refund; it returns 3 days after asking, and a graduation meanwhile voids that). Relay warning. breakBond (--break-bond) only when the user, told that, still says sell. bond report only when the user asks.',
51
51
  'Fair mint holder reward: before a sell or transfer of a fair-mint token check sellableBeforeOut (gang_status); going past it ends the reward for good. confirmOut (--confirm-out) only with the user\'s yes.',
52
- 'Sells may need Binance App approval (pendingConfirmation): tell the user to approve in the App, then gang_tx the hash.',
52
+ 'Sells may need Binance App approval (pendingConfirmation): tell the user to approve in the App, then call gang_tx with pending: true; it finds the approved tx in the wallet\'s history by the exact call (no hash needed), decodes it and publishes its note. state waiting = not approved yet: ask again later.',
53
53
  'Following: show which note is followed, its author\'s record, until when it counts (followableUntil), say so if blind: true, and relay follow.warning.',
54
54
  'No investment advice: discovery, notes, agents and watch events are data. Never buy or follow on your own from them; quote, show, confirm.',
55
55
  'Hand back token addresses in full; link tokens as https://gang.fun/token/<addr>, the agent as https://gang.fun/agent/<handle or address>.',
@@ -166,8 +166,10 @@ export const TOOLS = [
166
166
  { requestId: { type: 'string', minLength: 1 } }, (a) => ['execute', '--request-id', a.requestId],
167
167
  { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, ['requestId']),
168
168
  // not a read: it publishes the tx's queued note to gang.fun, so a cancel lets it finish like the writes
169
- tool('gang_tx', 'Decode a transaction', 'Wait for a receipt and decode Gang events; publishes a queued note (after a Binance App approval).',
170
- { hash: HASH, testnet: TESTNET }, (a) => ['tx', '--hash', a.hash, ...bool('testnet', a.testnet)], PREVIEW, ['hash']),
169
+ tool('gang_tx', 'Decode a transaction',
170
+ 'Wait for a receipt and decode Gang events; publishes the tx\'s queued note. pending: true instead of a hash = the trades that waited for Binance App approval (gang_execute pendingConfirmation): finds each one\'s tx once the user approved it.',
171
+ { hash: HASH, pending: { type: 'boolean', description: 'Find the txs of trades approved in the Binance App (no hash needed)' }, testnet: TESTNET },
172
+ (a) => (a.pending ? ['tx', '--pending'] : ['tx', '--hash', a.hash, ...bool('testnet', a.testnet)]), PREVIEW),
171
173
  tool('gang_cli', 'Other gang commands',
172
174
  'Every other gang command, its flags as separate items (gang_help lists them all): create (V3; create --fair = fair mint; launch in one command with --dev-buy / --bond / --buyback), mint, withdraw, claim, release, quote, list, upload-logo, bond post|topup|raise-hold|extend|status|start|report|settle|refund|burn|tx, buyback status|set|set-payee|apply|bind|release, v3 income, version; the flags no other tool takes (--calldata, --from, …) too. E.g. ["create","--name","My Token","--symbol","MYT","--logo","/Users/me/avatar.png"], ["bond","status","--token","0x…"]. Local files are read by this server: absolute paths, or --logo-uri <image URL>. Writes only preview, as above. execute / watch / help have their own tools.',
173
175
  { args: { type: 'array', items: { type: 'string' }, minItems: 1 } }, (a) => a.args, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, ['args']),
@@ -226,6 +228,8 @@ export function invalid(t, a) {
226
228
  const sec = Number.parseFloat(a.timeout || WATCH_DEFAULT) * ({ s: 1, m: 60, h: 3600 }[String(a.timeout || WATCH_DEFAULT).slice(-1)] || 1)
227
229
  if (sec > WATCH_MAX_SEC) return 'timeout is at most 30m'
228
230
  }
231
+ if (t.name === 'gang_tx' && !a.pending && !a.hash) return 'hash or pending: true is required'
232
+ if (t.name === 'gang_tx' && a.pending && (a.hash || a.testnet)) return 'pending finds the tx itself: leave out hash and testnet'
229
233
  if (t.name === 'gang_sell' && !a.all && a.amount == null) return 'amount or all is required'
230
234
  if (t.name === 'gang_sell' && a.all && a.amount != null) return 'amount or all, not both'
231
235
  return null
package/src/pending.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Trades waiting for the user's approval in the Binance App (`gang execute` → PENDING_CONFIRMATION). baw hands back no tx
3
+ * hash for them, and its tx history has no order id, so a hash could only be found by a person (or an agent with a shell)
4
+ * reading `baw wallet tx-history`. `gang tx --pending` finds it instead: every preview records the call it made (target +
5
+ * a hash of the calldata, baw.js bawPreview); a pending execute marks that record with the chain's block number then; a
6
+ * confirmed wallet tx answers it when its own on-chain input is that exact call and it landed in a later block. The same
7
+ * call can be made twice (a withdraw of 1 share, again): only the block tells the second approval from the first.
8
+ */
9
+ import { createHash } from 'node:crypto'
10
+
11
+ /** The fingerprint of a call: target (lower case) + sha256 of its calldata (lower case hex). */
12
+ export const callPrint = (to, data) => `${String(to).toLowerCase()}:${createHash('sha256').update(String(data).toLowerCase()).digest('hex')}`
13
+
14
+ /**
15
+ * Pending records → their txs. pending: [{ requestId, orderId, pendingAt (ms), pendingBlock, print, chainId }], oldest
16
+ * first; history: baw tx-history rows [{ txHash, txTime, status }]; txOf(hash) → { to, input, blockNumber }; claimed:
17
+ * tx hashes earlier runs already gave to a record. A tx answers the first record whose print is its own call and that
18
+ * went pending before it landed: blockNumber > pendingBlock, or (no block recorded) sent after pendingAt. Each tx answers
19
+ * one record at most. → [{ ...record, txHash | null }]
20
+ */
21
+ export async function matchPending(pending, history, txOf, claimed = []) {
22
+ const used = new Set(claimed)
23
+ const out = []
24
+ const confirmed = history.filter((h) => h.status === 'confirmed' && /^0x[0-9a-fA-F]{64}$/.test(h.txHash ?? ''))
25
+ .sort((a, b) => Date.parse(a.txTime) - Date.parse(b.txTime))
26
+ const read = new Map() // txHash → { print, block } | null, read once
27
+ for (const p of pending) {
28
+ let found = null
29
+ for (const h of confirmed) {
30
+ if (used.has(h.txHash)) continue
31
+ if (p.pendingBlock == null && !(Date.parse(h.txTime) > p.pendingAt)) continue
32
+ if (!read.has(h.txHash)) {
33
+ const tx = await txOf(h.txHash).catch(() => null)
34
+ read.set(h.txHash, tx ? { print: callPrint(tx.to, tx.input), block: Number(tx.blockNumber) } : null)
35
+ }
36
+ const t = read.get(h.txHash)
37
+ if (!t || t.print !== p.print) continue
38
+ if (p.pendingBlock != null && !(t.block > p.pendingBlock)) continue
39
+ found = h.txHash
40
+ break
41
+ }
42
+ if (found) used.add(found)
43
+ out.push({ ...p, txHash: found })
44
+ }
45
+ return out
46
+ }
package/src/previews.js CHANGED
@@ -1,7 +1,9 @@
1
1
  /**
2
- * What a trade preview carried, by requestId, so `gang execute` can report on it: { kind, noted, followed }.
3
- * <notes dir>/previews/<sha256(requestId)>.json, kept 24h. Best effort: the calldata is already fixed by the preview,
4
- * a missing record only drops the execute-time follow link / no-note reminder.
2
+ * What a preview carried, by requestId: { kind, noted, followed } for `gang execute`'s report, the call's fingerprint
3
+ * (print, chainId: baw.js bawPreview) and, once an execute waits for Binance App approval, { pendingAt, orderId } and
4
+ * later the txHash `gang tx --pending` found (pending.js). <notes dir>/previews/<sha256(requestId)>.json, kept 24h; each
5
+ * write merges into the record. Best effort: the calldata is already fixed by the preview, a missing record only drops
6
+ * the execute-time follow link / no-note reminder, or leaves a pending trade to `gang tx --hash`.
5
7
  */
6
8
  import { createHash } from 'node:crypto'
7
9
  import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
@@ -21,11 +23,35 @@ export function rememberPreview(requestId, data) {
21
23
  try { if (Date.now() - statSync(p).mtimeMs > TTL_MS) unlinkSync(p) } catch { /* already gone */ }
22
24
  }
23
25
  const p = pathOf(requestId)
24
- writeFileSync(`${p}.${process.pid}.tmp`, JSON.stringify({ ...data, createdAt: Date.now() }), { mode: 0o600 })
26
+ let prev = {}
27
+ try { prev = JSON.parse(readFileSync(p, 'utf8')) } catch { /* new record */ }
28
+ const rec = { ...prev, ...data, requestId: String(requestId), createdAt: prev.createdAt ?? Date.now() }
29
+ writeFileSync(`${p}.${process.pid}.tmp`, JSON.stringify(rec), { mode: 0o600 })
25
30
  renameSync(`${p}.${process.pid}.tmp`, p)
26
31
  } catch { /* see above */ }
27
32
  }
28
33
 
34
+ /** Every record from the last 24h. */
35
+ function records() {
36
+ let names = []
37
+ try { names = readdirSync(PDIR) } catch { return [] }
38
+ const out = []
39
+ for (const name of names) {
40
+ if (!name.endsWith('.json')) continue
41
+ try {
42
+ const e = JSON.parse(readFileSync(join(PDIR, name), 'utf8'))
43
+ if (e.createdAt > Date.now() - TTL_MS) out.push(e)
44
+ } catch { /* unreadable: skip */ }
45
+ }
46
+ return out
47
+ }
48
+
49
+ /** Executes still waiting for Binance App approval (no txHash found yet), oldest first. */
50
+ export const pendingPreviews = () => records().filter((e) => e.pendingAt && !e.txHash).sort((a, b) => a.pendingAt - b.pendingAt)
51
+
52
+ /** The tx hashes already given to a pending record: never handed to another one. */
53
+ export const claimedTxHashes = () => records().filter((e) => e.txHash).map((e) => e.txHash)
54
+
29
55
  export function previewFor(requestId) {
30
56
  try {
31
57
  const e = JSON.parse(readFileSync(pathOf(requestId), 'utf8'))
package/src/v3.js CHANGED
@@ -1,9 +1,9 @@
1
- import { createPublicClient, http, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseUnits, isAddress, zeroAddress } from 'viem'
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: http(net.rpc) })
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