@gangfun/cli 0.43.1 → 0.44.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.
@@ -0,0 +1,762 @@
1
+ import { createPublicClient, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, parseAbi, parseUnits, zeroAddress } from 'viem'
2
+ import { walletFor } from './fair.js'
3
+ import { atTokenPad, gangGens, KIND_UNREAD, NOT_ON_MAINNET, padNets, rpcTransport } from './gangpad.js'
4
+ import { decimalsOf, fundingStep, GAS_RESERVE, revertOf as revertIn, routerDeadline, step } from './steps.js'
5
+
6
+ /**
7
+ * 倒计时奖励, the countdown reward (GangCountdownReward, `countdown-v1`; docs/SPEC-COUNTDOWN-REWARD-2026-11-17.md): one
8
+ * V3 token's tax recipient that turns the recipient's part of the pool tax (the dev's own share) into a reward pool for
9
+ * the token's buyers, and that is also the buy entry that counts. A buy through the module (`buy` with BNB on a
10
+ * WBNB-quoted token, `buyWithQuote` otherwise; after graduation only, on the token's own pair) of at least `minBuy` is
11
+ * counted: it puts the round's deadline `window` ahead, never past the round's cap (its first counted buy + `maxRound`).
12
+ * Once the deadline passes, the round's last `entries` counted buys share min(pool × payoutBps, maxPayout): an equal
13
+ * share each, the newest `lastBps` of it on top (a round that ended at its cap: equal shares, no extra). Buys through
14
+ * PancakeSwap's router, an aggregator or GangRouter never count. A reward paid by fixed public rules from the dev's tax
15
+ * share: buyers buy the token at the pool price and pay the usual buy tax, nothing extra.
16
+ * The token is fixed when the module is cloned (`rewardToken`, its CREATE2 address before it exists), as the floor
17
+ * module's: a launch computes the token's address first, clones the module for it, creates the token at that address,
18
+ * then binds (launch.js). A module is a countdown module only when GangCountdownRewardFactory listed it
19
+ * (GangHandlerAdmin.moduleOf), as for the floor module: a contract that merely answers `countdown-v1` is not one.
20
+ * Env: GANG_COUNTDOWN_FACTORY / GANG_TESTNET_COUNTDOWN_FACTORY (gangpad.js).
21
+ */
22
+
23
+ export const COUNTDOWN_TYPE = 'countdown-v1'
24
+ const BPS = 10_000
25
+ const MIN = 60, HOUR = 3600, DAY = 86_400
26
+ export const BOUNDS = {
27
+ window: [30 * MIN, 24 * HOUR], maxRound: [HOUR, 24 * HOUR], idle: [7 * DAY, 90 * DAY],
28
+ payoutBps: [1_000, 5_000], lastBps: [0, 2_000], devBps: [0, 5_000], entries: [1, 20],
29
+ }
30
+ /** The user's defaults (2026-11-17): minBuy / minPot in BNB, for a WBNB-quoted token only. */
31
+ export const DEFAULTS = { window: 60 * MIN, maxRound: 6 * HOUR, idle: 30 * DAY, payoutBps: 3_000, lastBps: 2_000, devBps: 0, entries: 10, minBuy: '0.05', minPot: '0.1' }
32
+
33
+ const CFG = '(uint64 window, uint64 maxRound, uint64 idle, uint16 payoutBps, uint16 lastBps, uint16 devBps, uint8 entries, uint256 minBuy, uint256 minPot, uint256 maxPayout)'
34
+ const ERRORS = [
35
+ 'error ZeroAddress()', 'error NotClone()', 'error NotFactory()', 'error AlreadyInitialized()', 'error BadQuote()',
36
+ 'error BadConfig()', 'error AlreadyBound()', 'error NotBound()', 'error WrongToken()', 'error NotCurve()',
37
+ 'error NotCreator()', 'error WrongQuote()', 'error NothingForRecipient()', 'error NotRecipient()', 'error NotTradable()',
38
+ 'error NotWbnb()', 'error Expired()', 'error ZeroAmount()', 'error Slippage()', 'error NothingToClaim()', 'error NotDue()',
39
+ 'error NotCounted()',
40
+ ]
41
+ export const COUNTDOWN_FACTORY_ABI = parseAbi([
42
+ `function create(address token, address quote, ${CFG} config, bytes32 salt) returns (address module)`,
43
+ 'function predict(address dev, bytes32 salt) view returns (address)',
44
+ 'function pad() view returns (address)',
45
+ 'function admin() view returns (address)',
46
+ 'function implementation() view returns (address)',
47
+ 'function vanityEnabled() view returns (bool)',
48
+ 'error NotAgent()', 'error WrongHandler()', 'error NoVanityDeployer()', 'error BadToken()',
49
+ `event Created(address indexed dev, address indexed module, address indexed token, address quote, ${CFG} config)`,
50
+ ...ERRORS,
51
+ ])
52
+ export const COUNTDOWN_ABI = parseAbi([
53
+ 'function moduleType() view returns (bytes32)',
54
+ 'function pad() view returns (address)',
55
+ 'function factory() view returns (address)',
56
+ `function config() view returns (${CFG})`,
57
+ 'function dev() view returns (address)',
58
+ 'function rewardToken() view returns (address)',
59
+ 'function rewardQuote() view returns (address)',
60
+ 'function token() view returns (address)',
61
+ 'function quote() view returns (address)',
62
+ 'function pot() view returns (uint256)',
63
+ 'function potAvailable() view returns (uint256)',
64
+ 'function reservedTotal() view returns (uint256)',
65
+ 'function claimTotal() view returns (uint256)',
66
+ 'function devOwed() view returns (uint256)',
67
+ 'function claimableOf(address) view returns (uint256)',
68
+ 'function cur() view returns (uint8)',
69
+ 'function deadline() view returns (uint64)',
70
+ 'function lastRoundId() view returns (uint64)',
71
+ 'function lastCountedAt() view returns (uint64)',
72
+ 'function lastFinalizedAt() view returns (uint64)',
73
+ 'function currentRound() view returns (uint64)',
74
+ 'function roundEndsBy() view returns (uint64)',
75
+ 'function round(uint8 b) view returns (uint64 id, uint32 count, bool frozen, bool settled, uint256 reserved, (address buyer, uint96 tokens)[] list)',
76
+ 'function wouldCount(uint256 quoteIn) view returns (bool)',
77
+ 'function previewWork() view returns (bool due, uint256 minOut)',
78
+ 'function keeperServes(address q) view returns (bool)',
79
+ 'function buy(uint256 minTokensOut, uint256 deadline, bool mustCount) payable returns (uint256 tokensOut)',
80
+ 'function buyWithQuote(uint256 quoteIn, uint256 minTokensOut, uint256 deadline, bool mustCount) returns (uint256 tokensOut)',
81
+ 'function claim(address to) returns (uint256 amount)',
82
+ 'function fund(uint256 amount)',
83
+ 'function bind(address token)',
84
+ 'function settle()',
85
+ 'function finalize()',
86
+ 'function claimDev() returns (uint256 amount)',
87
+ 'function work(uint256)',
88
+ 'function distribute(address asset) returns (uint256 amount)',
89
+ 'event Bound(address indexed token, address indexed quote)',
90
+ 'event Funded(address indexed from, uint256 amount)',
91
+ 'event TaxBooked(uint256 incoming, uint256 toPot, uint256 toDev)',
92
+ 'event Shortfall(uint256 amount)',
93
+ 'event RoundStarted(uint64 indexed round)',
94
+ 'event Counted(uint64 indexed round, address indexed buyer, uint256 quoteIn, uint256 tokensOut, uint64 deadline)',
95
+ 'event RoundFrozen(uint64 indexed round, uint256 payout, uint256 entries)',
96
+ 'event Settled(uint64 indexed round, uint256 payout, uint256 credited, uint256 dust)',
97
+ 'event Finalized(uint64 indexed round, uint256 payout)',
98
+ 'event Credited(address indexed buyer, uint64 indexed round, uint256 amount)',
99
+ 'event Claimed(address indexed buyer, address indexed to, uint256 amount)',
100
+ 'event DevClaimed(address indexed dev, uint256 amount)',
101
+ 'event Distributed(address indexed asset, uint256 amount)',
102
+ ...ERRORS,
103
+ ])
104
+ /** gang tx decodes these (the factory's Created and the module's own events). */
105
+ export const COUNTDOWN_EVENT_ABIS = [COUNTDOWN_FACTORY_ABI, COUNTDOWN_ABI]
106
+
107
+ const PAIR_ABI = parseAbi(['function getReserves() view returns (uint112, uint112, uint32)', 'function token0() view returns (address)'])
108
+ const PAD_ABI = parseAbi([
109
+ '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)',
110
+ 'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
111
+ 'function PLATFORM_TAX_BPS() view returns (uint256)',
112
+ ])
113
+ const ERC20_ABI = parseAbi(['function symbol() view returns (string)', 'function decimals() view returns (uint8)'])
114
+
115
+ export const HINTS = {
116
+ NotAgent: 'only an Agent can create a V3 token, so only an Agent gets a countdown reward module',
117
+ NotFactory: 'this countdown factory is not allowed on the platform\'s GangHandlerAdmin: it cannot list a module as a tax recipient. If GANG_COUNTDOWN_FACTORY / GANG_TESTNET_COUNTDOWN_FACTORY is set, unset or fix it; otherwise launch without --countdown-reward',
118
+ NoVanityDeployer: 'this pad does not create its tokens at an address known in advance (its CREATE2 deployer is not on): a countdown module is cloned for one token address, so --countdown-reward is not available here yet',
119
+ BadToken: 'the token address a countdown module is cloned for must end in abcd and have no token at it yet: the launch computes it; run it again (or add --restart)',
120
+ BadConfig: 'a --cd-* setting is out of bounds: window 30m–24h; max round 1h–24h and at least the window; idle 7–90 days; payout 10–50%; last 0–20%; dev 0–50%; entries 1–20; min buy and max payout above 0',
121
+ BadQuote: 'the reward pool\'s quote must be WBNB, GANG or a quote in the pad\'s QuoteRegistry: a launch with --countdown-reward needs one of those as its quote',
122
+ AlreadyBound: 'the countdown module is bound to its token already',
123
+ NotBound: 'the countdown module is not bound to its token yet: nothing is counted, funded or paid before that (the launch binds it right after the create)',
124
+ WrongToken: 'a countdown module serves only the token it was cloned for (rewardToken): this is another token',
125
+ NotCurve: 'the token the countdown module was cloned for is not created yet (or is not a V3 curve token on this pad)',
126
+ NotCreator: 'the token at the module\'s address was not created by the module\'s dev',
127
+ NotRecipient: 'the token does not pay its tax to this countdown module',
128
+ WrongQuote: 'the token\'s quote (or its pair\'s other token) is not the countdown module\'s quote',
129
+ NothingForRecipient: 'the token gives all of its tax to the holders\' dividend (--dividend 100): nothing would ever reach the reward pool',
130
+ NotTradable: 'the token has not graduated: buys through the countdown module (and the countdown) start once it trades in its PancakeSwap pair',
131
+ NotWbnb: 'only a WBNB-quoted token takes BNB: pay with the token\'s quote',
132
+ Expired: 'the buy\'s deadline passed before it landed: run gang buy again',
133
+ ZeroAmount: 'the amount is 0, or too small to buy a single token unit',
134
+ Slippage: 'the price moved past --slippage before the buy landed: run gang buy again to re-quote',
135
+ NothingToClaim: 'nothing to claim for this wallet',
136
+ NotDue: 'nothing is due yet: the running round has not passed its deadline, or for finalize: not idle long enough, or the pool is under its minimum',
137
+ NotCounted: 'the buy would not be counted (below the minimum buy, or the pool is under its minimum and no round runs), and it asked to count: nothing is bought. Add --cd-uncounted to buy through the module anyway without counting',
138
+ }
139
+ export const revertOf = (e) => revertIn(e, [COUNTDOWN_ABI, COUNTDOWN_FACTORY_ABI], HINTS)
140
+
141
+ /** Dry-run a call; { result } or { failed } with the revert. */
142
+ export async function simulateCountdown(client, from, address, abi, functionName, args = [], value = 0n) {
143
+ try {
144
+ const { result } = await client.simulateContract({ account: from, address, abi, functionName, args, value })
145
+ return { result }
146
+ } catch (e) {
147
+ const r = revertOf(e)
148
+ return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
149
+ }
150
+ }
151
+
152
+ /** The create target's countdown factory, or null when this network has none in this CLI version (mainnet now). */
153
+ export const countdownFactoryAddress = (testnet) => gangGens(testnet)[0].countdownFactory || null
154
+ export const countdownNotLive = (testnet) => (testnet
155
+ ? 'the countdown reward (countdown-v1) has no factory on the BSC testnet in this CLI version: set GANG_TESTNET_COUNTDOWN_FACTORY to its address'
156
+ : 'the countdown reward (countdown-v1) has no factory on BSC mainnet for this pad in this CLI version: set GANG_COUNTDOWN_FACTORY to its address')
157
+
158
+ // ---- the wording (the user's framing: the dev's own tax share becomes the buyers' reward, paid by fixed public rules)
159
+ export const WHAT_IT_IS = 'the dev turned its own share of the pool tax into a reward for buyers: when the countdown runs out, the last counted buys share this round\'s reward by a fixed public rule. Buyers pay only the pool price and the usual buy tax, nothing extra, and keep the tokens they buy. Who gets what follows from the order of counted buys alone, by rules anyone can read on chain'
160
+ export const ONLY_GANG_BUYS = 'only buys through the countdown module count, as the gang CLI and MCP send them (gang buy): a buy on PancakeSwap\'s own router, through an aggregator or through GangRouter is a normal buy and never counts'
161
+ export const MULTI_WALLET_NOTE = 'anyone, the dev included, can take several reward slots with several wallets: each slot only costs a counted buy (at least the minimum buy, paying the buy tax), and the same wallet may hold several slots'
162
+ export const CAPPED_NOTE = 'a round that keeps getting buys ends at its cap (its first counted buy + the max round time): that end time is public in advance, so its last slots favour whoever controls the order of the last block (block builders, private relays, bundles). For that reason a round that ends at its cap pays all its slots equally, with no extra for the last buy'
163
+ export const POOL_GROWS_NOTE = 'the pool grows only when the held tax is sold: on pool sells, or by the keeper in small chunks; with buys alone it grows slowly'
164
+ export const SELL_NOTE = 'sells never take out a buyer\'s slots and there is no holding check: a slot stays in its round whether or not the wallet still holds the tokens'
165
+ export const PERMANENT_NOTE = 'PERMANENT: the token it serves, the quote and every setting (window, max round, idle, payout %, last-buy %, dev %, slots, minimum buy, minimum pool, max payout) are fixed for good — nobody (not you, not the platform) can change them or take the pool out. Credited rewards never expire'
166
+ export const UNCHECKED_NOTE = 'could not check whether GangCountdownRewardFactory made this module (RPC error): nothing is shown or built until it is known — run the same command again'
167
+ export const UNVERIFIED_NOTE = 'this contract says it is a countdown reward module, but GangCountdownRewardFactory did not make it (GangHandlerAdmin.moduleOf): its numbers are its own claims, and this CLI builds no buy or other call against it'
168
+
169
+ // ---- the launch's flags
170
+
171
+ export const CD_FLAGS = ['cd-window', 'cd-max-round', 'cd-idle', 'cd-payout', 'cd-last', 'cd-dev', 'cd-entries', 'cd-min-buy', 'cd-min-pot', 'cd-max-payout', 'cd-seed', 'cd-seed-again']
172
+ export const CD_USAGE = '--countdown-reward --cd-max-payout <amount> [--cd-window 60m] [--cd-max-round 6h] [--cd-idle 30d] [--cd-payout 30] [--cd-last 20] [--cd-dev 0] [--cd-entries 10] [--cd-min-buy 0.05] [--cd-min-pot 0.1] [--cd-seed <amount>]'
173
+ export const CD_ALONE = '--cd-* settings go with --countdown-reward (a launch whose tax recipient is a countdown reward module)'
174
+
175
+ const NUM_RE = /^(\d+(\.\d*)?|\.\d+)$/
176
+ const PCT_RE = /^(\d{1,3})(?:\.(\d{1,2}))?$/
177
+ const pctBps = (raw) => {
178
+ const m = PCT_RE.exec(String(raw ?? '').trim())
179
+ return m ? Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0')) : null
180
+ }
181
+ /** "60m" / "1h" / "90" (minutes) → seconds; days with `unit` 'd' ("30d" / "30"). null when not a whole number of them. */
182
+ export function parseDuration(raw, unit = 'm') {
183
+ const m = /^(\d+)\s*([mhd])?$/i.exec(String(raw ?? '').trim())
184
+ if (!m) return null
185
+ const u = (m[2] ?? unit).toLowerCase()
186
+ return Number(m[1]) * { m: MIN, h: HOUR, d: DAY }[u]
187
+ }
188
+ const human = (s) => (s % DAY === 0 ? `${s / DAY}d` : s % HOUR === 0 ? `${s / HOUR}h` : `${s / MIN}m`)
189
+
190
+ /**
191
+ * The --countdown-reward launch's --cd-* flags → { window, maxRound, idle, payoutBps, lastBps, devBps, entries, minBuy,
192
+ * minPot, maxPayout, seed } (amounts as typed; minBuy / minPot null = the BNB default), or { error }. Bounds as
193
+ * GangCountdownReward.initialize checks them.
194
+ */
195
+ export function parseCountdownSpec(opt, flag) {
196
+ const dur = (name, def, unit, [lo, hi], what) => {
197
+ if (!flag(name)) return { v: def }
198
+ const s = parseDuration(opt(name), unit)
199
+ const hm = (x) => (unit === 'd' ? `${x / DAY}d` : x % HOUR === 0 ? `${x / HOUR}h` : `${x / MIN}m`)
200
+ if (s === null || s < lo || s > hi) return { error: `--${name} must be ${what} (${hm(lo)}–${hm(hi)}; e.g. ${unit === 'd' ? '30d' : '60m or 1h'})`, got: opt(name) ?? null }
201
+ return { v: s }
202
+ }
203
+ const pct = (name, def, [lo, hi], what) => {
204
+ if (!flag(name)) return { v: def }
205
+ const b = pctBps(opt(name))
206
+ if (b === null || b < lo || b > hi) return { error: `--${name} must be ${what}: ${lo / 100} to ${hi / 100} (in %, at most 2 decimals)`, got: opt(name) ?? null }
207
+ return { v: b }
208
+ }
209
+ const amount = (name, { required = false, zero = false } = {}) => {
210
+ if (!flag(name)) return required ? { error: `--${name} <amount> is required: ${name === 'cd-max-payout' ? 'the most one round can ever pay, in the token\'s quote (e.g. --cd-max-payout 1)' : 'an amount of the token\'s quote'}` } : { v: null }
211
+ const raw = String(opt(name) ?? '').trim()
212
+ if (!NUM_RE.test(raw) || (!zero && !(Number(raw) > 0))) return { error: `--${name} must be ${zero ? 'an amount (0 or more)' : 'a positive amount'} of the token's quote`, got: opt(name) ?? null }
213
+ return { v: raw }
214
+ }
215
+ const window = dur('cd-window', DEFAULTS.window, 'm', BOUNDS.window, 'how long after each counted buy the countdown runs out')
216
+ if (window.error) return window
217
+ const maxRound = dur('cd-max-round', DEFAULTS.maxRound, 'm', BOUNDS.maxRound, 'the longest a round can run from its first counted buy')
218
+ if (maxRound.error) return maxRound
219
+ if (maxRound.v < window.v) return { error: `--cd-max-round (${human(maxRound.v)}) must be at least --cd-window (${human(window.v)})` }
220
+ const idle = dur('cd-idle', DEFAULTS.idle, 'd', BOUNDS.idle, 'the days with no counted buy after which the last round can be paid again (finalize)')
221
+ if (idle.error) return idle
222
+ const payout = pct('cd-payout', DEFAULTS.payoutBps, BOUNDS.payoutBps, 'the % of the pool a round pays')
223
+ if (payout.error) return payout
224
+ const last = pct('cd-last', DEFAULTS.lastBps, BOUNDS.lastBps, 'the % of a round\'s payout the last counted buy gets on top')
225
+ if (last.error) return last
226
+ const devPart = pct('cd-dev', DEFAULTS.devBps, BOUNDS.devBps, 'the % of the arriving tax you keep (the rest goes to the pool)')
227
+ if (devPart.error) return devPart
228
+ let entries = DEFAULTS.entries
229
+ if (flag('cd-entries')) {
230
+ const n = Number(opt('cd-entries'))
231
+ if (!Number.isInteger(n) || n < BOUNDS.entries[0] || n > BOUNDS.entries[1]) return { error: '--cd-entries must be an integer between 1 and 20 (how many of a round\'s last counted buys share it)', got: opt('cd-entries') ?? null }
232
+ entries = n
233
+ }
234
+ const minBuy = amount('cd-min-buy')
235
+ if (minBuy.error) return minBuy
236
+ const minPot = amount('cd-min-pot', { zero: true })
237
+ if (minPot.error) return minPot
238
+ const maxPayout = amount('cd-max-payout', { required: true })
239
+ if (maxPayout.error) return maxPayout
240
+ const seed = amount('cd-seed')
241
+ if (seed.error) return seed
242
+ return {
243
+ window: window.v, maxRound: maxRound.v, idle: idle.v, payoutBps: payout.v, lastBps: last.v, devBps: devPart.v, entries,
244
+ minBuy: minBuy.v, minPot: minPot.v, maxPayout: maxPayout.v, seed: seed.v,
245
+ }
246
+ }
247
+
248
+ /**
249
+ * The spec in the quote's units → { config (the contract's Config), seed (bigint, 0n for none), defaults: [notes] } or
250
+ * { error }. The minimum buy / pool defaults are BNB amounts: only a WBNB-quoted token takes them as they are; any other
251
+ * quote needs them given.
252
+ */
253
+ export function countdownConfig(spec, { decimals, wbnbQuoted, symbol = 'the quote' }) {
254
+ const notes = []
255
+ const amt = (raw, name, def) => {
256
+ if (raw !== null) return parseUnits(raw, decimals)
257
+ if (!wbnbQuoted) return { error: `--${name} <amount> is required on a token quoted in ${symbol}: its default (${def} BNB) is a BNB amount` }
258
+ notes.push(`--${name} left out: ${def} BNB`)
259
+ return parseUnits(def, 18)
260
+ }
261
+ const minBuy = amt(spec.minBuy, 'cd-min-buy', DEFAULTS.minBuy)
262
+ if (minBuy.error) return minBuy
263
+ const minPot = amt(spec.minPot, 'cd-min-pot', DEFAULTS.minPot)
264
+ if (minPot.error) return minPot
265
+ const maxPayout = parseUnits(spec.maxPayout, decimals)
266
+ if (minBuy === 0n) return { error: '--cd-min-buy rounds to 0 in the quote\'s decimals', got: spec.minBuy }
267
+ if (maxPayout === 0n) return { error: '--cd-max-payout rounds to 0 in the quote\'s decimals', got: spec.maxPayout }
268
+ const seed = spec.seed ? parseUnits(spec.seed, decimals) : 0n
269
+ if (spec.seed && seed === 0n) return { error: '--cd-seed rounds to 0 in the quote\'s decimals', got: spec.seed }
270
+ return {
271
+ config: {
272
+ window: BigInt(spec.window), maxRound: BigInt(spec.maxRound), idle: BigInt(spec.idle), payoutBps: spec.payoutBps,
273
+ lastBps: spec.lastBps, devBps: spec.devBps, entries: spec.entries, minBuy, minPot, maxPayout,
274
+ },
275
+ seed, notes,
276
+ }
277
+ }
278
+
279
+ /** Two Configs (as typed here, or as config() returns it) are the same. */
280
+ export function sameConfig(a, b) {
281
+ return ['window', 'maxRound', 'idle', 'minBuy', 'minPot', 'maxPayout'].every((k) => BigInt(a[k]) === BigInt(b[k]))
282
+ && ['payoutBps', 'lastBps', 'devBps', 'entries'].every((k) => Number(a[k]) === Number(b[k]))
283
+ }
284
+
285
+ // ---- the contract's math (pure: unit-tested to the wei)
286
+
287
+ /** _payoutOf: what a freeze of a pool `p` reserves for its round. */
288
+ export const payoutOf = (p, cfg) => {
289
+ const x = (BigInt(p) * BigInt(cfg.payoutBps)) / BigInt(BPS)
290
+ return x > BigInt(cfg.maxPayout) ? BigInt(cfg.maxPayout) : x
291
+ }
292
+
293
+ /** _credit: `payout` over `k` entries (the newest `last`), capped or not → { each, last, dust }. */
294
+ export function sharesOf(payout, k, cfg, capped = false) {
295
+ payout = BigInt(payout)
296
+ if (k === 0 || payout === 0n) return { each: 0n, last: 0n, dust: payout }
297
+ const extra = k === 1 || capped ? 0n : (payout * BigInt(cfg.lastBps)) / BigInt(BPS)
298
+ const each = (payout - extra) / BigInt(k)
299
+ return { each, last: each + extra, dust: payout - each * BigInt(k) - extra }
300
+ }
301
+
302
+ /**
303
+ * How much of the pool's volume reaches the reward pool, in % of volume: (tax − platform tax) × (1 − dividend) ×
304
+ * (1 − dev %). Buys pay the buy tax, sells the sell tax: `{ buys, sells }` when they differ.
305
+ */
306
+ export function poolShare({ buyTaxPct, sellTaxPct, platformTaxPct = 0.5, dividendPct = 0, devBps = 0 }) {
307
+ const at = (tax) => Math.max(0, Math.round((tax - platformTaxPct) * (1 - dividendPct / 100) * (1 - devBps / BPS) * 1e4) / 1e4)
308
+ const [a, b] = [at(buyTaxPct), at(sellTaxPct)]
309
+ return {
310
+ pctOfVolume: a === b ? a : { buys: a, sells: b },
311
+ how: `(tax − ${platformTaxPct}% platform) × (1 − ${dividendPct}% dividend)${devBps ? ` × (1 − ${devBps / 100}% kept by the dev)` : ''}, of pool volume after graduation, as the held tax is sold. While no holder has 10,000+ tokens the holders' part falls back to the recipient, so a little more arrives`,
312
+ }
313
+ }
314
+
315
+ /** The call reached a contract (or a wallet) and got a revert or no data back: its answer, not the node's failure. */
316
+ const reverted = (e) => !e?.walk?.((x) => x?.code === -32603)
317
+ && !!e?.walk?.((x) => ['ContractFunctionRevertedError', 'ContractFunctionZeroDataError', 'ExecutionRevertedError'].includes(x?.name) || x?.code === 3)
318
+
319
+ const fmt = (x, decimals) => formatUnits(BigInt(x), decimals)
320
+
321
+ /**
322
+ * What a launch preview says about the countdown reward (pure). `cfg`: the Config; amounts in the quote's units.
323
+ * The economics the spec asks the dev to see: what share of pool volume reaches the pool, what a round can pay at most,
324
+ * and what taking every slot costs.
325
+ */
326
+ export function countdownCreateView({ cfg, seed = 0n, decimals, symbol, buyTaxPct, sellTaxPct, platformTaxPct, dividendPct, defaults = [] }) {
327
+ const f = (x) => `${fmt(x, decimals)} ${symbol}`
328
+ const n = Number(cfg.entries)
329
+ const fill = BigInt(n) * BigInt(cfg.minBuy)
330
+ const fillTax = (fill * BigInt(Math.round(buyTaxPct * 100))) / BigInt(BPS)
331
+ const share = poolShare({ buyTaxPct, sellTaxPct, platformTaxPct, dividendPct, devBps: Number(cfg.devBps) })
332
+ const last = Number(cfg.lastBps) / 100
333
+ return {
334
+ what: WHAT_IT_IS,
335
+ rules: {
336
+ window: human(Number(cfg.window)), maxRound: human(Number(cfg.maxRound)), idle: human(Number(cfg.idle)),
337
+ payoutPct: Number(cfg.payoutBps) / 100, lastPct: last, devPct: Number(cfg.devBps) / 100, entries: n,
338
+ minBuy: f(cfg.minBuy), minPot: f(cfg.minPot), maxPayout: f(cfg.maxPayout),
339
+ },
340
+ how: `after graduation, each buy of at least ${f(cfg.minBuy)} through the module puts the countdown ${human(Number(cfg.window))} ahead, but a round never runs past ${human(Number(cfg.maxRound))} from its first counted buy. When the countdown runs out, the round's last ${n} counted buys share ${Number(cfg.payoutBps) / 100}% of the pool (never more than ${f(cfg.maxPayout)}): an equal share each${last > 0 ? `, and the very last buy ${last}% of the round's payout on top` : ''}. The rest of the pool carries over. No round starts while the pool is under ${f(cfg.minPot)}. With no counted buy for ${human(Number(cfg.idle))}, anyone may pay the last round's slots once more (finalize), again at most ${f(cfg.maxPayout)}`,
341
+ poolGets: share,
342
+ fromYourTax: Number(cfg.devBps) > 0 ? `of the tax that reaches the module you keep ${Number(cfg.devBps) / 100}% (claim with gang countdown claim-dev); the rest is the buyers' pool` : 'all of the tax that reaches the module goes to the buyers\' pool: you keep none of it',
343
+ roundPaysAtMost: f(cfg.maxPayout),
344
+ takingAllSlots: {
345
+ buys: `${n} counted buys of ${f(cfg.minBuy)} = ${f(fill)} spent on the token (the buyer keeps the tokens)`,
346
+ buyTax: `about ${f(fillTax)} in buy tax at ${buyTaxPct}%, plus price impact and the risk of holding the tokens; part of that tax comes back into the pool`,
347
+ versusPayout: `so one buyer (or several wallets of one) filling every slot could take up to ${f(cfg.maxPayout)} in one round for roughly that cost. A higher --cd-min-buy, more --cd-entries or a lower --cd-max-payout makes that dearer`,
348
+ },
349
+ ...(seed > 0n && { seed: `${f(seed)} from your wallet into the pool after the bind (approve, then fund): all of it is the buyers' pool, none of it ever comes back to you` }),
350
+ honest: [MULTI_WALLET_NOTE, CAPPED_NOTE, ONLY_GANG_BUYS, POOL_GROWS_NOTE, SELL_NOTE],
351
+ ...(defaults.length && { defaults }),
352
+ permanent: PERMANENT_NOTE,
353
+ }
354
+ }
355
+
356
+ const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
357
+
358
+ /**
359
+ * What a buy of `quoteIn` would mean, if no other counted buy came after it before the deadline (pure). `s`: the raw
360
+ * state (countdownRaw): cfg, deadline, roundEndsBy, potAvailable, cur round's count, now. → { k, payout, mine, capped,
361
+ * startsRound, freezesPrevious } or null when the buy would not count.
362
+ */
363
+ export function estimateShare(s, counted) {
364
+ if (!counted) return null
365
+ const cfg = s.cfg, now = BigInt(s.now), dl = BigInt(s.deadline), n = Number(cfg.entries)
366
+ let pool = BigInt(s.potAvailable)
367
+ let running = dl !== 0n && now <= dl
368
+ const freezesPrevious = dl !== 0n && now > dl
369
+ if (freezesPrevious) pool -= payoutOf(pool, cfg)
370
+ const count = running ? Number(s.count) : 0
371
+ const k = Math.min(count + 1, n)
372
+ // the deadline this buy sets, and whether it lands on the round's cap
373
+ const endsBy = running ? BigInt(s.roundEndsBy) : now + BigInt(cfg.maxRound)
374
+ const capped = now + BigInt(cfg.window) >= endsBy
375
+ const payout = payoutOf(pool, cfg)
376
+ const sh = sharesOf(payout, k, cfg, capped)
377
+ return { k, payout, mine: sh.last, each: sh.each, capped, startsRound: !running, freezesPrevious }
378
+ }
379
+
380
+ /**
381
+ * The raw state of a module for printing (reads it all). null when `addr` does not answer countdown-v1. `factory`: the
382
+ * countdown factory of the pad's generation (the provenance check). `me`: a wallet to report its claimable and slots.
383
+ */
384
+ export async function countdownRaw(read, addr, { factory, admin, token = null, me = null, getBlock } = {}) {
385
+ if (!addr || addr === zeroAddress) return null
386
+ let type
387
+ try { type = await read(addr, COUNTDOWN_ABI, 'moduleType') } catch (e) {
388
+ // no such function (a wallet, another contract) is "not one"; a node's failure is not an answer
389
+ if (reverted(e)) return null
390
+ throw e
391
+ }
392
+ if (hexToString(type, { size: 32 }).replace(/\0+$/, '') !== COUNTDOWN_TYPE) return null
393
+ // provenance first: a module of another factory (the superseded one) or any contract that answers countdown-v1 is
394
+ // read no further, so an older or bad ABI can't look like an RPC failure. Only the warning is shown for it
395
+ const [verified, rewardToken] = await Promise.all([
396
+ countdownVerified(read, addr, factory, admin),
397
+ read(addr, COUNTDOWN_ABI, 'rewardToken').catch(() => null),
398
+ ])
399
+ if (verified !== true) return { module: addr, verified, rewardToken, partial: true }
400
+ if (token && String(rewardToken).toLowerCase() !== token.toLowerCase()) return { module: addr, verified, rewardToken, partial: true }
401
+ const FIELDS = ['config', 'dev', 'rewardToken', 'rewardQuote', 'token', 'pot', 'potAvailable', 'reservedTotal', 'claimTotal', 'devOwed', 'cur', 'deadline', 'lastRoundId', 'lastCountedAt', 'lastFinalizedAt', 'currentRound', 'roundEndsBy', 'previewWork']
402
+ const [vals, rounds, block, claimable] = await Promise.all([
403
+ Promise.all(FIELDS.map((f) => read(addr, COUNTDOWN_ABI, f))),
404
+ Promise.all([0, 1].map((b) => read(addr, COUNTDOWN_ABI, 'round', [b]))),
405
+ getBlock ? getBlock() : null,
406
+ me ? read(addr, COUNTDOWN_ABI, 'claimableOf', [me]) : 0n,
407
+ ])
408
+ const r = Object.fromEntries(FIELDS.map((f, i) => [f, vals[i]]))
409
+ const cur = Number(r.cur)
410
+ const buf = (b) => {
411
+ const [id, count, frozen, settled, reserved, list] = rounds[b]
412
+ return { id: Number(id), count: Number(count), frozen, settled, reserved, list: list.map((e) => ({ buyer: e.buyer, tokens: e.tokens })) }
413
+ }
414
+ return {
415
+ module: addr, verified, cfg: r.config, dev: r.dev, rewardToken: r.rewardToken, rewardQuote: r.rewardQuote,
416
+ token: r.token === zeroAddress ? null : r.token, pot: r.pot, potAvailable: r.potAvailable, reservedTotal: r.reservedTotal,
417
+ claimTotal: r.claimTotal, devOwed: r.devOwed, cur, deadline: r.deadline, lastRoundId: Number(r.lastRoundId),
418
+ lastCountedAt: r.lastCountedAt, lastFinalizedAt: r.lastFinalizedAt, currentRound: Number(r.currentRound), roundEndsBy: r.roundEndsBy,
419
+ due: r.previewWork[0], rounds: [buf(0), buf(1)], count: buf(cur).count,
420
+ now: block ? block.timestamp : BigInt(Math.floor(Date.now() / 1000)), me, claimable,
421
+ }
422
+ }
423
+
424
+ const ADMIN_ABI = parseAbi(['function moduleOf(address module) view returns (address)'])
425
+ /**
426
+ * Whether `module` was made by `factory`: the factory's admin() is the network's pinned GangHandlerAdmin (`admin`, from
427
+ * gangpad.js; never from the env) and that admin's moduleOf(module) is the factory. null when it could not be read.
428
+ */
429
+ export async function countdownVerified(read, module, factory, admin) {
430
+ if (!factory || !admin) return false
431
+ try {
432
+ const a = await read(factory, COUNTDOWN_FACTORY_ABI, 'admin')
433
+ if (a.toLowerCase() !== admin.toLowerCase()) return false
434
+ return (await read(a, ADMIN_ABI, 'moduleOf', [module])).toLowerCase() === factory.toLowerCase()
435
+ } catch { return null }
436
+ }
437
+
438
+ /** Whether a settle / finalize is due now, from the raw state (as the contract's _due). */
439
+ export function dueOf(s) {
440
+ const now = BigInt(s.now), dl = BigInt(s.deadline)
441
+ const settle = (dl !== 0n && now > dl) || s.rounds.some((b) => b.frozen && !b.settled)
442
+ if (settle) return { settle: true, finalize: false }
443
+ const last = BigInt(s.lastCountedAt)
444
+ if (last === 0n || dl !== 0n) return { settle: false, finalize: false, finalizeFrom: null }
445
+ const since = BigInt(s.lastFinalizedAt) > last ? BigInt(s.lastFinalizedAt) : last
446
+ const from = since + BigInt(s.cfg.idle)
447
+ const p = BigInt(s.potAvailable)
448
+ return { settle: false, finalize: now >= from && p >= BigInt(s.cfg.minPot) && payoutOf(p, s.cfg) !== 0n, finalizeFrom: from }
449
+ }
450
+
451
+ /** The module's state for printing (pure). `q`: { symbol, decimals }; `ref`: how later commands name it. */
452
+ export function formatCountdown(s, q, ref) {
453
+ const d = q.decimals ?? 18
454
+ const f = (x) => fmt(x, d)
455
+ const sym = q.symbol ?? 'of the quote'
456
+ const now = BigInt(s.now), dl = BigInt(s.deadline)
457
+ const running = dl !== 0n && now <= dl
458
+ const due = dueOf(s)
459
+ const me = s.me ? String(s.me).toLowerCase() : null
460
+ const roundOf = (b) => {
461
+ const r = s.rounds[b]
462
+ if (!r.id) return null
463
+ const n = Number(s.cfg.entries)
464
+ return {
465
+ id: r.id, countedBuys: r.count, slots: Math.min(r.count, n),
466
+ state: r.settled ? 'paid' : r.frozen ? 'ended: its payout is set aside, waiting to be credited (settle)' : b === s.cur && running ? 'running' : b === s.cur && dl !== 0n ? 'ended: waiting for the freeze (settle, or the next counted buy)' : 'ended',
467
+ ...(r.frozen && !r.settled && { reserved: f(r.reserved) }),
468
+ // oldest first: the last one is the newest counted buy
469
+ slotsOldestFirst: r.list.map((e) => ({ buyer: e.buyer, tokens: formatUnits(e.tokens, 18), ...(me && e.buyer.toLowerCase() === me && { you: true }) })),
470
+ }
471
+ }
472
+ const curRound = roundOf(s.cur)
473
+ const prev = roundOf(1 - s.cur)
474
+ const payoutNow = payoutOf(s.potAvailable, s.cfg)
475
+ const state = s.verified === null ? 'unchecked' : s.verified !== true ? 'unverified' : !s.token ? 'unbound' : running ? 'running' : dl !== 0n ? 'ended' : s.lastRoundId ? 'waiting' : 'not started'
476
+ const next = []
477
+ const tn = ref
478
+ if (s.verified === true && s.token) {
479
+ if (due.settle) next.push(`gang countdown settle ${tn} (anyone: the round passed its deadline)`)
480
+ if (due.finalize) next.push(`gang countdown finalize ${tn} (anyone: idle long enough, pays the last round's slots again)`)
481
+ if (s.me && BigInt(s.claimable) > 0n) next.push(`gang countdown claim ${tn}`)
482
+ if (s.me && String(s.dev).toLowerCase() === me && BigInt(s.devOwed) > 0n) next.push(`gang countdown claim-dev ${tn}`)
483
+ }
484
+ return {
485
+ module: s.module, moduleType: COUNTDOWN_TYPE, verified: s.verified, state, dev: s.dev, rewardToken: s.rewardToken, token: s.token,
486
+ quote: s.rewardQuote, quoteSymbol: q.symbol ?? null, quoteDecimals: d,
487
+ rules: {
488
+ window: human(Number(s.cfg.window)), maxRound: human(Number(s.cfg.maxRound)), idle: human(Number(s.cfg.idle)),
489
+ payoutPct: Number(s.cfg.payoutBps) / 100, lastPct: Number(s.cfg.lastBps) / 100, devPct: Number(s.cfg.devBps) / 100,
490
+ entries: Number(s.cfg.entries), minBuy: f(s.cfg.minBuy), minPot: f(s.cfg.minPot), maxPayout: f(s.cfg.maxPayout),
491
+ },
492
+ pool: f(s.potAvailable), poolBooked: f(s.pot), reserved: f(s.reservedTotal), creditedUnclaimed: f(s.claimTotal), devOwed: f(s.devOwed),
493
+ nextRoundPays: `${f(payoutNow)} ${sym} if a round ended now (${Number(s.cfg.payoutBps) / 100}% of the pool, at most ${f(s.cfg.maxPayout)})`,
494
+ round: {
495
+ current: s.currentRound || null,
496
+ deadline: iso(s.deadline), ...(running && { secondsLeft: Number(dl - now) }),
497
+ endsBy: running ? iso(s.roundEndsBy) : null,
498
+ ...(dl !== 0n && !running && { ended: 'the deadline passed: the round is paid on the next settle (anyone) or the next counted buy' }),
499
+ ...(curRound && { latest: curRound }), ...(prev && { previous: prev }),
500
+ },
501
+ lastCountedAt: iso(s.lastCountedAt),
502
+ due: { settle: due.settle, finalize: due.finalize, ...(due.finalizeFrom && !due.finalize && { finalizeFrom: iso(due.finalizeFrom) }) },
503
+ ...(s.me && { wallet: s.me, claimable: f(s.claimable) }),
504
+ ...(next.length && { next }),
505
+ what: WHAT_IT_IS,
506
+ notes: [ONLY_GANG_BUYS, MULTI_WALLET_NOTE, CAPPED_NOTE, SELL_NOTE, POOL_GROWS_NOTE],
507
+ }
508
+ }
509
+
510
+ /** The status of a module that may not be shown (unchecked, unverified, or cloned for another token): the warning only. */
511
+ export function countdownShown(s, token) {
512
+ const warning = s.verified === null ? UNCHECKED_NOTE : s.verified !== true ? UNVERIFIED_NOTE
513
+ : token && String(s.rewardToken).toLowerCase() !== token.toLowerCase()
514
+ ? `this token pays its tax to a countdown reward module cloned for another token (${s.rewardToken}): this token has NO countdown reward, and its tax feeds that other token's pool` : null
515
+ return warning ? { module: s.module, claims: COUNTDOWN_TYPE, verified: s.verified, isThisTokensCountdown: false, warning } : null
516
+ }
517
+
518
+ /**
519
+ * The countdown reward of a V3 `token` whose tax recipient is `recipient`, on ctx (already on the token's generation).
520
+ * → null (none: no factory here, or the recipient is no countdown module) | { unread } | { warning } (claims to be one,
521
+ * or is one for another token: never bought through) | { live: true, raw } (made by the factory, cloned for this token).
522
+ */
523
+ export async function countdownForToken(ctx, token, recipient, me = null) {
524
+ const factory = ctx.countdownFactory || null
525
+ if (!factory || !recipient || recipient === zeroAddress) return null
526
+ let raw
527
+ try { raw = await countdownRaw(ctx.read, recipient, { factory, admin: ctx.handlerAdmin, token, me, getBlock: () => ctx.client.getBlock() }) } catch (e) {
528
+ return { unread: e.shortMessage || e.message.split('\n')[0] }
529
+ }
530
+ if (!raw) return null
531
+ if (raw.verified === null) return { unread: UNCHECKED_NOTE }
532
+ const shown = countdownShown(raw, token)
533
+ if (shown) return { warning: shown.warning, module: raw.module }
534
+ return { live: true, raw }
535
+ }
536
+
537
+ /** rewards.countdown of a pool buy through the module (pure). `counted`: wouldCount(quoteIn). */
538
+ export function countdownBuyLine(s, quoteIn, counted, q, { mustCount = true } = {}) {
539
+ const d = q.decimals ?? 18
540
+ const f = (x) => `${fmt(x, d)} ${q.symbol ?? 'of the quote'}`
541
+ const now = BigInt(s.now), dl = BigInt(s.deadline)
542
+ const running = dl !== 0n && now <= dl
543
+ const belowMin = BigInt(quoteIn) < BigInt(s.cfg.minBuy)
544
+ const why = counted
545
+ ? `it spends at least the ${f(s.cfg.minBuy)} minimum${running ? ' and a round is running' : ` and the pool (${f(s.potAvailable)}) can start a round`}`
546
+ : belowMin ? `it spends less than the ${f(s.cfg.minBuy)} minimum`
547
+ : `no round is running and the pool would be under its ${f(s.cfg.minPot)} minimum${dl !== 0n ? ' once the ended round takes its payout' : ''}: no round starts until the tax brings it back`
548
+ const est = estimateShare(s, counted)
549
+ return {
550
+ counts: counted, why, mustCount,
551
+ ...(!counted && { ifNotCounted: mustCount ? 'with the default mustCount the buy reverts (NotCounted): nothing is bought' : '--cd-uncounted: the buy goes through as a plain buy, not counted' }),
552
+ pool: f(s.potAvailable), minBuy: f(s.cfg.minBuy), slots: Number(s.cfg.entries),
553
+ round: {
554
+ current: running ? s.currentRound : null,
555
+ deadline: iso(s.deadline), ...(running && { secondsLeft: Number(dl - now), endsBy: iso(s.roundEndsBy), countedSoFar: s.count }),
556
+ ...(dl !== 0n && !running && { ended: 'its deadline passed: this buy first ends it (its slots are paid as they stand), then starts the next round' }),
557
+ },
558
+ ...(est && {
559
+ estimate: {
560
+ yourShareIfLast: f(est.mine), roundPays: f(est.payout), slotsFilled: est.k,
561
+ ...(est.startsRound && { startsRound: true }),
562
+ ...(est.capped && { atCap: 'the countdown this buy sets reaches the round\'s cap: the round ends at a public time and its slots are paid equally (no extra for the last buy)' }),
563
+ note: `if no other counted buy came before the deadline (as the pool stands now). Every later counted buy puts the deadline ${human(Number(s.cfg.window))} ahead and, once ${Number(s.cfg.entries)} more come, pushes this buy out of the round's slots; the pool also grows as tax is sold`,
564
+ },
565
+ }),
566
+ note: `${WHAT_IT_IS}. ${MULTI_WALLET_NOTE}. ${ONLY_GANG_BUYS}`,
567
+ }
568
+ }
569
+
570
+ /** rewards.countdown of a pool sell (pure): sells don't touch slots. */
571
+ export const countdownSellLine = (s, q) => ({
572
+ pool: `${fmt(s.potAvailable, q.decimals ?? 18)} ${q.symbol ?? 'of the quote'}`,
573
+ note: `${SELL_NOTE}. Pool sells sell some of the held tax first: that is how the countdown pool grows`,
574
+ })
575
+
576
+ /**
577
+ * A pool buy of `amount` (decimal string) through the module, for a graduated token whose recipient is its own
578
+ * countdown module (`cd.raw`). Returns what the command prints. `c`: curveOf(…). `payBnb`: pay native BNB (WBNB-quoted
579
+ * only). `mustCount`: revert unless counted.
580
+ */
581
+ export async function countdownBuy(ctx, { token, c, cd, me, amount, slippage, payBnb, mustCount, rawOnly, summarize, base = {} }) {
582
+ const s = cd.raw
583
+ const quote = s.rewardQuote
584
+ const wbnbQuoted = quote.toLowerCase() === String(ctx.wbnb).toLowerCase()
585
+ const failOut = (o) => ({ success: false, ...base, step: 'pool-buy', via: 'countdown', module: s.module, ...o })
586
+ if (payBnb && !wbnbQuoted) return failOut({ error: '--pay-bnb: the countdown reward module takes the token\'s own quote only (it buys on the token\'s own pair)', hint: `drop --pay-bnb and pay in ${c.quoteSymbol ?? quote}` })
587
+ const useBnb = wbnbQuoted && payBnb
588
+ const decimals = await decimalsOf(ctx, quote)
589
+ const q = { symbol: c.quoteSymbol, decimals }
590
+ const quoteIn = parseUnits(amount, useBnb ? 18 : decimals)
591
+ if (quoteIn === 0n) return failOut({ error: `--amount ${amount} rounds to 0` })
592
+ const counted = await ctx.read(s.module, COUNTDOWN_ABI, 'wouldCount', [quoteIn])
593
+ const line = countdownBuyLine(s, quoteIn, counted, q, { mustCount })
594
+ if (mustCount && !counted) {
595
+ return failOut({
596
+ error: `this buy would not count for the countdown reward: ${line.why}`, rewards: { countdown: line },
597
+ hint: BigInt(quoteIn) < BigInt(s.cfg.minBuy) ? `buy at least ${line.minBuy} (--amount), or add --cd-uncounted to buy through the module without counting` : 'add --cd-uncounted to buy through the module without counting, or wait for the pool to grow',
598
+ })
599
+ }
600
+ // the pool's own price for the estimate (the module swaps on the pair at Pancake V2's 0.25% fee), less the buy tax
601
+ const [[r0, r1], t0] = await Promise.all([ctx.read(c.pair, PAIR_ABI, 'getReserves'), ctx.read(c.pair, PAIR_ABI, 'token0')])
602
+ const [rT, rQ] = t0.toLowerCase() === token.toLowerCase() ? [r0, r1] : [r1, r0]
603
+ const inFee = quoteIn * 9_975n
604
+ const gross = rQ > 0n ? (inFee * rT) / (rQ * 10_000n + inFee) : 0n
605
+ const buyTaxBps = BigInt(Math.round(c.buyTaxPct * 100))
606
+ const estimate = gross - (gross * buyTaxBps) / 10_000n
607
+ const deadline = routerDeadline()
608
+ const minOf = (x) => (x * BigInt(Math.round((100 - slippage) * 100))) / 10_000n
609
+ const fields = {
610
+ step: 'pool-buy', venue: 'pancakeswap', via: 'countdown', module: s.module, function: useBnb ? 'buy' : 'buyWithQuote',
611
+ spend: amount, payWith: useBnb ? 'BNB' : c.quoteSymbol, quote: c.quoteSymbol, pair: c.pair, buyTaxPct: c.buyTaxPct,
612
+ slippagePct: slippage, deadline: Number(deadline), mustCount,
613
+ ...base, rewards: { countdown: line },
614
+ }
615
+ if (useBnb) {
616
+ const native = await ctx.client.getBalance({ address: me })
617
+ if (native < quoteIn + GAS_RESERVE) {
618
+ return failOut({ error: 'not enough BNB for this buy (native BNB must also cover gas)', haveBnb: formatUnits(native, 18), needBnb: amount, reserveForGas: formatUnits(GAS_RESERVE, 18), hint: 'add --use-quote to pay from WBNB instead' })
619
+ }
620
+ } else {
621
+ const pre = await fundingStep(ctx, { me, token: quote, need: quoteIn, spender: s.module, sym: c.quoteSymbol, approveStep: 'approve-quote' }, rawOnly, summarize)
622
+ if (pre) {
623
+ return pre.success === false ? failOut(pre) : {
624
+ ...pre, chainId: Number(ctx.chainId), token, module: s.module, next: 'pool-buy',
625
+ then: { via: 'countdown', function: 'buyWithQuote', spend: amount, expectTokens: formatUnits(estimate, 18), mustCount },
626
+ rewards: { countdown: line }, note: `${pre.note ? `${pre.note}. ` : ''}the countdown module pulls the quote straight to the pair (it never holds it): approve it for this buy's amount, then run the same command again`,
627
+ }
628
+ }
629
+ }
630
+ const fn = useBnb ? 'buy' : 'buyWithQuote'
631
+ const args = useBnb ? [0n, deadline, mustCount] : [quoteIn, 0n, deadline, mustCount]
632
+ const sim = await simulateCountdown(ctx.client, me, s.module, COUNTDOWN_ABI, fn, args, useBnb ? quoteIn : 0n)
633
+ if (sim.failed) return failOut({ ...fields, ...sim.failed })
634
+ const tokensOut = sim.result
635
+ const minOut = minOf(tokensOut)
636
+ const data = encodeFunctionData({ abi: COUNTDOWN_ABI, functionName: fn, args: useBnb ? [minOut, deadline, mustCount] : [quoteIn, minOut, deadline, mustCount] })
637
+ return step(ctx, { from: me, to: s.module, data, value: useBnb ? quoteIn : 0n }, {
638
+ chainId: Number(ctx.chainId), token, ...fields,
639
+ expectTokens: formatUnits(tokensOut, 18), minTokensOut: formatUnits(minOut, 18), quotedWith: 'simulation',
640
+ note: `bought through the token's countdown reward module on its own PancakeSwap pair (${useBnb ? 'BNB, wrapped in the same call' : 'the quote goes straight from this wallet to the pair'}); the tokens go to ${me}, after the ${c.buyTaxPct}% buy tax. minTokensOut = the simulated amount less --slippage. ${mustCount ? 'mustCount: if the buy would not count when it lands, it reverts and nothing is bought (--cd-uncounted to buy anyway)' : '--cd-uncounted: the buy goes through even if it is not counted'}. Let the wallet estimate gas (a buy that ends a round pays it out in place: up to about 350k gas)`,
641
+ }, rawOnly, summarize)
642
+ }
643
+
644
+ // ---- gang countdown <sub>
645
+
646
+ function cdCtx(testnet) {
647
+ const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
648
+ if (!net.pad) throw new Error(NOT_ON_MAINNET)
649
+ const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
650
+ return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
651
+ }
652
+
653
+ const SUBS = ['status', 'claim', 'settle', 'finalize', 'claim-dev']
654
+ const USAGE = 'usage: gang countdown <status|claim|settle|finalize|claim-dev> --token <addr> [--to <addr>] [--from <addr>] [--testnet] [--calldata] — see gang help'
655
+
656
+ /** `gang countdown <sub>`: the countdown reward module of a V3 token (its tax recipient), found from --token. */
657
+ export async function runCountdown(sub, { opt, flag, out, fail, summarize }) {
658
+ if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
659
+ const testnet = flag('testnet')
660
+ let ctx
661
+ try { ctx = cdCtx(testnet) } catch (e) { return fail(e.message) }
662
+ const chainId = Number(ctx.chainId)
663
+ const tn = testnet ? ' --testnet' : ''
664
+ // no generation of this network has a countdown factory (mainnet now): said before any read
665
+ if (!gangGens(testnet).some((g) => g.countdownFactory)) return fail(countdownNotLive(testnet))
666
+ const token = opt('token')
667
+ if (!isAddress(token ?? '')) return fail('--token must be a V3 token address (0x…)', { got: token ?? null })
668
+ const kind = await atTokenPad(ctx, token)
669
+ if (kind === null) return fail(KIND_UNREAD.error, { token, retry: KIND_UNREAD.retry })
670
+ if (kind !== 'v3') return fail(`not a V3 curve token on a GangLaunchpad (${testnet ? 'BSC testnet' : 'BSC mainnet; add --testnet for a testnet token'})`, { token, chainId, ...(kind && kind !== 'none' && { kind }) })
671
+ if (!ctx.countdownFactory) return fail(countdownNotLive(testnet), { token, padGen: ctx.gen ?? null })
672
+ if (flag('to') && sub !== 'claim') return fail('--to applies to gang countdown claim only (where your reward is paid)')
673
+ let curve, recipient
674
+ try {
675
+ [curve, [, , , recipient]] = await Promise.all([ctx.read(ctx.pad, PAD_ABI, 'curves', [token]), ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token])])
676
+ } catch (e) {
677
+ return fail('could not read the token\'s curve and tax recipient (RPC error)', { token, detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' })
678
+ }
679
+ let me = null
680
+ try { me = walletFor(ctx, opt('from')) } catch { /* status works without a wallet */ }
681
+ let raw
682
+ try { raw = await countdownRaw(ctx.read, recipient, { factory: ctx.countdownFactory, admin: ctx.handlerAdmin, token, me, getBlock: () => ctx.client.getBlock() }) } catch (e) {
683
+ return fail('could not read the countdown reward module (RPC error)', { token, module: recipient, detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' })
684
+ }
685
+ if (!raw) return fail('this token\'s tax recipient is not a countdown reward module (countdown-v1): the token was not launched with --countdown-reward', { token, recipient: recipient === zeroAddress ? null : recipient })
686
+ if (raw.verified === null) return fail(UNCHECKED_NOTE, { token, module: raw.module, retry: 'same command again' })
687
+ const shown = countdownShown(raw, token)
688
+ if (shown) return sub === 'status' ? out({ success: true, chainId, token, ...shown }) : fail(shown.warning, { token, module: raw.module })
689
+ const [symbol, decimals] = await Promise.all([
690
+ ctx.read(raw.rewardQuote, ERC20_ABI, 'symbol').catch(() => null), ctx.read(raw.rewardQuote, ERC20_ABI, 'decimals').then(Number).catch(() => 18),
691
+ ])
692
+ const q = { symbol, decimals }
693
+ const ref = `--token ${token}${tn}`
694
+ const view = formatCountdown(raw, q, ref)
695
+ if (sub === 'status') return out({ success: true, chainId, token, graduated: curve[6], ...(!curve[6] && { beforeGraduation: 'the token has not graduated: the countdown starts with the first counted buy through the module in its PancakeSwap pool' }), ...view })
696
+
697
+ if (!me) return fail('no wallet: sign in to baw, or pass --from <addr> with --calldata')
698
+ if (!raw.token) return fail(HINTS.NotBound, { token, module: raw.module })
699
+ const f = (x) => formatUnits(BigInt(x), decimals)
700
+ const sym = symbol ?? 'of the quote'
701
+ const due = dueOf(raw)
702
+ const send = async (functionName, args, extra) => {
703
+ const sim = await simulateCountdown(ctx.client, me, raw.module, COUNTDOWN_ABI, functionName, args)
704
+ if (sim.failed) return out({ success: false, step: extra.step, token, module: raw.module, ...sim.failed })
705
+ const data = encodeFunctionData({ abi: COUNTDOWN_ABI, functionName, args })
706
+ return out(step(ctx, { from: me, to: raw.module, data }, { chainId, token, module: raw.module, ...extra }, flag('calldata'), summarize))
707
+ }
708
+
709
+ if (sub === 'claim') {
710
+ if (BigInt(raw.claimable) === 0n) {
711
+ return fail('nothing to claim for this wallet: no round it had slots in has been paid to it', {
712
+ token, wallet: me, ...(due.settle && { hint: `a round passed its deadline and is not credited yet: gang countdown settle ${ref} first (anyone), then claim` }),
713
+ })
714
+ }
715
+ let to = me
716
+ if (flag('to')) {
717
+ to = opt('to')
718
+ if (!isAddress(to ?? '') || to === zeroAddress) return fail('--to must be a 0x address (checksummed or all lowercase): where the reward is paid (left out: this wallet)', { got: to ?? null })
719
+ to = getAddress(to)
720
+ }
721
+ return send('claim', [to], {
722
+ step: 'countdown-claim', amount: f(raw.claimable), quote: sym, to,
723
+ note: `pays everything credited to this wallet (${f(raw.claimable)} ${sym}) to ${to.toLowerCase() === String(me).toLowerCase() ? 'this wallet' : to}`,
724
+ })
725
+ }
726
+ // the local reading of what is due must agree with the module's own previewWork, or nothing is built
727
+ if ((sub === 'settle' || sub === 'finalize') && (due.settle || due.finalize) !== !!raw.due) {
728
+ return fail(`the module's previewWork says ${raw.due ? 'something is due' : 'nothing is due'}, but this CLI reads the round as ${due.settle ? 'due to settle' : due.finalize ? 'due to finalize' : 'not due'}: nothing is built. Run the command again (a block may have landed in between); if it persists, report it`, { token, module: raw.module, previewWork: !!raw.due, local: due, retry: 'same command again' })
729
+ }
730
+ if (sub === 'settle') {
731
+ if (!due.settle) {
732
+ const dl = BigInt(raw.deadline)
733
+ return fail(dl !== 0n ? `nothing to settle yet: the round runs until ${iso(raw.deadline)} (each counted buy can put it later, up to ${iso(raw.roundEndsBy)})` : 'nothing to settle: no round has passed its deadline unpaid', { token, ...(due.finalize && { hint: `a finalize is due: gang countdown finalize ${ref}` }) })
734
+ }
735
+ return send('settle', [], {
736
+ step: 'countdown-settle', pool: f(raw.potAvailable), quote: sym,
737
+ note: 'anyone may: books the tax that arrived, ends the round whose deadline passed (its payout is fixed now) and credits every ended round\'s slots; the buyers then claim with gang countdown claim',
738
+ })
739
+ }
740
+ if (sub === 'finalize') {
741
+ if (due.settle) return fail(`a round is still to be settled first: gang countdown settle ${ref}`, { token })
742
+ if (!due.finalize) {
743
+ return fail(raw.lastCountedAt === 0n ? 'nothing to finalize: no buy has been counted yet'
744
+ : BigInt(raw.deadline) !== 0n ? `nothing to finalize: a round is running (until ${iso(raw.deadline)}); finalize is for a countdown with no counted buy for ${human(Number(raw.cfg.idle))}`
745
+ : BigInt(raw.potAvailable) < BigInt(raw.cfg.minPot) ? `nothing to finalize: the pool (${f(raw.potAvailable)} ${sym}) is under its ${f(raw.cfg.minPot)} minimum` : `not due yet: finalize opens ${iso(due.finalizeFrom)} (no counted buy for ${human(Number(raw.cfg.idle))})`, { token, hint: HINTS.NotDue })
746
+ }
747
+ const payout = payoutOf(raw.potAvailable, raw.cfg)
748
+ return send('finalize', [], {
749
+ step: 'countdown-finalize', pays: f(payout), quote: sym,
750
+ note: `anyone may: after ${human(Number(raw.cfg.idle))} with no counted buy, pays the last round's slots once more (${Number(raw.cfg.payoutBps) / 100}% of the pool, at most ${f(raw.cfg.maxPayout)}); again only after another ${human(Number(raw.cfg.idle))}. A later counted buy starts the countdown again`,
751
+ })
752
+ }
753
+ // claim-dev: the dev's booked part of the tax (devBps), always paid to the dev; anyone may push it
754
+ if (Number(raw.cfg.devBps) === 0) return fail('this module keeps no part of the tax for the dev (dev 0%): all of it is the buyers\' pool', { token })
755
+ const sim = await simulateCountdown(ctx.client, me, raw.module, COUNTDOWN_ABI, 'claimDev', [])
756
+ if (sim.failed) return out({ success: false, step: 'countdown-claim-dev', token, module: raw.module, ...sim.failed, ...(sim.failed.error === 'NothingToClaim' && { hint: 'nothing is owed to the dev yet: its part comes from the tax as it is sold' }) })
757
+ const data = encodeFunctionData({ abi: COUNTDOWN_ABI, functionName: 'claimDev', args: [] })
758
+ return out(step(ctx, { from: me, to: raw.module, data }, {
759
+ chainId, token, module: raw.module, step: 'countdown-claim-dev', amount: f(sim.result), quote: sym, to: raw.dev,
760
+ note: `sends the dev its ${Number(raw.cfg.devBps) / 100}% part of the tax booked so far (always to the dev ${raw.dev}; anyone may push it)`,
761
+ }, flag('calldata'), summarize))
762
+ }