@gangfun/cli 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/promote.js ADDED
@@ -0,0 +1,669 @@
1
+ import { createPublicClient, concat, encodeAbiParameters, encodeFunctionData, getAddress, isAddress, isHash, keccak256, parseAbi, zeroAddress } from 'viem'
2
+ import { API, get as apiGet } from './discover.js'
3
+ import { atTokenPad, gangGens, KIND_UNREAD, NOT_ON_MAINNET, padNets, PAD3_GEN, rpcTransport } from './gangpad.js'
4
+ import { walletFor } from './fair.js'
5
+ import { revertOf as revertIn, step, units } from './steps.js'
6
+
7
+ /**
8
+ * `gang promote …`, `gang create … --promote <pct>` and `gang buy … --promoter <addr>`: the promoter share on GangLaunchpad 3.0
9
+ * (docs/SPEC-PROMOTER-SHARE-2026-11-04.md, docs/SPEC-PROMOTER-POOL-SHARE-2026-11-05.md).
10
+ * A dev sets a share of its creator fee and a window at create, fixed for good. A wallet is bound to a promoter by its
11
+ * first trade of the token, only through `buyWithPromoter`, called directly from the wallet on the curve. On every curve
12
+ * trade of a bound wallet inside the window the promoter accrues that share of the creator's fee on the pad.
13
+ * On a taxed token whose recipient is the dev's GangPromotePoolModule (`promote-pool-v1`), it also earns that share of the
14
+ * recipient's part of the pool tax after graduation: the module escrows it, a settler posts Merkle roots of cumulative
15
+ * amounts (2-day dispute window, the Safe can veto), and each account claims with its proof. The dev gets the rest at once.
16
+ * What this CLI is told by gang.fun about a root is never trusted: each proof is checked against the root read on chain.
17
+ * Env: GANG_PROMOTE_POOL_FACTORY / GANG_TESTNET_PROMOTE_POOL_FACTORY override the factory (gangpad.js).
18
+ */
19
+ export const PROMOTE_POOL_TYPE = 'promote-pool-v1'
20
+ export const MIN_WINDOW_DAYS = 7
21
+ export const MAX_WINDOW_DAYS = 90
22
+ export const DEFAULT_WINDOW_DAYS = 30
23
+ const MAX_SHARE_BPS = 5_000
24
+ const BPS = 10_000
25
+ const DAY = 86_400
26
+ const BATCH = 200
27
+ const MAX_SCAN = 2_000
28
+
29
+ export const PROMOTE_PAD_ABI = parseAbi([
30
+ 'function promoteOf(address token) view returns (uint16 shareBps, uint32 window)',
31
+ 'function bindingOf(address token, address wallet) view returns (address promoter, uint40 boundAt, bool traded)',
32
+ 'function promoterFeeOf(address token, address promoter) view returns (uint256)',
33
+ 'function canBind(address token, address wallet, address promoter) view returns (bool)',
34
+ 'function buyWithPromoter(address token, uint256 funds, uint256 minAmount, address promoter) payable returns (uint256 amountOut, uint256 fundsUsed)',
35
+ 'function claimPromoterFee(address token, address to) returns (uint256 amount)',
36
+ 'error BadPromoteTerms()', 'error TraderNotOrigin()', 'error NotCurveToken()', 'error BadMsgValue()', 'error ZeroAmount()',
37
+ 'event PromoteSet(address indexed token, uint16 shareBps, uint32 window)',
38
+ 'event PromoterBound(address indexed token, address indexed wallet, address indexed promoter)',
39
+ 'event PromoterFeeAccrued(address indexed token, address indexed promoter, address indexed wallet, uint256 amount)',
40
+ 'event PromoterFeeClaimed(address indexed token, address indexed promoter, address indexed to, uint256 amount)',
41
+ ])
42
+
43
+ const ERRORS = [
44
+ 'error ZeroAddress()', 'error NotClone()', 'error NotFactory()', 'error AlreadyInitialized()', 'error AlreadyBound()', 'error NotBound()',
45
+ 'error NotCurve()', 'error NotCreator()', 'error NotRecipient()', 'error NotPromoted()', 'error AllDividends()', 'error AlreadyGraduated()',
46
+ 'error NotSettler()', 'error NotVetoer()', 'error NotDev()', 'error BadRoot()', 'error BadAllocated()', 'error BadThroughBlock()',
47
+ 'error PostPending()', 'error NothingPending()', 'error TooEarly()', 'error TooLate()', 'error BadProof()', 'error NothingToClaim()',
48
+ 'error OverAllocated()', 'error BadReceiver()', 'error StillActive()', 'error Closed()', 'error NothingOwed()', 'error BoundQuote()',
49
+ 'error PushStarved()',
50
+ ]
51
+
52
+ export const POOL_FACTORY_ABI = parseAbi([
53
+ 'function create(bytes32 salt) returns (address module)',
54
+ 'function predict(address dev, bytes32 salt) view returns (address)',
55
+ 'function pad() view returns (address)',
56
+ 'function implementation() view returns (address)',
57
+ 'error NotAgent()', 'error WrongHandler()',
58
+ 'event Created(address indexed dev, address indexed module)',
59
+ ...ERRORS,
60
+ ])
61
+
62
+ export const POOL_ABI = parseAbi([
63
+ 'function moduleType() view returns (bytes32)',
64
+ 'function factory() view returns (address)',
65
+ 'function dev() view returns (address)',
66
+ 'function token() view returns (address)',
67
+ 'function quote() view returns (address)',
68
+ 'function shareBps() view returns (uint16)',
69
+ 'function window() view returns (uint32)',
70
+ 'function closed() view returns (bool)',
71
+ 'function escrowOpen() view returns (bool)',
72
+ 'function firstGradSeenAt() view returns (uint64)',
73
+ 'function lastPostAt() view returns (uint64)',
74
+ 'function escrowIn() view returns (uint256)',
75
+ 'function reclaimed() view returns (uint256)',
76
+ 'function claimedTotal() view returns (uint256)',
77
+ 'function devOwed() view returns (uint256)',
78
+ 'function undistributed() view returns (uint256)',
79
+ 'function root() view returns (bytes32)',
80
+ 'function allocatedTotal() view returns (uint256)',
81
+ 'function throughBlock() view returns (uint64)',
82
+ 'function pendingRoot() view returns (bytes32)',
83
+ 'function pendingAllocated() view returns (uint256)',
84
+ 'function pendingThroughBlock() view returns (uint64)',
85
+ 'function pendingActiveAt() view returns (uint64)',
86
+ 'function claimed(address account) view returns (uint256)',
87
+ 'function SETTLER_SILENCE() view returns (uint64)',
88
+ 'function ESCROW_GRACE() view returns (uint64)',
89
+ 'function bind(address token)',
90
+ 'function work(uint256 minOut)',
91
+ 'function activate()',
92
+ 'function sweep(address asset) returns (uint256 amount)',
93
+ 'function claim(uint256 cumulative, bytes32[] proof, address to) returns (uint256 amount)',
94
+ 'function reclaim(address to) returns (uint256 amount)',
95
+ 'function releaseDev(address to) returns (uint256 amount)',
96
+ 'event Bound(address indexed token, address indexed quote, uint16 shareBps, uint32 window)',
97
+ 'event Split(uint256 incoming, uint256 toEscrow, uint256 toDev)',
98
+ 'event DevOwed(uint256 amount)',
99
+ 'event DevReleased(address indexed to, uint256 amount)',
100
+ 'event RootPosted(bytes32 indexed root, uint256 allocatedTotal, uint64 throughBlock, uint64 activeAt, string uri)',
101
+ 'event RootActivated(bytes32 indexed root, uint256 allocatedTotal, uint64 throughBlock)',
102
+ 'event RootVetoed(bytes32 indexed root)',
103
+ 'event Claimed(address indexed account, address indexed to, uint256 amount)',
104
+ 'event Reclaimed(address indexed to, uint256 amount)',
105
+ 'event Swept(address indexed asset, uint256 amount)',
106
+ ...ERRORS,
107
+ ])
108
+ /** gang tx decodes these. */
109
+ export const PROMOTE_EVENT_ABIS = [PROMOTE_PAD_ABI, POOL_FACTORY_ABI, POOL_ABI]
110
+
111
+ const PAD_READS = parseAbi([
112
+ 'function curves(address token) view returns (address creator, address quote, uint128 realQuote, uint128 sold, uint128 gradAmt, uint128 virtualQuote, bool graduated, uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address pair, address refPair)',
113
+ 'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
114
+ 'function tokenCount() view returns (uint256)',
115
+ 'function allTokens(uint256) view returns (address)',
116
+ 'function isAgent(address) view returns (bool)',
117
+ ])
118
+ const SYMBOL_ABI = parseAbi(['function symbol() view returns (string)'])
119
+
120
+ const GAS_NOTE = 'let the wallet estimate the gas limit (eth_estimateGas) and do not lower it: a push to the dev needs about 365k gas left before it, far more than the call uses'
121
+
122
+ export const HINTS = {
123
+ NotAgent: 'only an Agent can create a V3 token, so only an Agent gets a promoter pool module',
124
+ NotFactory: 'this factory is not allowed on the platform\'s GangHandlerAdmin yet, so it cannot list a module as a tax recipient. If GANG_PROMOTE_POOL_FACTORY / GANG_TESTNET_PROMOTE_POOL_FACTORY is set, check it',
125
+ AlreadyBound: 'the module is bound to a token already',
126
+ NotCurve: 'not a V3 (curve) token on this pad',
127
+ NotCreator: 'the token was not created by this module\'s dev',
128
+ NotRecipient: 'the token does not pay its tax to this module',
129
+ NotPromoted: 'the token was not made with promoter terms (gang create … --promote)',
130
+ AllDividends: 'all of the token\'s tax goes to holders, so the module would never receive anything',
131
+ AlreadyGraduated: 'a module binds before graduation only: this token has no pool share, and gang promote sweep sends its income to the dev',
132
+ NotBound: 'the module is not bound to a token yet',
133
+ NotDev: 'only the dev this module was made for',
134
+ NothingPending: 'no root is waiting',
135
+ TooEarly: 'the root\'s 2-day dispute window is not over',
136
+ BadProof: 'that amount and proof do not match the root in effect: fetch them again',
137
+ NothingToClaim: 'this account has already claimed all the root gives it',
138
+ OverAllocated: 'the root\'s total is used up: the leaves add up to more than it allows, so this claim reverts (report it to the platform)',
139
+ BadReceiver: '--to cannot be zero or the module itself',
140
+ StillActive: 'the settler has posted within the last 30 days, or the token has not graduated: reclaim opens after 30 days of silence once graduation was seen (a first gang promote work records it)',
141
+ Closed: 'the dev reclaimed: the module is closed for good, and every arrival goes to the dev',
142
+ NothingOwed: 'nothing of that asset here',
143
+ BoundQuote: 'the module\'s own quote is split, not swept',
144
+ PostPending: 'a root waits for its dispute window: reclaim opens after it took effect',
145
+ PushStarved: `the tx's gas limit was too low: ${GAS_NOTE}`,
146
+ BadPromoteTerms: `--promote takes 0.01–${MAX_SHARE_BPS / 100}%, --promote-days ${MIN_WINDOW_DAYS}–${MAX_WINDOW_DAYS}`,
147
+ TraderNotOrigin: 'a promoter binds only on a buy sent directly from the wallet: no contract, router or aggregator',
148
+ NotCurveToken: 'a promoter binds on the curve only: this token has graduated or isn\'t a V3 curve token',
149
+ }
150
+ export const revertOf = (e) => revertIn(e, [POOL_ABI, POOL_FACTORY_ABI, PROMOTE_PAD_ABI], HINTS)
151
+
152
+ export async function simulatePool(client, from, address, abi, functionName, args = []) {
153
+ try {
154
+ const { result } = await client.simulateContract({ account: from, address, abi, functionName, args })
155
+ return { result }
156
+ } catch (e) {
157
+ const r = revertOf(e)
158
+ return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
159
+ }
160
+ }
161
+
162
+ export function poolFactoryAddress(testnet) {
163
+ return gangGens(testnet)[0].promotePoolFactory || null
164
+ }
165
+
166
+ export const poolNotDeployed = (testnet) =>
167
+ `GangPromotePoolModuleFactory is not deployed on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version, so the promoter share can't reach the pool yet. Set ${testnet ? 'GANG_TESTNET_PROMOTE_POOL_FACTORY' : 'GANG_PROMOTE_POOL_FACTORY'} to its address, or name a recipient with --recipient (the share then stays on the curve)`
168
+
169
+ const PCT_RE = /^(\d{1,3})(?:\.(\d{1,2}))?$/
170
+
171
+ /** --promote <pct> and --promote-days <n> → { shareBps, windowDays, window } or { error }. Pure. */
172
+ export function parsePromote(raw, daysRaw) {
173
+ const usage = `--promote takes the promoter's share of your creator fee in %, 0.01–${MAX_SHARE_BPS / 100}, up to 2 decimals (e.g. --promote 20)`
174
+ const m = PCT_RE.exec(String(raw ?? '').trim())
175
+ if (!m) return { error: usage, got: raw ?? null }
176
+ const shareBps = Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0'))
177
+ if (shareBps < 1 || shareBps > MAX_SHARE_BPS) return { error: usage, got: raw }
178
+ const d = daysRaw === undefined ? DEFAULT_WINDOW_DAYS : Number(daysRaw)
179
+ if (!Number.isInteger(d) || d < MIN_WINDOW_DAYS || d > MAX_WINDOW_DAYS) {
180
+ return { error: `--promote-days takes whole days, ${MIN_WINDOW_DAYS}–${MAX_WINDOW_DAYS}`, got: daysRaw }
181
+ }
182
+ return { shareBps, windowDays: d, window: d * DAY }
183
+ }
184
+
185
+ /** Does this create's flags ask for the pool module? --promote on a taxed V3 token with no recipient or other module named. Pure. */
186
+ export function wantsPoolModule(kind, flag, opt) {
187
+ if (kind !== 'v3' || !flag('promote') || flag('recipient') || flag('vault')) return false
188
+ if (flag('buyback') || flag('split') || flag('lp')) return false
189
+ const zero = (f) => !flag(f) || /^0*(\.0*)?$/.test(opt(f) ?? '')
190
+ if (zero('buy-tax') && zero('sell-tax')) return false
191
+ return !/^0*100(\.0+)?$/.test(opt('dividend', '0'))
192
+ }
193
+
194
+ /** What a --promote create says it does. `pool`: the token's recipient is a promoter pool module. Pure. */
195
+ export function promoteLine({ shareBps, windowDays, pool, taxed, dividendPct = 0 }) {
196
+ const pct = shareBps / 100
197
+ const curve = `${pct}% of your creator fee goes to the promoter of each bound wallet, on that wallet's curve trades for ${windowDays} days after it binds; you keep the rest. Fixed for good. A wallet binds only by its first buy, sent directly with gang promote buy --promoter (never through a router or aggregator)`
198
+ if (pool) {
199
+ const onTax = (pct * (100 - dividendPct)) / 100
200
+ return `${curve}. After graduation the promoter also earns ${pct}% of the recipient's part of those wallets' pool tax (about ${onTax}% of the tax left after the platform's part): the module escrows ${pct}% of each arrival and pushes the rest to you, and a settler posts who gets what, with a 2-day dispute window. What the escrow holds for trades with no promoter is yours too, but only once you claim it: gang promote claim-pool. A trade counts for the promoter only if the bound wallet itself moves the tokens, or calls a listed router directly: tokens moved to another address first, or sold through an unlisted contract, don't count; nor does tax still unsold when escrow ends. Escrow ends about ${windowDays + 7} days after graduation (counted from the first split that sees it). If the settler is silent for 30 days after graduation you can reclaim what no root allocated, which closes the module. The module can't be combined with --buyback / --lp / --split`
201
+ }
202
+ if (taxed && dividendPct === 100) return `${curve}. Curve only: all of this token's tax goes to holders, so there is no recipient's part to share`
203
+ return `${curve}. Curve only: ${taxed ? 'this token\'s tax goes to another recipient, so promoters earn nothing from its pool tax (a token has one recipient: to share it, launch with no --recipient, --buyback, --lp or --split)' : 'an untaxed token has no pool tax to share'}`
204
+ }
205
+
206
+ // --- the Merkle tree the settler posts: OpenZeppelin StandardMerkleTree leaves and sorted pairs
207
+
208
+ export function leafOf(account, cumulative) {
209
+ return keccak256(keccak256(encodeAbiParameters([{ type: 'address' }, { type: 'uint256' }], [getAddress(account), BigInt(cumulative)])))
210
+ }
211
+
212
+ export function verifyProof(root, leaf, proof) {
213
+ let h = leaf
214
+ for (const p of proof) h = BigInt(h) < BigInt(p) ? keccak256(concat([h, p])) : keccak256(concat([p, h]))
215
+ return h.toLowerCase() === String(root).toLowerCase()
216
+ }
217
+
218
+ /** The amount gang.fun's `active` gives `account`, or null when it doesn't prove out against `root`, a malformed answer included. */
219
+ export function provenAmount(root, account, active) {
220
+ try {
221
+ const c = BigInt(active.cumulative)
222
+ return verifyProof(root, leafOf(account, c), active.proof) ? c : null
223
+ } catch { return null }
224
+ }
225
+
226
+ const NO_ROOT = `0x${'00'.repeat(32)}`
227
+ const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
228
+
229
+ /** The runtime code of an EIP-1167 clone of `impl`. */
230
+ export const cloneCode = (impl) => `0x363d3d373d3d3d363d73${impl.slice(2)}5af43d82803e903d91602b57fd5bf3`.toLowerCase()
231
+
232
+ /**
233
+ * A module of a known factory, for printing. null: not a clone of that factory's implementation, so nothing it says
234
+ * counts: moduleType() and factory() are only what a contract says about itself. `getCode(addr)` reads the code.
235
+ * The whole check for "this token has a pool share" (spec §2): the recipient is such a module and its token() is the token.
236
+ */
237
+ export async function poolOf(read, getCode, module, factory) {
238
+ if (!module || module === zeroAddress || !factory) return null
239
+ // an RPC error throws: "not a module" would be an answer
240
+ const [impl, code] = await Promise.all([read(factory, POOL_FACTORY_ABI, 'implementation'), getCode(module)])
241
+ if (String(code ?? '').toLowerCase() !== cloneCode(impl)) return null
242
+ const names = ['dev', 'token', 'quote', 'shareBps', 'window', 'closed', 'escrowOpen', 'firstGradSeenAt', 'lastPostAt', 'escrowIn', 'reclaimed',
243
+ 'claimedTotal', 'devOwed', 'undistributed', 'root', 'allocatedTotal', 'throughBlock', 'pendingRoot', 'pendingAllocated', 'pendingThroughBlock', 'pendingActiveAt']
244
+ const vals = await Promise.all(names.map((n) => read(module, POOL_ABI, n)))
245
+ const s = Object.fromEntries(names.map((n, i) => [n, vals[i]]))
246
+ return { module, ...s, token: s.token === zeroAddress ? null : s.token, quote: s.quote === zeroAddress ? null : s.quote }
247
+ }
248
+
249
+ /** The module's state in units (pure apart from `f`). `f(x)`: amount to string in its quote. `now`: seconds. */
250
+ export function formatPool(s, f, now, ref = '') {
251
+ const pending = s.pendingRoot !== NO_ROOT
252
+ const due = pending && Number(s.pendingActiveAt) <= now
253
+ const next = []
254
+ if (due) next.push(`gang promote activate ${ref} (anyone: the root's dispute window is over)`)
255
+ if (s.undistributed > 0n) next.push(`gang promote work ${ref} (anyone: split what arrived)`)
256
+ if (s.devOwed > 0n) next.push(`gang promote release-dev ${ref} (the dev)`)
257
+ return {
258
+ module: s.module, moduleType: PROMOTE_POOL_TYPE, dev: s.dev, boundToken: s.token, quote: s.quote, sharePct: Number(s.shareBps) / 100,
259
+ windowDays: Number(s.window) / DAY, closed: s.closed, escrowOpen: s.escrowOpen,
260
+ graduationSeenAt: iso(s.firstGradSeenAt), lastPostAt: iso(s.lastPostAt),
261
+ escrowed: f(s.escrowIn), reclaimed: f(s.reclaimed), claimedTotal: f(s.claimedTotal), devOwed: f(s.devOwed), waitingToSplit: f(s.undistributed),
262
+ root: s.root === NO_ROOT ? null : { root: s.root, allocated: f(s.allocatedTotal), throughBlock: Number(s.throughBlock) },
263
+ pending: pending ? { root: s.pendingRoot, allocated: f(s.pendingAllocated), throughBlock: Number(s.pendingThroughBlock), activeAt: iso(s.pendingActiveAt), due } : null,
264
+ ...(next.length && { next }),
265
+ }
266
+ }
267
+
268
+ /** The wallet's binding as printed: what is left of its window (`window`, `now`: seconds). Pure. */
269
+ export function formatBinding(promoter, boundAt, traded, window, now, graduated = false) {
270
+ if (!traded) {
271
+ return { promoter: null, traded: false, note: graduated ? 'this wallet never traded the token on the curve, and it has graduated: it can\'t bind now' : 'this wallet has not traded the token: its first buy can name a promoter' }
272
+ }
273
+ if (promoter === zeroAddress) return { promoter: null, traded: true, note: 'this wallet traded the token with no promoter: it can never bind now' }
274
+ const ends = Number(boundAt) + Number(window)
275
+ return { promoter, boundAt: iso(boundAt), windowEnds: iso(ends), inWindow: now < ends, traded: true }
276
+ }
277
+
278
+ /**
279
+ * --promoter on a buy: the reason it can't bind (the pad would drop it without a word, and the buy would go on), else null.
280
+ * Pure over the reads. `b`: bindingOf; `terms`: promoteOf.
281
+ */
282
+ export function whyNoBind({ me, promoter, creator, shareBps, boundPromoter, traded, promoterIsAgent, canBind }) {
283
+ const same = (a, b) => String(a).toLowerCase() === String(b).toLowerCase()
284
+ if (Number(shareBps) === 0) return 'this token was made without promoter terms: nobody earns from a --promoter here'
285
+ if (same(promoter, me)) return '--promoter is this wallet itself: a wallet cannot be its own promoter'
286
+ if (same(promoter, creator)) return '--promoter is the token\'s creator, who cannot be a promoter of its own token'
287
+ if (traded) {
288
+ return boundPromoter && boundPromoter !== zeroAddress
289
+ ? `this wallet is already bound to ${boundPromoter} for good: its trades pay that promoter. Drop --promoter`
290
+ : 'this wallet already traded this token: a wallet binds only by its first trade. Drop --promoter'
291
+ }
292
+ if (promoterIsAgent === false) return '--promoter holds no Agent ID: the pad would ignore it'
293
+ if (canBind === false) return 'the pad would not bind this promoter (canBind is false): drop --promoter'
294
+ return null
295
+ }
296
+
297
+ // a timeout or a 429 says nothing about the token: reading it as "no terms" would send a buyer to a plain buy, which can never bind
298
+ const UNREAD_TERMS = 'could not read the promoter terms (RPC error). Nothing was built. Run the same command again; don\'t switch to a plain gang buy: a first buy without a promoter can never bind later'
299
+ // only a revert: a node that is behind can answer an eth_call with empty data for a pad that has the function
300
+ export const isMissingRead = (e) => !!revertOf(e)
301
+
302
+ /** Reads what --promoter needs; { promoter, refuse?, retry? } with the promoter checksummed. `ctx` is on the token's pad. */
303
+ export async function checkPromoter(ctx, { token, me, raw, creator }) {
304
+ const promoter = getAddress(raw)
305
+ let shareBps, b, can, agent
306
+ try {
307
+ [[shareBps], b, can, agent] = await Promise.all([
308
+ ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'promoteOf', [token]),
309
+ ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'bindingOf', [token, me]),
310
+ ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'canBind', [token, me, promoter]),
311
+ ctx.read(ctx.pad, PAD_READS, 'isAgent', [promoter]),
312
+ ])
313
+ } catch (e) {
314
+ if (!isMissingRead(e)) return { promoter, refuse: UNREAD_TERMS, retry: 'same command again' }
315
+ return { promoter, refuse: `GangLaunchpad ${ctx.gen ?? ctx.pad} has no promoter share (only a 3.0 pad upgraded for it does)` }
316
+ }
317
+ const refuse = whyNoBind({ me, promoter, creator, shareBps, boundPromoter: b[0], traded: b[2], promoterIsAgent: agent, canBind: can })
318
+ return { promoter, ...(refuse && { refuse }) }
319
+ }
320
+
321
+ /** { sharePct, windowDays } of a token (0 share: none), null when the pad has no promoter share. Throws on an RPC error. */
322
+ export async function promoteTermsOf(ctx, token) {
323
+ try {
324
+ const [shareBps, window] = await ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'promoteOf', [token])
325
+ return { shareBps: Number(shareBps), sharePct: Number(shareBps) / 100, windowDays: Number(window) / DAY }
326
+ } catch (e) {
327
+ if (isMissingRead(e)) return null
328
+ throw e
329
+ }
330
+ }
331
+
332
+ /**
333
+ * For a plain curve buy: the wallet's first trade of a token with promoter terms is its only chance to bind. Advice on a
334
+ * preview, so an unread answer just says nothing.
335
+ */
336
+ export async function firstBuyWarning(ctx, token, me) {
337
+ try {
338
+ const [[shareBps], b] = await Promise.all([
339
+ ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'promoteOf', [token]),
340
+ ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'bindingOf', [token, me]),
341
+ ])
342
+ if (Number(shareBps) === 0 || b[2]) return null
343
+ return `this token has a promoter share and this is this wallet's first trade of it: without a promoter it can never bind later. If the user came from an invite link (…?promoter=0x…), build this buy with gang promote buy --promoter <that address> instead`
344
+ } catch { return null }
345
+ }
346
+
347
+ /** For gang info / status: the token's promoter terms and whether they reach the pool. null without terms. */
348
+ export async function promoteField(ctx, token, { recipient, dividendPct = 0, testnet } = {}) {
349
+ let t
350
+ try { t = await promoteTermsOf(ctx, token) } catch { return { error: 'could not read the promoter terms (RPC error): this doesn\'t mean there are none', retry: 'same command again' } }
351
+ if (!t || t.shareBps === 0) return null
352
+ const pool = await poolOf(ctx.read, (a) => ctx.client.getCode({ address: a }), recipient, poolFactoryAddress(testnet)).catch(() => null)
353
+ const live = !!pool && pool.token?.toLowerCase() === token.toLowerCase() && !pool.closed
354
+ return {
355
+ sharePct: t.sharePct, windowDays: t.windowDays, poolShare: live,
356
+ ...(live && { module: pool.module, escrowOpen: pool.escrowOpen, poolPct: (t.sharePct * (100 - dividendPct)) / 100 }),
357
+ next: `gang promote status --token ${token}${testnet ? ' --testnet' : ''}`,
358
+ }
359
+ }
360
+
361
+ const SUBS = ['buy', 'status', 'earnings', 'claim', 'claim-pool', 'activate', 'work', 'bind', 'reclaim', 'release-dev', 'sweep']
362
+ const USAGE = `usage: gang promote ${SUBS.join('|')} [--token <addr> | --module <addr>] [--to <addr>] [--from <wallet>] [--testnet] — see gang help`
363
+
364
+ function promoteCtx(testnet) {
365
+ const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
366
+ if (!net.pad) throw new Error(NOT_ON_MAINNET)
367
+ const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
368
+ return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
369
+ }
370
+
371
+ /** gang.fun's answers, or { error } (a claim can still go on with --cumulative and --proof). */
372
+ async function apiOr(path) {
373
+ try {
374
+ const r = await apiGet(path, undefined, '')
375
+ return r ?? { error: `gang.fun has no answer at ${API}${path.split('?')[0]}` }
376
+ } catch (e) { return { error: e.message } }
377
+ }
378
+
379
+ /** Every 3.0 token where `who` has a curve share to claim; read on chain, as gang creator-fee does. */
380
+ async function curveEarnings(ctx, who) {
381
+ const pads = ctx.gens.filter((g) => g.gen === PAD3_GEN)
382
+ const tokens = []
383
+ let unread = 0
384
+ for (const g of pads) {
385
+ const n = Number(await ctx.read(g.pad, PAD_READS, 'tokenCount'))
386
+ const take = Math.min(n, MAX_SCAN)
387
+ const multi = (contracts, allowFailure = true) => ctx.client.multicall({ contracts, allowFailure, batchSize: 0 })
388
+ for (let from = 0; from < take; from += BATCH) {
389
+ const idx = Array.from({ length: Math.min(BATCH, take - from) }, (_, i) => BigInt(n - 1 - from - i))
390
+ const addrs = await multi(idx.map((i) => ({ address: g.pad, abi: PAD_READS, functionName: 'allTokens', args: [i] })), false)
391
+ const fees = await multi(addrs.map((t) => ({ address: g.pad, abi: PROMOTE_PAD_ABI, functionName: 'promoterFeeOf', args: [t, who] })))
392
+ const due = addrs.map((t, i) => ({ t, owed: fees[i].result, ok: fees[i].status === 'success' }))
393
+ // a pad before the upgrade answers none of them: no share to report there
394
+ if (!due.some((x) => x.ok)) break
395
+ unread += due.filter((x) => !x.ok).length
396
+ for (const { t, owed } of due.filter((x) => x.owed > 0n)) {
397
+ const [, quote] = await ctx.read(g.pad, PAD_READS, 'curves', [t])
398
+ const symbol = await ctx.read(t, SYMBOL_ABI, 'symbol').catch(() => null)
399
+ tokens.push({ token: t, symbol, quote: await ctx.read(quote, SYMBOL_ABI, 'symbol').catch(() => quote), claimable: await units(ctx, quote, owed) })
400
+ }
401
+ }
402
+ }
403
+ return { tokens, ...(unread && { unreadNote: `${unread} token(s) could not be read (RPC); run it again to include them` }) }
404
+ }
405
+
406
+ /** Entry for `gang promote <sub>`. io: { opt, flag, out, fail, summarize } from index.js. */
407
+ export async function runPromote(sub, { opt, flag, out, fail, summarize }) {
408
+ // buy runs in index.js, on the path of gang buy
409
+ if (!SUBS.includes(sub) || sub === 'buy') return fail(USAGE, { got: sub ?? null })
410
+ const testnet = flag('testnet')
411
+ const rawOnly = flag('calldata')
412
+ const tn = testnet ? ' --testnet' : ''
413
+ let ctx
414
+ try { ctx = promoteCtx(testnet) } catch (e) { return fail(e.message) }
415
+ const chainId = Number(ctx.chainId)
416
+ const me = () => walletFor(ctx, opt('from'))
417
+ const getCode = (a) => ctx.client.getCode({ address: a })
418
+ const toArg = () => {
419
+ if (!flag('to')) return me()
420
+ const to = opt('to')
421
+ if (!isAddress(to ?? '') || to === zeroAddress) fail('--to must be a 0x address', { got: to ?? null })
422
+ return getAddress(to)
423
+ }
424
+
425
+ if (sub === 'earnings') {
426
+ const who = getAddress(me())
427
+ const curve = await curveEarnings(ctx, who).catch((e) => ({ error: e.shortMessage || e.message.split('\n')[0] }))
428
+ const pool = await apiOr(`/promote-pool/earnings?${new URLSearchParams({ account: who })}`)
429
+ const modules = []
430
+ for (const m of (pool.modules ?? [])) {
431
+ if (!isAddress(m.module ?? '')) continue
432
+ const c = await poolOf(ctx.read, getCode, m.module, poolFactoryAddress(testnet)).catch(() => null)
433
+ if (!c?.quote) continue
434
+ const done = await ctx.read(m.module, POOL_ABI, 'claimed', [who]).catch(() => null)
435
+ if (done === null) continue
436
+ let total
437
+ try { total = BigInt(m.cumulative ?? 0) } catch { continue }
438
+ modules.push({
439
+ module: m.module, token: c.token, quote: await ctx.read(c.quote, SYMBOL_ABI, 'symbol').catch(() => c.quote),
440
+ allocated: await units(ctx, c.quote, total), claimed: await units(ctx, c.quote, done),
441
+ claimable: await units(ctx, c.quote, total > done ? total - done : 0n),
442
+ ...(/^\d+$/.test(String(m.pendingCumulative ?? '')) && { totalOnceInEffect: await units(ctx, c.quote, BigInt(m.pendingCumulative)) }),
443
+ next: `gang promote claim-pool --module ${m.module}${tn}`,
444
+ })
445
+ }
446
+ return out({
447
+ success: true, chainId, wallet: who,
448
+ curve: curve.error ? { error: curve.error, retry: `gang promote earnings${tn}` } : { ...curve, ...(curve.tokens.length && { next: `gang promote claim --token <addr>${tn}` }) },
449
+ pool: pool.error ? { error: `gang.fun pool data unavailable (${pool.error})`, hint: `gang promote status --token <addr>${tn} still reads the chain` } : { modules },
450
+ note: 'pool amounts come from gang.fun and are not checked here; a claim checks them against the root on chain',
451
+ })
452
+ }
453
+
454
+ // --- one token or one module
455
+ if (flag('token') && flag('module')) fail('give --token (its tax recipient is the module) or --module, not both')
456
+ let token = null, module = null, creator = null, quote = null, dividendPct = 0, gradDone = false
457
+ if (flag('module')) {
458
+ if (sub === 'bind' || sub === 'claim') fail(`gang promote ${sub} needs --token <the token>`)
459
+ module = opt('module')
460
+ if (!isAddress(module ?? '')) fail('--module must be a promoter pool module address (0x…)', { got: module ?? null })
461
+ module = getAddress(module)
462
+ } else {
463
+ token = opt('token')
464
+ if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…), or name the module with --module <addr>', { got: token ?? null })
465
+ token = getAddress(token)
466
+ if ((await atTokenPad(ctx, token)) === null) return fail(KIND_UNREAD.error, { token, retry: KIND_UNREAD.retry })
467
+ try {
468
+ const c = await ctx.read(ctx.pad, PAD_READS, 'curves', [token])
469
+ if (c[0] === zeroAddress) throw new Error('not a curve')
470
+ ;[creator, quote] = c
471
+ gradDone = c[6]
472
+ dividendPct = Number(c[9]) / 100
473
+ module = (await ctx.read(ctx.pad, PAD_READS, 'taxConfigOf', [token]))[3]
474
+ } catch {
475
+ return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet'}${testnet ? '' : '; add --testnet for a testnet token'})`, { token, chainId })
476
+ }
477
+ }
478
+ const ref = `${token ? `--token ${token}` : `--module ${module}`}${tn}`
479
+
480
+ // the curve side needs only the pad
481
+ if (sub === 'claim') {
482
+ const who = me()
483
+ const to = toArg()
484
+ const owed = await ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'promoterFeeOf', [token, who]).catch((e) => {
485
+ if (isMissingRead(e)) return null
486
+ return fail('could not read the promoter share (RPC error)', { token, detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' })
487
+ })
488
+ if (owed === null) return fail(`GangLaunchpad ${ctx.gen ?? ctx.pad} has no promoter share (only a 3.0 pad upgraded for it does)`, { token })
489
+ if (owed === 0n) return fail('this wallet has no curve share to claim on this token', { token, wallet: who, hint: `pool income is claimed with gang promote claim-pool ${ref}` })
490
+ const sim = await simulatePool(ctx.client, who, ctx.pad, PROMOTE_PAD_ABI, 'claimPromoterFee', [token, to])
491
+ if (sim.failed) return out({ success: false, step: 'claim-promoter-fee', ...sim.failed })
492
+ const data = encodeFunctionData({ abi: PROMOTE_PAD_ABI, functionName: 'claimPromoterFee', args: [token, to] })
493
+ return out(step(ctx, { from: who, to: ctx.pad, data }, {
494
+ step: 'claim-promoter-fee', chainId, token, amount: await units(ctx, quote, owed), to,
495
+ note: 'claims all of it, in the token\'s quote; it keeps growing with later curve trades of wallets you brought',
496
+ }, rawOnly, summarize))
497
+ }
498
+
499
+ const factory = poolFactoryAddress(testnet)
500
+ const s = await poolOf(ctx.read, getCode, module, factory).catch((e) => fail('could not read the module (RPC error)', { module, detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' }))
501
+ // the pool side: only a module of the factory this CLI knows, and bound to this very token
502
+ const decoy = token && s?.token && s.token.toLowerCase() !== token.toLowerCase()
503
+ const poolLive = !!s && !decoy && !s.closed
504
+ const q = s?.quote ?? quote
505
+ const f = async (x) => (q ? units(ctx, q, x) : x.toString())
506
+ const now = Number((await ctx.client.getBlock({ blockTag: 'latest' })).timestamp)
507
+
508
+ if (sub === 'status') {
509
+ if (!token && !s) return fail('not a promoter pool module of this CLI\'s factory', { module, factory })
510
+ let t = null
511
+ if (token) {
512
+ try { t = await promoteTermsOf(ctx, token) } catch (e) { return fail('could not read the promoter terms (RPC error)', { token, detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' }) }
513
+ }
514
+ if (token && !t) return fail(`GangLaunchpad ${ctx.gen ?? ctx.pad} has no promoter share (only a 3.0 pad upgraded for it does)`, { token })
515
+ const who = flag('from') || flag('wallet') ? (opt('wallet') ?? opt('from')) : (() => { try { return me() } catch { return null } })()
516
+ const wallet = isAddress(who ?? '') ? getAddress(who) : null
517
+ const res = {
518
+ success: true, chainId, ...(token && { token, sharePct: t.sharePct, windowDays: t.windowDays, graduated: gradDone }),
519
+ ...(token && t.shareBps === 0 && { note: 'this token was made without promoter terms' }),
520
+ }
521
+ if (token && t.shareBps > 0 && wallet) {
522
+ const [b, fee] = await Promise.all([ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'bindingOf', [token, wallet]), ctx.read(ctx.pad, PROMOTE_PAD_ABI, 'promoterFeeOf', [token, wallet])])
523
+ res.wallet = wallet
524
+ res.binding = formatBinding(b[0], b[1], b[2], t.windowDays * DAY, now, gradDone)
525
+ res.curve = { claimable: await units(ctx, quote, fee), ...(fee > 0n && { next: `gang promote claim ${ref}` }) }
526
+ }
527
+ if (s) {
528
+ const pool = formatPool({ ...s, escrowIn: s.escrowIn }, (x) => x, now, ref)
529
+ const conv = async (k) => { pool[k] = await f(pool[k]) }
530
+ await Promise.all(['escrowed', 'reclaimed', 'claimedTotal', 'devOwed', 'waitingToSplit'].map(conv))
531
+ if (pool.root) pool.root.allocated = await f(pool.root.allocated)
532
+ if (pool.pending) pool.pending.allocated = await f(pool.pending.allocated)
533
+ res.pool = pool
534
+ if (decoy) res.pool.warning = `this token pays its tax to the module, but the module is bound to another token (${s.token}): this token's promoters earn nothing from the pool`
535
+ } else if (token) {
536
+ res.pool = { poolShare: false, note: 'this token\'s tax recipient is not a promoter pool module of this CLI\'s factory: the share stays on the curve' }
537
+ }
538
+ if (s && wallet) {
539
+ const done = await ctx.read(s.module, POOL_ABI, 'claimed', [wallet])
540
+ const a = await apiOr(`/promote-pool/proof?${new URLSearchParams({ module: s.module, account: wallet })}`)
541
+ // gang.fun's amount counts only with a proof of the root on chain; a bad answer costs this part, not the chain's data
542
+ // a root past its dispute window that nobody activated yet is in effect for gang.fun, and claim-pool activates it first
543
+ const due = s.pendingRoot !== NO_ROOT && Number(s.pendingActiveAt) <= now
544
+ const active = a.active && (provenAmount(s.root, wallet, a.active) ?? (due ? provenAmount(s.pendingRoot, wallet, a.active) : null))
545
+ const pendingAmount = /^\d+$/.test(String(a.pending?.cumulative ?? '')) ? BigInt(a.pending.cumulative) : null
546
+ res.poolClaim = a.error
547
+ ? { claimed: await f(done), error: `gang.fun pool data unavailable (${a.error})` }
548
+ : {
549
+ claimed: await f(done),
550
+ ...(active !== null && active !== undefined && { allocated: await f(active), ...(active > done && { next: `gang promote claim-pool ${ref}` }) }),
551
+ ...(a.active && active === null && { warning: 'gang.fun\'s amount does not match the root on chain: not shown. Try again shortly' }),
552
+ ...(pendingAmount !== null && { totalOnceInEffect: await f(pendingAmount), totalOnceInEffectNote: 'this account\'s whole total under the root in its dispute window, not an addition; from gang.fun, unchecked', activeAt: iso(a.pending.activeAt) }),
553
+ }
554
+ }
555
+ return out(res)
556
+ }
557
+
558
+ if (!s) {
559
+ return fail(token ? 'this token\'s tax recipient is not a promoter pool module of this CLI\'s factory' : 'not a promoter pool module of this CLI\'s factory',
560
+ { ...(token && { token }), recipient: module === zeroAddress ? null : module, factory })
561
+ }
562
+ if (decoy) return fail(`the module is bound to another token (${s.token}), not this one: nothing here is owed to this token's promoters`, { token, module })
563
+
564
+ const who = me()
565
+ const send = async (functionName, args, extra) => {
566
+ const sim = await simulatePool(ctx.client, who, s.module, POOL_ABI, functionName, args)
567
+ if (sim.failed) return out({ success: false, step: extra.step, ...sim.failed })
568
+ const data = encodeFunctionData({ abi: POOL_ABI, functionName, args })
569
+ // no gas field: the wallet / node estimates it (GAS_NOTE)
570
+ return out(step(ctx, { from: who, to: s.module, data }, { chainId, ...(token && { token }), module: s.module, ...extra }, rawOnly, summarize))
571
+ }
572
+
573
+ if (sub === 'bind') {
574
+ if (s.token) return fail('already bound', { boundTo: s.token })
575
+ return send('bind', [token], { step: 'bind', note: 'anyone may bind (once), before graduation only. A token bound later has no pool share' })
576
+ }
577
+
578
+ if (sub === 'activate') {
579
+ if (s.pendingRoot === NO_ROOT) return fail(HINTS.NothingPending, { module: s.module })
580
+ if (Number(s.pendingActiveAt) > now) return fail(HINTS.TooEarly, { module: s.module, activeAt: iso(s.pendingActiveAt) })
581
+ return send('activate', [], { step: 'activate', root: s.pendingRoot, note: 'anyone may: puts the root in effect now its dispute window is over' })
582
+ }
583
+
584
+ if (sub === 'work') {
585
+ if (s.undistributed === 0n && !(gradDone && Number(s.firstGradSeenAt) === 0)) return fail('nothing has arrived since the last split', { module: s.module, ...(token && { token }) })
586
+ return send('work', [0n], {
587
+ step: 'work', amount: await f(s.undistributed),
588
+ note: `anyone may: ${s.escrowOpen ? `escrows ${Number(s.shareBps) / 100}% of what arrived and pushes the rest to the dev` : 'escrow is over: all of it goes to the dev'}. Gas: ${GAS_NOTE}`,
589
+ })
590
+ }
591
+
592
+ if (sub === 'sweep') {
593
+ const a = opt('asset')
594
+ if (!isAddress(a ?? '') || a === zeroAddress) fail('--asset must be a token address (0x…)', { got: a ?? null })
595
+ return send('sweep', [getAddress(a)], { step: 'sweep', asset: getAddress(a), note: 'anyone may: sends the module\'s whole balance of that asset to the dev. Never the bound quote' })
596
+ }
597
+
598
+ if (sub === 'release-dev') {
599
+ if (s.devOwed === 0n) return fail(HINTS.NothingOwed, { module: s.module })
600
+ const to = toArg()
601
+ return send('releaseDev', [to], { step: 'release-dev', amount: await f(s.devOwed), to, note: 'the dev only: sends what failed pushes left here' })
602
+ }
603
+
604
+ if (sub === 'reclaim') {
605
+ if (s.dev.toLowerCase() !== String(who).toLowerCase()) return fail(HINTS.NotDev, { dev: s.dev, wallet: who })
606
+ if (s.closed) return fail(HINTS.Closed, { module: s.module })
607
+ const to = toArg()
608
+ // the simulation's answer: reclaim first activates a due root and splits what arrived
609
+ const preview = await simulatePool(ctx.client, who, s.module, POOL_ABI, 'reclaim', [to])
610
+ return send('reclaim', [to], {
611
+ step: 'reclaim', to, ...(preview.result !== undefined && { amount: await f(preview.result) }),
612
+ warning: 'PERMANENT: this closes the module for good. No more roots can be posted, promoters lose what no root allocated, and every later arrival goes to you. Roots in effect keep paying',
613
+ note: `the dev only, once graduation was seen and the settler has been silent for 30 days. Gas: ${GAS_NOTE}`,
614
+ })
615
+ }
616
+
617
+ // claim-pool
618
+ const account = getAddress(who)
619
+ const done = await ctx.read(s.module, POOL_ABI, 'claimed', [account])
620
+ // a root whose window is over isn't in effect until something activates it: a claim would do it, but its proof must be for that root
621
+ if (s.pendingRoot !== NO_ROOT && Number(s.pendingActiveAt) <= now) {
622
+ return send('activate', [], {
623
+ step: 'activate', root: s.pendingRoot, next: `re-run this same command after executing it: gang promote claim-pool ${ref}`,
624
+ note: 'a newer root\'s dispute window is over: this puts it in effect first (anyone may), then the claim can use it',
625
+ })
626
+ }
627
+ let cumulative, proof
628
+ if (flag('cumulative')) {
629
+ const raw = opt('cumulative')
630
+ if (!/^\d+$/.test(raw ?? '')) fail('--cumulative takes the account\'s total in the root, in wei', { got: raw ?? null })
631
+ cumulative = BigInt(raw)
632
+ proof = String(opt('proof', '')).split(',').map((x) => x.trim()).filter(Boolean)
633
+ if (proof.some((p) => !isHash(p))) fail('--proof takes comma-separated 32-byte hashes', { got: opt('proof') ?? null })
634
+ } else {
635
+ const a = await apiOr(`/promote-pool/proof?${new URLSearchParams({ module: s.module, account })}`)
636
+ if (a.error) {
637
+ return fail(`gang.fun pool data unavailable (${a.error})`, {
638
+ hint: `anyone can recompute the root from chain logs (scripts/promote-settle in gang-launchpad), then gang promote claim-pool ${ref} --cumulative <wei> --proof <hash,hash>`,
639
+ })
640
+ }
641
+ if (!a.active) {
642
+ return fail('no root in effect names this account yet', {
643
+ module: s.module, account,
644
+ ...(s.root !== NO_ROOT && { hint: `if a root should name this account, gang.fun may be behind: try again, or recompute it from chain logs and give --cumulative and --proof` }),
645
+ ...(/^\d+$/.test(String(a.pending?.cumulative ?? '')) && { totalOnceInEffect: await f(BigInt(a.pending.cumulative)), activeAt: iso(a.pending.activeAt), hint: 'claim after the dispute window' }),
646
+ })
647
+ }
648
+ if (provenAmount(s.root, account, a.active) === null) {
649
+ return fail('that amount and proof do not match the root on chain: nothing was built', {
650
+ module: s.module, account, rootOnChain: s.root, hint: 'gang.fun may be behind the chain: try again shortly',
651
+ })
652
+ }
653
+ cumulative = BigInt(a.active.cumulative)
654
+ proof = a.active.proof
655
+ }
656
+ // the root on chain decides, not what gang.fun said
657
+ if (s.root === NO_ROOT) return fail('no root is in effect on chain yet', { module: s.module })
658
+ if (!verifyProof(s.root, leafOf(account, cumulative), proof)) {
659
+ return fail('that amount and proof do not match the root on chain: nothing was built', {
660
+ module: s.module, account, rootOnChain: s.root, hint: 'gang.fun may be behind the chain: try again shortly',
661
+ })
662
+ }
663
+ if (cumulative <= done) return fail(HINTS.NothingToClaim, { module: s.module, account, claimed: await f(done) })
664
+ const to = toArg()
665
+ return send('claim', [cumulative, proof, to], {
666
+ step: 'claim-pool', account, to, amount: await f(cumulative - done), cumulative: await f(cumulative), claimedBefore: await f(done), throughBlock: Number(s.throughBlock),
667
+ note: 'claims what the root in effect gives this account beyond what it already claimed',
668
+ })
669
+ }