@gangfun/cli 0.37.0 → 0.39.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/floor.js ADDED
@@ -0,0 +1,818 @@
1
+ import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, maxUint256, numberToHex, parseUnits, zeroAddress } from 'viem'
2
+ import { atPad, atTokenPad, GANG_GENS, gangGens, KIND_UNREAD, padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
3
+ import { walletFor } from './fair.js'
4
+ import { fundingStep, parseAmount, parseNum, poolSellQuote, revertOf as revertIn, step } from './steps.js'
5
+ import { parseSplitSpec } from './split.js'
6
+ import { COMBO_GAS_NOTE } from './combo.js'
7
+ import { capUnits, parseCapShare, payeeAmounts, quoteUnits } from './capped.js'
8
+ import { bondGuard } from './bond.js'
9
+ import { callBondGuard } from './callbond.js'
10
+
11
+ /**
12
+ * `gang floor …` and `gang create … --floor [--redeem-fee <pct>] [--tax-cap <amount> [--tax-cap-share <pct>] [--split <addr>:<pct>,…]]`
13
+ * — GangFloorModule (底价赎回, `floor-v1`): one V3 token's tax recipient that keeps the tax as a treasury. Of each payment
14
+ * of the bound quote, `payBps` goes to 0–10 payees at fixed shares until they have been credited `capAmount` in all (the
15
+ * capped recipient's rule); the rest — once the cap is reached, or with no payees, all of it — stays in the module. Any
16
+ * holder may `redeem`: its tokens go to 0xdead and it takes `amount × treasury ÷ floorSupply` of the quote, less
17
+ * `redeemFeeBps` that stays in the treasury. floorSupply = total supply − what 0xdead holds. No buy-back, no liquidity, no
18
+ * swap. A redemption never calls a payee: the payees' part of what arrived is counted against the cap and set aside
19
+ * (`payeesPending`) for the next split.
20
+ * The token is fixed when the module is cloned (`floorToken`, its CREATE2 address before it exists): `bind` only checks
21
+ * it. So a launch computes the token's address first (the final name, symbol, metadata URI, tax rates), clones the
22
+ * module for it, then creates the token with the same salt (launch.js; vanity.js `fixed`).
23
+ * A module is a floor module only when GangFloorModuleFactory listed it (GangHandlerAdmin.moduleOf): a contract that
24
+ * merely answers `floor-v1` is not one, and this CLI builds no redemption against it (docs/SPEC-FLOOR-MODULE-2026-11-11.md §6).
25
+ * Env: GANG_FLOOR_FACTORY / GANG_TESTNET_FLOOR_FACTORY (gangpad.js).
26
+ */
27
+
28
+ export const MAINNET_FLOOR_FACTORY = GANG_GENS.mainnet[0].floorFactory ?? null
29
+ export const TESTNET_FLOOR_FACTORY = GANG_GENS.testnet[0].floorFactory ?? null
30
+ export const FLOOR_TYPE = 'floor-v1'
31
+ const BPS = 10_000
32
+ const MAX_REDEEM_FEE_BPS = 500
33
+ const DEFAULT_REDEEM_FEE_BPS = 200
34
+ const DEAD = '0x000000000000000000000000000000000000dEaD'
35
+
36
+ const ERRORS = [
37
+ 'error ZeroAddress()', 'error NotClone()', 'error NotFactory()', 'error AlreadyInitialized()', 'error BadBps()',
38
+ 'error BadPayees()', 'error BadShares()', 'error BadPayee()', 'error DuplicatePayee()', 'error BadIndex()',
39
+ 'error NotPayee()', 'error AlreadyBound()', 'error NotBound()', 'error WrongToken()', 'error NotCurve()',
40
+ 'error NotCreator()', 'error NotRecipient()', 'error NothingOwed()', 'error NotTradable()', 'error Slippage()',
41
+ 'error PushStarved()', 'error BadCap()', 'error WrongQuote()', 'error BadQuote()', 'error ZeroAmount()', 'error BadTo()',
42
+ 'error NothingToRedeem()', 'error NothingForRecipient()',
43
+ ]
44
+
45
+ export const FLOOR_FACTORY_ABI = parseAbi([
46
+ 'function create(address token, address floorQuote, uint256 capAmount, uint16 payBps, uint16 redeemFeeBps, address[] payees, uint16[] shares, bytes32 salt) returns (address module)',
47
+ 'function predict(address dev, bytes32 salt) view returns (address)',
48
+ 'function pad() view returns (address)',
49
+ 'function admin() view returns (address)',
50
+ 'function vanityEnabled() view returns (bool)',
51
+ 'error NotAgent()', 'error WrongHandler()', 'error NoVanityDeployer()', 'error BadToken()',
52
+ 'event Created(address indexed dev, address indexed module, address indexed token, address floorQuote, uint256 capAmount, uint16 payBps, uint16 redeemFeeBps, address[] payees, uint16[] shares)',
53
+ ...ERRORS,
54
+ ])
55
+
56
+ export const FLOOR_ABI = parseAbi([
57
+ 'function moduleType() view returns (bytes32)',
58
+ 'function pad() view returns (address)',
59
+ 'function dev() view returns (address)',
60
+ 'function floorToken() view returns (address)',
61
+ 'function token() view returns (address)',
62
+ 'function quote() view returns (address)',
63
+ 'function floorQuote() view returns (address)',
64
+ 'function gangQuote() view returns (address)',
65
+ 'function capAmount() view returns (uint256)',
66
+ 'function paidTotal() view returns (uint256)',
67
+ 'function payBps() view returns (uint16)',
68
+ 'function redeemFeeBps() view returns (uint16)',
69
+ 'function capLeft() view returns (uint256)',
70
+ 'function capReached() view returns (bool)',
71
+ 'function payeesOf() view returns (address[] payees, uint16[] shares)',
72
+ 'function treasuryHeld() view returns (uint256)',
73
+ 'function treasury() view returns (uint256)',
74
+ 'function payeesPending() view returns (uint256)',
75
+ 'function floorSupply() view returns (uint256)',
76
+ 'function floorPrice() view returns (uint256)',
77
+ 'function previewRedeem(uint256 amount) view returns (uint256 quoteOut, uint256 fee)',
78
+ 'function owedOf(address asset, uint256 index) view returns (uint256)',
79
+ 'function owedTotal(address asset) view returns (uint256)',
80
+ 'function unsplit() view returns (uint256)',
81
+ 'function undistributed(address asset) view returns (uint256)',
82
+ 'function keeperServes(address q) view returns (bool)',
83
+ 'function previewWork() view returns (bool due, uint256 minOut)',
84
+ 'function lastPaidAt() view returns (uint64)',
85
+ 'function bind(address token)',
86
+ 'function split()',
87
+ 'function distribute(address asset) returns (uint256 incoming)',
88
+ 'function release(address asset, uint256 index, uint256 maxAmount) returns (uint256 amount)',
89
+ 'function setPayee(uint256 index, address newPayee)',
90
+ 'function redeem(uint256 amount, uint256 minQuoteOut, address to) returns (uint256 quoteOut)',
91
+ 'function work(uint256 minOut)',
92
+ 'event Bound(address indexed token, address indexed quote)',
93
+ 'event Split(uint256 incoming, uint256 toTreasury, uint256 toPayees)',
94
+ 'event CapReached(uint256 capAmount)',
95
+ 'event Redeemed(address indexed holder, address indexed to, uint256 tokensIn, uint256 quoteOut, uint256 fee, uint256 treasuryAfter, uint256 supplyAfter)',
96
+ 'event Distributed(address indexed asset, uint256 incoming, uint256 toDead)',
97
+ 'event PayeeOwed(address indexed asset, uint256 indexed index, uint256 amount)',
98
+ 'event PayeeReleased(address indexed asset, uint256 indexed index, uint256 amount)',
99
+ 'event PayeeChanged(uint256 indexed index, address indexed oldPayee, address indexed newPayee)',
100
+ 'event Shortfall(address indexed asset, uint256 amount)',
101
+ ...ERRORS,
102
+ ])
103
+ /** gang tx decodes these (the factory's Created and the module's Split / Redeemed; the rest share capped's topics). */
104
+ export const FLOOR_EVENT_ABIS = [FLOOR_FACTORY_ABI, FLOOR_ABI]
105
+
106
+ const ADMIN_ABI = parseAbi(['function moduleOf(address module) view returns (address)'])
107
+ const PAD_ABI = parseAbi([
108
+ 'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
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 taxHandler() view returns (address)',
111
+ 'function PLATFORM_TAX_BPS() view returns (uint256)',
112
+ ])
113
+ const ERC20_ABI = parseAbi([
114
+ 'function symbol() view returns (string)', 'function decimals() view returns (uint8)',
115
+ 'function balanceOf(address) view returns (uint256)', 'function totalSupply() view returns (uint256)',
116
+ ])
117
+
118
+ const DEAD_GAS_NOTE = 'let the wallet estimate the gas limit and do not lower it: the transfer to 0xdead needs about 365k gas left before it (a lower limit reverts PushStarved: nothing moves)'
119
+
120
+ export const HINTS = {
121
+ NotAgent: 'only an Agent can create a V3 token, so only an Agent gets a floor module',
122
+ NotFactory: 'this floor factory is not allowed on the platform\'s GangHandlerAdmin: it cannot list a floor module as a tax recipient. If GANG_FLOOR_FACTORY / GANG_TESTNET_FLOOR_FACTORY is set, unset or fix it; otherwise launch without --floor',
123
+ NoVanityDeployer: 'this pad does not create its tokens at an address known in advance (its CREATE2 deployer is not on): a floor module is cloned for one token address, so --floor is not available here yet',
124
+ BadToken: 'the token address a floor 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)',
125
+ BadCap: '--tax-cap must be above 0 when payees take a share, and left out when they don\'t',
126
+ BadBps: '--tax-cap-share is 0.01–100% of the recipient\'s part, and --redeem-fee 0–5%',
127
+ BadPayees: 'with --tax-cap: 1–10 payees (--split), one share each; without it: no payees',
128
+ BadShares: 'each payee share at least 0.01% (1 bps) of the payees\' part, all adding up to 100% of it',
129
+ BadPayee: 'a payee cannot be the floor module itself',
130
+ DuplicatePayee: 'that address is a payee already (each address holds at most one slot)',
131
+ ZeroAddress: 'the zero address cannot be a payee, the quote, or where a redemption is paid',
132
+ BadIndex: 'no payee slot with that index (gang floor status lists them, from 0; a module without payees has none)',
133
+ NotPayee: 'only the current payee of a slot can move it to another address',
134
+ AlreadyBound: 'the floor module is bound to its token already',
135
+ NotBound: 'the floor module is not bound to its token yet (gang floor bind --token <the token>): nothing is split or redeemed before that',
136
+ WrongToken: 'a floor module serves only the token it was cloned for (floorToken): this is another token',
137
+ NotCurve: 'the token the floor module was cloned for is not created yet (or is not a V3 curve token on this pad)',
138
+ NotCreator: 'the token at the module\'s address was not created by the module\'s dev',
139
+ NotRecipient: 'the token does not pay its tax to this floor module',
140
+ WrongQuote: 'the token\'s quote is not the floor module\'s quote (floorQuote): it can never be bound',
141
+ BadQuote: 'the treasury\'s quote must be WBNB, GANG or a quote in the pad\'s QuoteRegistry: a launch with --floor needs one of those as its quote',
142
+ NothingForRecipient: 'the token gives all of its tax to the holders\' dividend (--dividend 100): nothing would ever reach the floor module, so it can\'t be bound',
143
+ NothingOwed: 'nothing is owed to that slot (gang floor status shows what each slot is owed). If a split just paid it, there is nothing left to release',
144
+ NotTradable: 'the token has not graduated: redemptions start once it trades in its PancakeSwap pair (the pool tax, which fills the treasury, starts then too)',
145
+ Slippage: 'the redemption would pay less than the minimum asked: the treasury per token only falls when the quote itself is taken from the module (a freezable quote); run gang floor redeem again to see what it pays now',
146
+ NothingToRedeem: 'this amount redeems for nothing: the treasury is empty, or the amount is too small',
147
+ ZeroAmount: '--amount must be above 0',
148
+ BadTo: '--to cannot be the floor module itself',
149
+ PushStarved: `the tx's gas limit was too low for the payee pushes: ${COMBO_GAS_NOTE}`,
150
+ }
151
+ export const revertOf = (e) => revertIn(e, [FLOOR_ABI, FLOOR_FACTORY_ABI], HINTS)
152
+
153
+ /** Dry-run a call; { failed } with the revert when it would not pass. */
154
+ export async function simulateFloor(client, from, address, abi, functionName, args = []) {
155
+ try {
156
+ const { result } = await client.simulateContract({ account: from, address, abi, functionName, args })
157
+ return { result }
158
+ } catch (e) {
159
+ const r = revertOf(e)
160
+ return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
161
+ }
162
+ }
163
+
164
+ /** The create target's floor factory (a launch clones its floor module there), or null when not deployed. */
165
+ export function floorFactoryAddress(testnet) {
166
+ return gangGens(testnet)[0].floorFactory || null
167
+ }
168
+
169
+ export const floorNotDeployed = (testnet) => (testnet
170
+ ? 'GangFloorModuleFactory (the floor module, --floor) is not deployed on the BSC testnet in this CLI version: set GANG_TESTNET_FLOOR_FACTORY to its address, or launch without --floor'
171
+ : 'GangFloorModuleFactory (the floor module, --floor) is not deployed on BSC mainnet in this CLI version: set GANG_FLOOR_FACTORY to its address, or launch without --floor')
172
+
173
+ export const PERMANENT_NOTE = 'PERMANENT: the token it serves, the quote, the redemption fee, the cap, the payees\' % and the payees and their shares are fixed for good — nobody (not you, not the platform) can change them later; a payee can only move its own slot to another address (gang floor set-payee)'
174
+ export const FLOOR_NOTE = 'What the floor is: the treasury per token, in the quote — anyone can give up tokens for it at any time after graduation. What it is not: a price promise. It starts at 0 (the curve pays no tax), grows only with pool volume, and is usually far below the market price: redeeming tokens bought above it is a loss. It is never lowered by a redemption (with a fee, each one raises it); only a quote that is itself frozen or taken from the module can lower it'
175
+ export const OTHER_ASSETS_NOTE = 'any other asset sent to it (not the token\'s quote) cannot count in the treasury: all of it goes to 0xdead when it is distributed (gang floor distribute --asset <addr>, anyone), never to holders or payees; one that cannot be sent there stays in the module'
176
+ export const UNCHECKED_NOTE = 'could not check whether GangFloorModuleFactory made this module (RPC error): nothing is shown or built until it is known — run the same command again'
177
+ export const UNVERIFIED_NOTE = 'this contract says it is a floor module, but GangFloorModuleFactory did not make it (GangHandlerAdmin.moduleOf): its numbers are its own claims, and this CLI builds no redemption or other call against it'
178
+
179
+ // ---- the launch's flags
180
+
181
+ const PCT_RE = /^(\d{1,3})(?:\.(\d{1,2}))?$/
182
+ const pctBps = (raw) => {
183
+ const m = PCT_RE.exec(String(raw ?? '').trim())
184
+ return m ? Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0')) : null
185
+ }
186
+ const FEE_USAGE = '--redeem-fee is the % of each redemption that stays in the treasury for the holders who remain: 0 to 5, at most 2 decimals (left out: 2)'
187
+ const FLOOR_SPLIT_NOTE = 'with --floor, --split lists the payees of the capped part (it needs --tax-cap), their shares adding up to 100 (of that part)'
188
+
189
+ /** --redeem-fee → { redeemFeeBps } (0–500) or { error }. Left out: 2%. */
190
+ export function parseRedeemFee(raw) {
191
+ if (raw === undefined) return { redeemFeeBps: DEFAULT_REDEEM_FEE_BPS }
192
+ const bps = pctBps(raw)
193
+ if (bps === null || bps > MAX_REDEEM_FEE_BPS) return { error: FEE_USAGE, got: raw ?? null }
194
+ return { redeemFeeBps: bps }
195
+ }
196
+
197
+ /** A payee's share (bps of the payees' part) as a % of the recipient's whole part, until the cap. */
198
+ const ofRecipient = (share, payBps) => Math.round((Number(share) * Number(payBps)) / 1e2) / 1e4
199
+
200
+ /**
201
+ * A floor launch's flags → { payBps, redeemFeeBps, payees, shares, list, capped } or { error, … }, checked as
202
+ * GangFloorModule.initialize checks them. `cap`: whether --tax-cap is given (its amount needs the quote's decimals:
203
+ * capped.js capUnits); `capShare` / `split` / `redeemFee`: the raw flags (undefined when absent); `me`: the creating
204
+ * wallet. Without --tax-cap there are no payees: all of the recipient's part is the treasury.
205
+ */
206
+ export function parseFloorSpec({ cap = false, capShare, split, redeemFee } = {}, me) {
207
+ const fee = parseRedeemFee(redeemFee)
208
+ if (fee.error) return fee
209
+ if (!cap) {
210
+ if (capShare !== undefined) return { error: '--tax-cap-share goes with --tax-cap <amount>: with --floor alone nobody takes a share, all of the recipient\'s part is the treasury' }
211
+ if (split !== undefined) return { error: '--split goes with --tax-cap <amount>: with --floor alone there are no payees, all of the recipient\'s part is the treasury', hint: FLOOR_SPLIT_NOTE }
212
+ return { payBps: 0, redeemFeeBps: fee.redeemFeeBps, payees: [], shares: [], list: [], capped: false }
213
+ }
214
+ const share = parseCapShare(capShare)
215
+ if (share.error) return share
216
+ let spec
217
+ if (split === undefined) {
218
+ if (!isAddress(me ?? '')) return { error: 'the capped part goes to your wallet: sign in with baw, or give --from (or name the payees with --split)' }
219
+ spec = { payees: [getAddress(me)], shares: [BPS], list: [{ index: 0, payee: getAddress(me), pct: 100, you: true }] }
220
+ } else {
221
+ spec = parseSplitSpec(split, me)
222
+ if (spec.error) return { ...spec, hint: spec.hint ? `${spec.hint}. ${FLOOR_SPLIT_NOTE}` : FLOOR_SPLIT_NOTE }
223
+ }
224
+ return {
225
+ payBps: share.payBps, redeemFeeBps: fee.redeemFeeBps, payees: spec.payees, shares: spec.shares, capped: true,
226
+ list: spec.list.map(({ pct: p, ...x }) => ({ ...x, pctOfPayees: p, pctOfRecipientUntilCap: ofRecipient(spec.shares[x.index], share.payBps) })),
227
+ }
228
+ }
229
+
230
+ // ---- the contract's math (pure: unit-tested to the wei)
231
+
232
+ /** _partsOf: how `incoming` of the bound quote splits with `paid` already credited against `capAmount`. */
233
+ export function partsOf(incoming, paid, capAmount, payBps) {
234
+ let toPayees = (BigInt(incoming) * BigInt(payBps)) / 10_000n
235
+ const left = BigInt(capAmount) - BigInt(paid)
236
+ if (toPayees > left) toPayees = left
237
+ return { toPayees, toTreasury: BigInt(incoming) - toPayees }
238
+ }
239
+
240
+ /** _quoteFor: what `amount` tokens redeem for against `held` over `supply`, and the fee left in the treasury. */
241
+ export function quoteFor(amount, held, supply, redeemFeeBps) {
242
+ if (BigInt(supply) === 0n) return { quoteOut: 0n, fee: 0n }
243
+ const gross = (BigInt(amount) * BigInt(held)) / BigInt(supply)
244
+ const fee = (gross * BigInt(redeemFeeBps)) / 10_000n
245
+ return { quoteOut: gross - fee, fee }
246
+ }
247
+
248
+ /**
249
+ * How much of the pool's volume reaches the treasury, in % of volume (spec §1): (tax − platform tax) × (1 − dividend) ×
250
+ * (1 − pay share), until the cap and after it. Buys pay the buy tax and sells the sell tax: `low` / `high` when they differ.
251
+ */
252
+ export function treasuryShare({ buyTaxPct, sellTaxPct, platformTaxPct = 0.5, dividendPct = 0, payBps = 0 }) {
253
+ const at = (tax, pay) => Math.max(0, Math.round((tax - platformTaxPct) * (1 - dividendPct / 100) * (1 - pay / BPS) * 1e4) / 1e4)
254
+ const of = (pay) => {
255
+ const [a, b] = [at(buyTaxPct, pay), at(sellTaxPct, pay)]
256
+ return a === b ? { pctOfVolume: a } : { pctOfVolume: { buys: a, sells: b } }
257
+ }
258
+ const after = of(0)
259
+ return {
260
+ ...(Number(payBps) > 0 && { untilCap: of(Number(payBps)) }), afterCap: after,
261
+ how: `(tax − ${platformTaxPct}% platform) × (1 − ${dividendPct}% dividend)${Number(payBps) > 0 ? ` × (1 − ${Number(payBps) / 100}% to the payees, until the cap)` : ''}, of pool volume after graduation. While no holder has 10,000+ tokens the holders' part falls back to the recipient, so a little more arrives`,
262
+ }
263
+ }
264
+
265
+ /** The floor module's terms as one line, for a launch preview and a re-run's refusal. */
266
+ export function floorLine({ cap, symbol, payBps, redeemFeeBps, payees, shares }) {
267
+ const fee = `a redemption leaves ${Number(redeemFeeBps) / 100}% of what it takes in the treasury`
268
+ if (!payees.length) return `all of it stays in the treasury that holders can redeem; ${fee}`
269
+ const who = payees.map((x, i) => `${x}: ${Number(shares[i]) / 100}% of it`).join(', ')
270
+ const until = Number(payBps) === BPS ? `all of it to ${who}` : `${Number(payBps) / 100}% to ${who}, the rest to the treasury`
271
+ return `until the payees have been credited ${cap} ${symbol ?? 'of the quote'} in all: ${until}. From then on all of it stays in the treasury that holders can redeem; ${fee}`
272
+ }
273
+
274
+ const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
275
+ /**
276
+ * The treasury per whole token, as text: `treasury` (quote wei) over `supply` (token wei, 18 decimals), less `feeBps`.
277
+ * Computed here with 6 more digits than the contract's floorPrice(), which rounds to the quote's smallest unit per
278
+ * whole token (0 for a small treasury in a quote with few decimals).
279
+ */
280
+ const perToken = (treasury, supply, quoteDecimals, feeBps = 0) => {
281
+ if (BigInt(supply ?? 0n) === 0n) return '0'
282
+ // 6 digits past the quote's own decimals: enough to see a floor under one unit of it, without a tail of noise
283
+ const scaled = (BigInt(treasury ?? 0n) * 10n ** 24n * BigInt(BPS - feeBps)) / (BigInt(supply) * BigInt(BPS))
284
+ return formatUnits(scaled, quoteDecimals + 6)
285
+ }
286
+
287
+ /**
288
+ * The module's state for printing, from the raw reads (pure: unit-tested). `raw`: { module, verified, dev, floorToken,
289
+ * token, quote, floorQuote, quoteSymbol, quoteDecimals, capAmount, paidTotal, payBps, redeemFeeBps, payees, shares,
290
+ * treasuryHeld, treasury, payeesPending, floorSupply, floorPrice, unsplit, lastPaidAt, keeperServesQuote, work: [due,
291
+ * minOut] | null, graduated: bool | null, tokenExists: bool, assets: [{ asset, symbol, decimals, undistributed,
292
+ * owedTotal, owed: bigint[] | null }] }. `ref`: how later commands name it.
293
+ */
294
+ export function formatFloor(raw, ref) {
295
+ const token = raw.token && raw.token !== zeroAddress ? raw.token : null
296
+ const quote = token && raw.quote && raw.quote !== zeroAddress ? raw.quote : null
297
+ const isQuote = (a) => !!quote && a.toLowerCase() === quote.toLowerCase()
298
+ const dec = raw.quoteDecimals ?? 18
299
+ const fq = (x) => formatUnits(BigInt(x ?? 0n), dec)
300
+ const payBps = Number(raw.payBps), feeBps = Number(raw.redeemFeeBps)
301
+ const capAmount = BigInt(raw.capAmount), paid = BigInt(raw.paidTotal)
302
+ const hasPayees = raw.payees.length > 0
303
+ const left = capAmount - paid
304
+ const reached = left <= 0n
305
+ const dev = String(raw.dev).toLowerCase()
306
+ const payees = raw.payees.map((payee, index) => ({
307
+ index, payee, pctOfPayees: Number(raw.shares[index]) / 100, pctOfRecipientUntilCap: ofRecipient(raw.shares[index], payBps),
308
+ bps: Number(raw.shares[index]), ...(payee.toLowerCase() === dev && { isDev: true }),
309
+ }))
310
+ const unsplit = BigInt(raw.unsplit ?? 0n)
311
+ const pending = partsOf(unsplit, paid, capAmount, payBps)
312
+ const sym = raw.quoteSymbol || raw.floorQuote
313
+ const next = []
314
+ const assets = []
315
+ for (const a of raw.assets ?? []) {
316
+ const owedTotal = a.owedTotal ?? 0n
317
+ const undistributed = a.undistributed ?? 0n
318
+ if (!isQuote(a.asset) && undistributed === 0n && owedTotal === 0n) continue
319
+ const f = (x) => formatUnits(x, a.decimals ?? 18)
320
+ const owed = owedTotal > 0n && a.owed
321
+ ? a.owed.map((x, index) => ({ index, payee: raw.payees[index], amount: f(x) })).filter((_, i) => a.owed[i] > 0n) : []
322
+ const burns = !!token && !isQuote(a.asset) && undistributed > 0n
323
+ assets.push({
324
+ asset: a.asset, symbol: a.symbol ?? null, ...(isQuote(a.asset) && { boundQuote: true }),
325
+ undistributed: f(undistributed), owedTotal: f(owedTotal), ...(owed.length && { owed }), ...(burns && { burns: true }),
326
+ })
327
+ if (burns && raw.verified === true) next.push(`gang floor distribute ${ref} --asset ${a.asset} (BURNS all of it: sends it to 0xdead, paid to nobody; only if that is wanted)`)
328
+ for (const o of owed) if (raw.verified === true) next.push(`gang floor release ${ref} --asset ${a.asset} --index ${o.index}`)
329
+ }
330
+ const pendingPay = BigInt(raw.payeesPending ?? 0n) + pending.toPayees
331
+ const ok = raw.verified === true
332
+ if (token && ok && pendingPay > 0n) next.unshift(`gang floor distribute ${ref} (pushes the payees' ${fq(pendingPay)} ${sym})`)
333
+ if (!token && ok) next.unshift(raw.tokenExists ? `gang floor bind ${String(ref).replace(/^--module \S+/, `--token ${raw.floorToken}`)}` : 'nothing yet: the token it was cloned for is not created')
334
+ if (token && ok && raw.graduated && BigInt(raw.treasury ?? 0n) > 0n) next.push(`gang floor redeem ${ref} --amount <tokens>`)
335
+
336
+ const [due] = raw.work ?? [false, 0n]
337
+ const state = raw.verified === null ? 'unchecked' : !ok ? 'unverified' : !token ? 'unbound' : raw.graduated === false ? 'before-graduation' : 'live'
338
+ const stateLine = {
339
+ unchecked: UNCHECKED_NOTE,
340
+ unverified: UNVERIFIED_NOTE,
341
+ unbound: raw.tokenExists
342
+ ? 'Not bound yet: the token it was cloned for exists, anyone can bind it (gang floor bind). Nothing is split or redeemed before that'
343
+ : 'Not bound yet: the token it was cloned for does not exist. Whatever reaches the module waits; it can never serve another token',
344
+ 'before-graduation': 'The token has not graduated: the pool tax that fills the treasury starts at graduation, and so do redemptions',
345
+ live: BigInt(raw.treasury ?? 0n) === 0n ? 'The treasury is empty so far: it fills with the pool tax' : `Each token redeems for ${perToken(raw.treasury, raw.floorSupply, dec)} ${sym} before the ${feeBps / 100}% fee`,
346
+ }[state]
347
+ const capLine = !hasPayees ? 'No payees: all of the recipient\'s part is the treasury'
348
+ : reached ? `The cap is reached: the payees were credited ${fq(capAmount)} ${sym} in all, and every payment now stays in the treasury`
349
+ : `${fq(paid)} of the ${fq(capAmount)} ${sym} cap credited to the payees so far, ${fq(left)} left`
350
+ return {
351
+ module: raw.module, moduleType: FLOOR_TYPE, verified: raw.verified === null ? null : ok, state, dev: raw.dev, floorToken: raw.floorToken,
352
+ token, quote, quoteSymbol: raw.quoteSymbol ?? null, floorQuote: raw.floorQuote, quoteDecimals: dec,
353
+ ...(raw.quoteDecimalsUnread && { decimalsNote: 'the quote\'s decimals could not be read: amounts assume 18' }),
354
+ treasury: fq(raw.treasury ?? 0n), floorSupply: formatUnits(BigInt(raw.floorSupply ?? 0n), 18),
355
+ floorPerToken: perToken(raw.treasury, raw.floorSupply, dec), redeemFeePct: feeBps / 100, redeemFeeBps: feeBps,
356
+ redeemPerTokenAfterFee: perToken(raw.treasury, raw.floorSupply, dec, feeBps),
357
+ ...(hasPayees
358
+ ? { cap: { amount: fq(capAmount), paid: fq(paid), left: fq(left), reached, progressPct: capAmount > 0n ? Number((paid * 10_000n) / capAmount) / 100 : 0 }, payPct: payBps / 100, payBps, payees }
359
+ : { cap: null, payPct: 0, payBps: 0, payees: [] }),
360
+ permanent: true,
361
+ unsplit: fq(unsplit),
362
+ ...(unsplit > 0n && { unsplitGoes: { toPayees: fq(pending.toPayees), toTreasury: fq(pending.toTreasury) } }),
363
+ payeesPending: fq(raw.payeesPending ?? 0n),
364
+ lastPaidAt: iso(raw.lastPaidAt ?? 0n),
365
+ keeper: { servesQuote: token ? !!raw.keeperServesQuote : null, due: !!due },
366
+ assets,
367
+ ...(next.length && { next }),
368
+ floor: FLOOR_NOTE,
369
+ note: `${stateLine}. ${capLine}. ${PERMANENT_NOTE}. The treasury needs no keeper; a redemption pushes no payee — what it sets aside for them is pushed by the next gang floor distribute (anyone) or the keeper`,
370
+ }
371
+ }
372
+
373
+ /** Reads `asset`'s side of the module; null when it is not an ERC20 the module can read. */
374
+ async function assetRaw(read, module, asset, n) {
375
+ let undistributed, owedTotal
376
+ try {
377
+ [undistributed, owedTotal] = await Promise.all([
378
+ read(module, FLOOR_ABI, 'undistributed', [asset]), read(module, FLOOR_ABI, 'owedTotal', [asset]),
379
+ ])
380
+ } catch { return null }
381
+ const [symbol, decimals, owed] = await Promise.all([
382
+ read(asset, ERC20_ABI, 'symbol').catch(() => null),
383
+ read(asset, ERC20_ABI, 'decimals').then(Number).catch(() => 18),
384
+ owedTotal > 0n && n > 0 ? Promise.all(Array.from({ length: n }, (_, i) => read(module, FLOOR_ABI, 'owedOf', [asset, BigInt(i)]))) : null,
385
+ ])
386
+ return { asset, symbol, decimals, undistributed, owedTotal, owed }
387
+ }
388
+
389
+ /**
390
+ * Whether `module` was made by `factory` (GangHandlerAdmin.moduleOf): the only thing that makes a contract a floor
391
+ * module. null when it could not be read (RPC): never treated as verified, and never reported as "not made by it".
392
+ */
393
+ export async function floorVerified(read, module, factory) {
394
+ if (!factory) return false
395
+ try {
396
+ const admin = await read(factory, FLOOR_FACTORY_ABI, 'admin')
397
+ return (await read(admin, ADMIN_ABI, 'moduleOf', [module])).toLowerCase() === factory.toLowerCase()
398
+ } catch { return null }
399
+ }
400
+
401
+ const LISTING_ABI = parseAbi([
402
+ 'function taxHandler() view returns (address)', 'function isListed(address recipient) view returns (bool)',
403
+ 'function owner() view returns (address)',
404
+ ])
405
+ /** A module kind as every one of the platform's modules names itself: `split-v1`, `buyback-burn-v4`, `floor-v1`. */
406
+ const KIND_RE = /^[a-z][a-z0-9-]*-v\d+$/
407
+
408
+ /**
409
+ * The node ran the call and the contract reverted: JSON-RPC code 3 (or -32000, as older nodes send it) whose message
410
+ * is "execution reverted" (any case; alone or with a reason after a colon), with no data or real revert data (a
411
+ * selector and more). NOT a node's own failure: an internal error (-32603), a gateway's message that only mentions a revert, "gas
412
+ * required exceeds allowance", a rate limit dressed as code 3, data that is not revert data.
413
+ */
414
+ function revertedCall(e) {
415
+ // the node's own error (viem wraps a -32000 in a class that keeps the code and the message but drops the data)
416
+ const x = e?.walk?.((y) => y?.name === 'RpcRequestError' && typeof y.code === 'number') ?? null
417
+ if (!x || (x.code !== 3 && x.code !== -32000)) return false
418
+ if (!/^execution reverted(:|$)/i.test(String(x.details ?? x.message ?? '').trim())) return false
419
+ const data = x.data && typeof x.data === 'object' ? x.data.data : x.data
420
+ return data == null || data === '0x' || (typeof data === 'string' && /^0x([0-9a-fA-F]{2}){4,}$/.test(data))
421
+ }
422
+
423
+ /**
424
+ * Is `recipient` — an address someone typed as the tax recipient of a token created on `pad` — a floor module?
425
+ * → { floor: true, by } | { floor: false } | { unlisted: true } | { unread: <detail> }.
426
+ * A token that names a floor module by hand lands at another address than the one the module was cloned for, and its
427
+ * tax is stuck there for good. So "no" is said only on the chain's own evidence, and whatever a node leaves unanswered
428
+ * is `unread` (the caller builds nothing and asks to run again), never "no".
429
+ * Every read is at ONE block (the latest one the node names): a node that does not have that block fails the read, so
430
+ * a node behind the chain can't answer "no code" or "not listed" for a module cloned seconds ago. The reads whose
431
+ * answer can be "no" (the registries, the code, moduleType()) go to the node raw: only a hex string is an answer —
432
+ * `null`, an empty string or a missing result is the node's silence, not the contract's.
433
+ * 1. The pad takes a recipient that is not the creator only when its tax handler lists it (CurveLogic3.checkTax). Not
434
+ * listed at that block: `unlisted` — the create is refused whatever the address is.
435
+ * 2. The floor `factory` (the create target's; null where there is none) has its modules recorded by the
436
+ * GangHandlerAdmin it was built over (factory.admin(), fixed for good; moduleOf, written in the clone's tx): a
437
+ * floor module, whoever owns the handler by now.
438
+ * 3. The handler's owner (that admin, or a later one) records which factory listed a module. Listed by a factory: one
439
+ * of the platform's modules, and every one of those names its kind (moduleType(): `split-v1`, `floor-v1`, …).
440
+ * `floor-v1` (a floor factory this CLI does not know): a floor module. Another kind: not one. No answer, or an
441
+ * answer that is no kind's name: `unread`.
442
+ * 4. Listed by no factory (the platform listed it by hand: a partner's treasury): a wallet (no code at that block) is
443
+ * not a module. A contract is asked moduleType(): `floor-v1` → a floor module; any other word (or more than a
444
+ * word), an empty return, or a revert (revertedCall) → not one; a piece of a word, or no answer → `unread`.
445
+ */
446
+ export async function typedFloorModule({ client, pad }, recipient, factory) {
447
+ try {
448
+ const blockNumber = await client.getBlockNumber()
449
+ const block = numberToHex(blockNumber)
450
+ const at = (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args, blockNumber })
451
+ /** The node's own word, raw: a hex string, or the failure. */
452
+ const hex = async (method, params) => {
453
+ const r = await client.request({ method, params: [...params, block] })
454
+ if (typeof r !== 'string' || !/^0x([0-9a-fA-F]{2})*$/.test(r)) throw new Error(`the node gave no result for ${method}`)
455
+ return r
456
+ }
457
+ /** moduleOf(recipient) on `admin`: the factory, the zero address, or null when `admin` keeps no such record. */
458
+ const listedBy = async (admin) => {
459
+ let r
460
+ try { r = await hex('eth_call', [{ to: admin, data: encodeFunctionData({ abi: ADMIN_ABI, functionName: 'moduleOf', args: [recipient] }) }]) } catch (e) {
461
+ if (!revertedCall(e)) throw e
462
+ return null
463
+ }
464
+ if (r === '0x') return null // not a contract, or one whose fallback returns nothing
465
+ if (r.length !== 66 || !/^0x0{24}/.test(r)) throw new Error('moduleOf answered something that is not an address')
466
+ return getAddress(`0x${r.slice(26)}`)
467
+ }
468
+ const same = (x, y) => !!x && !!y && x.toLowerCase() === y.toLowerCase()
469
+
470
+ const handler = await at(pad, LISTING_ABI, 'taxHandler')
471
+ if (!(await at(handler, LISTING_ABI, 'isListed', [recipient]))) return { unlisted: true }
472
+ const owner = await at(handler, LISTING_ABI, 'owner')
473
+ let by = null
474
+ if (factory) {
475
+ const admin = await at(factory, FLOOR_FACTORY_ABI, 'admin')
476
+ const listed = await listedBy(admin)
477
+ if (same(listed, factory)) return { floor: true, by: 'GangHandlerAdmin.moduleOf' }
478
+ // recorded there for another factory: a factory's module too, whoever owns the handler by now
479
+ by = same(admin, owner) || (listed && listed !== zeroAddress) ? listed : await listedBy(owner)
480
+ } else by = await listedBy(owner)
481
+ const byFactory = !!by && by !== zeroAddress
482
+
483
+ if (!byFactory && (await hex('eth_getCode', [recipient])) === '0x') return { floor: false }
484
+ let r
485
+ try { r = await hex('eth_call', [{ to: recipient, data: encodeFunctionData({ abi: FLOOR_ABI, functionName: 'moduleType' }) }]) } catch (e) {
486
+ // a module a factory listed always answers: a revert from one is not the chain's word
487
+ if (byFactory || !revertedCall(e)) throw e
488
+ return { floor: false }
489
+ }
490
+ const kind = r.length === 66 ? hexToString(r, { size: 32 }).replace(/\0+$/, '') : null
491
+ if (kind === FLOOR_TYPE) return { floor: true, by: 'moduleType()' }
492
+ if (byFactory) {
493
+ if (kind === null || !KIND_RE.test(kind)) throw new Error('a listed module did not name its kind')
494
+ return { floor: false }
495
+ }
496
+ // listed by hand: an empty return (no such function, a silent fallback), a full word or more is the contract's
497
+ // answer — a floor module returns exactly one word, and a node's failure never makes an answer longer. A piece of
498
+ // a word is not an answer
499
+ if (r !== '0x' && r.length < 66) throw new Error('moduleType() answered less than a word')
500
+ return { floor: false }
501
+ } catch (e) {
502
+ return { unread: e?.details || String(e?.shortMessage ?? e?.message ?? e).split('\n')[0] }
503
+ }
504
+ }
505
+
506
+ /**
507
+ * The module's state when `addr` answers `floor-v1`; null when it does not. `factory`: the floor factory of the pad's
508
+ * generation (the provenance check). Assets read: the quote, WBNB, the module's GANG and `extraAssets`.
509
+ */
510
+ export async function floorOf(read, addr, { wbnb, pad, factory, extraAssets = [], ref, getCode } = {}) {
511
+ if (!addr || addr === zeroAddress) return null
512
+ let type
513
+ try { type = await read(addr, FLOOR_ABI, 'moduleType') } catch { return null }
514
+ if (hexToString(type, { size: 32 }).replace(/\0+$/, '') !== FLOOR_TYPE) return null
515
+ const FIELDS = ['dev', 'floorToken', 'token', 'quote', 'floorQuote', 'capAmount', 'paidTotal', 'payBps', 'redeemFeeBps', 'payeesOf', 'treasuryHeld', 'treasury', 'payeesPending', 'floorSupply', 'floorPrice', 'unsplit', 'lastPaidAt']
516
+ const [vals, gangQuote, verified] = await Promise.all([
517
+ Promise.all(FIELDS.map((f) => read(addr, FLOOR_ABI, f))),
518
+ read(addr, FLOOR_ABI, 'gangQuote').catch(() => zeroAddress),
519
+ floorVerified(read, addr, factory),
520
+ ])
521
+ const r = Object.fromEntries(FIELDS.map((f, i) => [f, vals[i]]))
522
+ const [payees, shares] = r.payeesOf
523
+ const bound = r.token !== zeroAddress
524
+ const [work, keeperServesQuote, graduated, units, tokenExists] = await Promise.all([
525
+ bound ? read(addr, FLOOR_ABI, 'previewWork').catch(() => null) : null,
526
+ bound ? read(addr, FLOOR_ABI, 'keeperServes', [r.quote]).catch(() => false) : false,
527
+ bound && pad ? read(pad, PAD_ABI, 'curves', [r.token]).then((c) => c[6]).catch(() => null) : null,
528
+ quoteUnits(read, r.floorQuote),
529
+ bound ? true : pad ? read(pad, PAD_ABI, 'curves', [r.floorToken]).then((c) => c[0] !== zeroAddress).catch(() => (getCode ? getCode(r.floorToken).then((c) => !!c && c !== '0x').catch(() => false) : false)) : false,
530
+ ])
531
+ const seen = new Set()
532
+ const list = [r.quote, r.floorQuote, wbnb, gangQuote, ...extraAssets].filter((a) => {
533
+ if (!a || a === zeroAddress || seen.has(a.toLowerCase())) return false
534
+ seen.add(a.toLowerCase())
535
+ return true
536
+ })
537
+ const assets = (await Promise.all(list.map((a) => assetRaw(read, addr, a, payees.length)))).filter(Boolean)
538
+ return formatFloor({
539
+ module: addr, verified, dev: r.dev, floorToken: r.floorToken, token: r.token, quote: r.quote,
540
+ floorQuote: r.floorQuote, quoteSymbol: units.symbol, quoteDecimals: units.decimals ?? 18,
541
+ ...(units.decimals === null && { quoteDecimalsUnread: true }),
542
+ capAmount: r.capAmount, paidTotal: r.paidTotal, payBps: r.payBps, redeemFeeBps: r.redeemFeeBps, payees, shares,
543
+ treasuryHeld: r.treasuryHeld, treasury: r.treasury, payeesPending: r.payeesPending, floorSupply: r.floorSupply,
544
+ floorPrice: r.floorPrice, unsplit: r.unsplit, lastPaidAt: r.lastPaidAt, keeperServesQuote, work, graduated, tokenExists, assets,
545
+ }, ref ?? (bound ? `--token ${r.token}` : `--module ${addr}`))
546
+ }
547
+
548
+ /**
549
+ * When `token` pays its tax to a floor module that is not its own (cloned for another token): what to say. This token
550
+ * has no floor; its tax is a gift to the other token's holders (or waits in a module whose token does not exist).
551
+ */
552
+ export function notItsFloor(s, token) {
553
+ if (!token || String(s.floorToken).toLowerCase() === token.toLowerCase()) return null
554
+ return `this token pays its tax to a floor module cloned for another token (${s.floorToken}): this token has NO floor and its holders can redeem nothing — its tax goes to the payees and the treasury of that other token${s.token ? '' : ', which is not even bound yet (the tax waits in the module)'}`
555
+ }
556
+
557
+ /**
558
+ * What may be shown of `s` for `token` (null: the module named directly). A module the factory did not make, one that
559
+ * could not be checked, or one cloned for another token is NOT this token's floor: only what it is and the warning are
560
+ * shown — no treasury, no price per token, no next command (spec §6, §8). Else `s` as it is.
561
+ */
562
+ export function floorShown(s, token) {
563
+ const warning = s.verified === null ? UNCHECKED_NOTE : !s.verified ? UNVERIFIED_NOTE : notItsFloor(s, token)
564
+ if (!warning) return s
565
+ return {
566
+ module: s.module, claims: FLOOR_TYPE, verified: s.verified, isThisTokensFloor: false,
567
+ ...(s.verified === true && { floorToken: s.floorToken }), warning,
568
+ }
569
+ }
570
+
571
+ function floorCtx(testnet) {
572
+ const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
573
+ if (!net.pad) throw new Error(NOT_ON_MAINNET)
574
+ const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
575
+ return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
576
+ }
577
+
578
+ const SUBS = ['status', 'redeem', 'distribute', 'release', 'set-payee', 'bind']
579
+ const USAGE = 'usage: gang floor <status|redeem|distribute|release|set-payee|bind> --token <addr> (or --module <addr>) [--amount <tokens>|all] [--to <addr>] [--break-bond] [--break-call-bond] [--settle-first] [--asset <addr>|wbnb] [--index <i>] [--max <amount>] [--testnet] — see gang help'
580
+
581
+ /** `gang floor <sub>`: the floor module of a V3 token (its tax recipient), found from --token (or named by --module). */
582
+ export async function runFloor(sub, { opt, flag, out, fail, summarize }) {
583
+ if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
584
+ const testnet = flag('testnet')
585
+ const rawOnly = flag('calldata')
586
+ let ctx
587
+ try { ctx = floorCtx(testnet) } catch (e) { return fail(e.message) }
588
+ const chainId = Number(ctx.chainId)
589
+ const tn = testnet ? ' --testnet' : ''
590
+ if (flag('token') && flag('module')) fail('give --token (its tax recipient is the floor module) or --module, not both')
591
+ let token = null, module, tokenQuote = null, padKnown = true, curve = null
592
+ if (flag('module')) {
593
+ if (sub === 'redeem') fail('gang floor redeem needs --token <the token>: it redeems that token against its own floor module')
594
+ module = opt('module')
595
+ if (!isAddress(module ?? '')) fail('--module must be a floor module address (0x…)', { got: module ?? null })
596
+ const pad = await ctx.read(module, FLOOR_ABI, 'pad').catch(() => null)
597
+ padKnown = !!pad && atPad(ctx, pad, testnet)
598
+ } else {
599
+ token = opt('token')
600
+ if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…), or name the module with --module <addr>', { got: token ?? null })
601
+ if ((await atTokenPad(ctx, token)) === null) return fail(KIND_UNREAD.error, { token, retry: KIND_UNREAD.retry })
602
+ try {
603
+ curve = await ctx.read(ctx.pad, PAD_ABI, 'curves', [token])
604
+ if (curve[0] === zeroAddress) throw new Error('not a curve')
605
+ tokenQuote = curve[1]
606
+ module = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3]
607
+ } catch {
608
+ return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet; add --testnet for a testnet token'})`, { token, chainId })
609
+ }
610
+ }
611
+ const ref = `${token ? `--token ${token}` : `--module ${module}`}${tn}`
612
+ const extra = sub === 'status' && flag('asset') && isAddress(opt('asset') ?? '') ? [getAddress(opt('asset'))] : []
613
+ const s = await floorOf(ctx.read, module, {
614
+ wbnb: ctx.wbnb, pad: padKnown ? ctx.pad : null, factory: padKnown ? ctx.floorFactory : null,
615
+ extraAssets: [...(tokenQuote && tokenQuote !== zeroAddress ? [tokenQuote] : []), ...extra], ref,
616
+ getCode: (a) => ctx.client.getCode({ address: a }),
617
+ })
618
+ if (!s) {
619
+ return fail(token ? 'this token\'s tax recipient is not a floor module (floor-v1)' : 'not a floor module (floor-v1)',
620
+ { ...(token && { token }), recipient: module === zeroAddress ? null : module })
621
+ }
622
+ const shown = floorShown(s, token)
623
+ if (sub === 'status') return out({ success: true, chainId, ...shown, ...(shown === s && s.token === null && { bound: false }) })
624
+
625
+ // every write is built only against a module the factory made, and never for a token that is not the module's own
626
+ if (s.verified === null) return fail(UNCHECKED_NOTE, { module: s.module, retry: 'same command again' })
627
+ if (shown !== s) return fail(shown.warning, { module: s.module, ...(shown.floorToken && { floorToken: shown.floorToken }) })
628
+
629
+ const me = () => walletFor(ctx, opt('from'))
630
+ const send = async (functionName, args, extraOut) => {
631
+ const sim = await simulateFloor(ctx.client, me(), s.module, FLOOR_ABI, functionName, args)
632
+ if (sim.failed) return out({ success: false, step: extraOut.step, ...sim.failed })
633
+ const data = encodeFunctionData({ abi: FLOOR_ABI, functionName, args })
634
+ return out(step(ctx, { from: me(), to: s.module, data }, { chainId, ...(token && { token }), module: s.module, ...extraOut }, rawOnly, summarize))
635
+ }
636
+ const assetArg = (def) => {
637
+ if (!flag('asset')) return def
638
+ const a = opt('asset')
639
+ if (/^wbnb$/i.test(a ?? '')) return ctx.wbnb
640
+ if (!isAddress(a ?? '') || a === zeroAddress) fail('--asset must be a token address (0x…, checksummed or all lowercase) or wbnb', { got: a ?? null })
641
+ return getAddress(a)
642
+ }
643
+ const assetState = async (asset) => {
644
+ const r = await assetRaw(ctx.read, s.module, asset, s.payees.length)
645
+ if (!r) fail('the module cannot read that asset\'s balance (not an ERC20?)', { asset })
646
+ return { ...r, f: (x) => formatUnits(x, r.decimals) }
647
+ }
648
+ const needBound = () => {
649
+ if (!s.token) fail(HINTS.NotBound, { module: s.module, floorToken: s.floorToken })
650
+ }
651
+ const fq = (x) => formatUnits(x, s.quoteDecimals)
652
+ const sym = s.quoteSymbol ?? 'of the quote'
653
+
654
+ if (sub === 'bind') {
655
+ if (s.token) return fail('already bound', { boundTo: s.token })
656
+ return send('bind', [s.floorToken], { step: 'bind', token: s.floorToken, note: `anyone may bind (once): the module takes only the token it was cloned for (${s.floorToken}), created by its dev, paying its tax to it, quoted in ${sym}, with less than all of the tax going to the holders' dividend` })
657
+ }
658
+
659
+ if (sub === 'redeem') {
660
+ needBound()
661
+ if (!curve[6]) return fail(HINTS.NotTradable, { token })
662
+ const wallet = me()
663
+ const bal = await ctx.read(token, ERC20_ABI, 'balanceOf', [wallet])
664
+ const rawAmount = opt('amount')
665
+ if (!flag('amount')) fail('--amount <tokens> required (or --amount all): the tokens to give up; they go to 0xdead for good')
666
+ const amount = /^all$/i.test(rawAmount ?? '') ? bal : parseUnits(parseAmount(fail, 'amount', rawAmount), 18)
667
+ if (amount === 0n) return fail(bal === 0n ? 'this wallet holds none of this token' : HINTS.ZeroAmount, { wallet })
668
+ if (amount > bal) return fail('not enough tokens', { have: formatUnits(bal, 18), need: formatUnits(amount, 18) })
669
+ let to = wallet
670
+ if (flag('to')) {
671
+ to = opt('to')
672
+ if (!isAddress(to ?? '') || to === zeroAddress) fail('--to must be a 0x address (checksummed or all lowercase): where the quote is paid (left out: this wallet)', { got: to ?? null })
673
+ if (to.toLowerCase() === s.module.toLowerCase()) return fail(HINTS.BadTo, { to })
674
+ to = getAddress(to)
675
+ }
676
+ // the tokens leave the wallet for good, as in a sell: the creator's own bond and call bond are checked the same way
677
+ const guard = await bondGuard(ctx, { token, me: wallet, amount, testnet, breakBond: flag('break-bond'), settleFirst: flag('settle-first') }, rawOnly, summarize)
678
+ const callGuard = await callBondGuard(ctx, { token, me: wallet, amount, testnet, breakBond: flag('break-call-bond') })
679
+ if (guard?.refuse || callGuard?.refuse) {
680
+ return out({
681
+ success: false, step: 'redeem', wallet, redeemingCountsAsSelling: 'a redemption sends the tokens to 0xdead: for a bond it is a sell',
682
+ ...(guard?.refuse ?? callGuard.refuse), ...(guard?.refuse && callGuard?.refuse && { callBond: callGuard.refuse }),
683
+ })
684
+ }
685
+ if (guard?.settleStep) return out(guard.settleStep)
686
+ const bondInfo = { ...guard?.info, ...callGuard?.info }
687
+ const slippage = parseNum(fail, 'slippage', opt('slippage', '0'), 0, 50)
688
+ const [[quoteOut, fee], supply, held] = await Promise.all([
689
+ ctx.read(s.module, FLOOR_ABI, 'previewRedeem', [amount]), ctx.read(s.module, FLOOR_ABI, 'floorSupply'), ctx.read(s.module, FLOOR_ABI, 'treasury'),
690
+ ])
691
+ if (quoteOut === 0n) return fail(HINTS.NothingToRedeem, { treasury: fq(held), amount: formatUnits(amount, 18) })
692
+ // the redemption against the pool: tokens bought above the floor redeem at a loss, and a sale may pay far more
693
+ const handler = await ctx.read(ctx.pad, PAD_ABI, 'taxHandler').catch(() => null)
694
+ // a quote of 0 is no price to compare with (the handler has no pair for the token): treated as unread, never as "a sale pays nothing"
695
+ const quoted = handler ? await poolSellQuote(ctx, handler, token, amount) : null
696
+ const sale = quoted && quoted.out > 0n ? quoted : null
697
+ const better = sale && sale.out > quoteOut
698
+ const poolWarning = better
699
+ ? `selling these tokens in the pool pays about ${fq(sale.out)} ${sym}, redeeming them ${fq(quoteOut)} ${sym}: the floor is below the market price, so redeeming is a loss here (gang sell --token ${token}${tn})`
700
+ : !sale ? `the pool price could not be read, so this redemption is NOT compared with a sale: the floor is usually far below the market price, and then redeeming is a loss. Check gang quote --token ${token}${tn} (or gang sell) before executing`
701
+ : null
702
+ const funding = await fundingStep(ctx, { me: wallet, token, need: amount, spender: s.module, sym: 'tokens', approveStep: 'approve' }, rawOnly, summarize)
703
+ if (funding) {
704
+ return out({
705
+ ...funding, chainId, token, module: s.module,
706
+ ...(funding.success !== false && { then: { step: 'redeem', irreversible: true, redeems: formatUnits(amount, 18), quoteOut: fq(quoteOut), quoteSymbol: s.quoteSymbol, sellingInThePoolInstead: sale ? fq(sale.out) : null } }),
707
+ ...bondInfo, ...(poolWarning && { warning: poolWarning }),
708
+ })
709
+ }
710
+ const minOut = (quoteOut * BigInt(Math.round((100 - slippage) * 100))) / 10_000n
711
+ return send('redeem', [amount, minOut, to], {
712
+ step: 'redeem', redeems: formatUnits(amount, 18), quoteOut: fq(quoteOut), fee: fq(fee), feePct: s.redeemFeePct, quoteSymbol: s.quoteSymbol,
713
+ minQuoteOut: fq(minOut), to, treasury: fq(held), floorSupply: formatUnits(supply, 18), irreversible: true,
714
+ ...(sale ? { sellingInThePoolInstead: fq(sale.out), poolQuotedWith: sale.quotedWith } : { sellingInThePoolInstead: null }),
715
+ ...bondInfo, ...(poolWarning && { warning: poolWarning }),
716
+ note: `IRREVERSIBLE: the ${formatUnits(amount, 18)} tokens go to 0xdead for good and ${to.toLowerCase() === wallet.toLowerCase() ? 'this wallet' : to} gets ${fq(quoteOut)} ${sym} — their share of the treasury (${fq(held)} ${sym} over ${formatUnits(supply, 18)} tokens) less the ${s.redeemFeePct}% fee, which stays for the holders who remain. No tax on the way. The minimum is ${slippage === 0 ? 'the previewed amount itself' : `${slippage}% under it`}: what a token redeems for only falls when the quote itself is taken from the module. Redeeming pushes no payee`,
717
+ })
718
+ }
719
+
720
+ if (sub === 'distribute') {
721
+ needBound()
722
+ const asset = assetArg(s.quote)
723
+ const a = await assetState(asset)
724
+ if (asset.toLowerCase() === s.quote.toLowerCase()) {
725
+ const [paid, capAmount, pend] = await Promise.all([ctx.read(s.module, FLOOR_ABI, 'paidTotal'), ctx.read(s.module, FLOOR_ABI, 'capAmount'), ctx.read(s.module, FLOOR_ABI, 'payeesPending')])
726
+ // a balance under what the module holds (a quote that was frozen or taken): the split only records the shortfall —
727
+ // every held part shrinks in proportion, nothing is pushed; the next call pushes
728
+ const [bal, held] = await Promise.all([ctx.read(s.quote, ERC20_ABI, 'balanceOf', [s.module]), ctx.read(s.module, FLOOR_ABI, 'treasuryHeld')])
729
+ const books = held + a.owedTotal + pend
730
+ if (bal < books) {
731
+ return send('distribute', [asset], {
732
+ step: 'distribute', asset, symbol: a.symbol, boundQuote: true, shortfall: fq(books - bal), holds: fq(bal), books: fq(books), pushedNow: fq(0n),
733
+ warning: `the module holds ${fq(bal)} ${sym}, ${fq(books - bal)} less than its books (${fq(books)}): some of the quote was frozen or taken`,
734
+ note: 'anyone may: this call only records the shortfall — the treasury, what payees are owed and what is set aside for them shrink in proportion, and nothing is pushed. Run gang floor distribute again after it to push the payees what is left for them',
735
+ })
736
+ }
737
+ if (a.undistributed === 0n && pend === 0n) {
738
+ return fail('nothing is waiting: no quote arrived since the last split and nothing is set aside for the payees', {
739
+ asset, symbol: a.symbol, owedTotal: a.f(a.owedTotal),
740
+ ...(a.owedTotal > 0n && { hint: `what payees are owed after failed pushes: gang floor release ${ref} --index <i>` }),
741
+ })
742
+ }
743
+ const p = partsOf(a.undistributed, paid, capAmount, s.payBps)
744
+ const push = p.toPayees + pend
745
+ const amounts = payeeAmounts(push, s.payees.map((x) => x.bps))
746
+ const reachesCap = paid < capAmount && paid + p.toPayees === capAmount
747
+ return send('distribute', [asset], {
748
+ step: 'distribute', asset, symbol: a.symbol, boundQuote: true, amount: fq(a.undistributed),
749
+ toTreasury: fq(p.toTreasury), toPayees: fq(p.toPayees), setAsideBefore: fq(pend), pushedNow: fq(push),
750
+ ...(s.payees.length && { parts: s.payees.map((x, i) => ({ index: x.index, payee: x.payee, pctOfPayees: x.pctOfPayees, gets: fq(amounts[i]) })) }),
751
+ ...(s.cap && { cap: { amount: fq(capAmount), paidBefore: fq(paid), paidAfter: fq(paid + p.toPayees), ...(reachesCap && { reachesCap: true }) } }),
752
+ note: `anyone may: splits the bound quote that arrived (as split())${s.payees.length ? `: ${s.payPct}% to the payees, never more than what is left of the cap, the rest to the treasury; what earlier redemptions set aside for the payees is pushed with it. A push that fails is owed to that slot; a slot that is owed from before gets that too when its push goes through. Gas: ${COMBO_GAS_NOTE}` : ': all of it is the treasury already (no payees); the call only settles the books'}`,
753
+ })
754
+ }
755
+ if (a.undistributed === 0n) return fail('nothing of this asset is in the module', { asset, symbol: a.symbol })
756
+ return send('distribute', [asset], {
757
+ step: 'distribute', asset, symbol: a.symbol, amount: a.f(a.undistributed), toDead: a.f(a.undistributed), burns: true,
758
+ note: `anyone may: this is not the bound quote, so it cannot count in the treasury: ALL of it goes to 0xdead, none to holders or payees (when it cannot be sent there it stays in the module). Gas: ${DEAD_GAS_NOTE}`,
759
+ })
760
+ }
761
+
762
+ if (sub === 'release') {
763
+ needBound()
764
+ if (!s.payees.length) return fail('this floor module has no payees: nothing is ever owed', { module: s.module })
765
+ const asset = assetArg(s.quote)
766
+ if (asset.toLowerCase() !== s.quote.toLowerCase()) {
767
+ return fail('payees are only ever owed the bound quote: any other asset goes to 0xdead (gang floor distribute --asset)', { asset, boundQuote: s.quote })
768
+ }
769
+ const a = await assetState(asset)
770
+ let index
771
+ if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
772
+ else {
773
+ const mine = s.payees.find((p) => p.payee.toLowerCase() === String(me()).toLowerCase())
774
+ const owedSlots = (a.owed ?? []).map((x, i) => (x > 0n ? i : -1)).filter((i) => i >= 0)
775
+ if (mine) index = mine.index
776
+ else if (owedSlots.length === 1) index = owedSlots[0]
777
+ else fail('--index <i> required: which payee slot to pay (gang floor status lists what each is owed)', { owedSlots })
778
+ }
779
+ const owed = a.owed ? a.owed[index] : 0n
780
+ if (owed === 0n) return fail(HINTS.NothingOwed, { asset, symbol: a.symbol, index, payee: s.payees[index].payee })
781
+ let max = maxUint256
782
+ if (flag('max')) max = parseUnits(parseAmount(fail, 'max', opt('max')), a.decimals)
783
+ const amount = owed < max ? owed : max
784
+ return send('release', [asset, BigInt(index), max], {
785
+ step: 'release', asset, symbol: a.symbol, index, payee: s.payees[index].payee, amount: a.f(amount), owed: a.f(owed),
786
+ note: `anyone may: splits what arrived first, then pushes ${max === maxUint256 ? 'all' : 'up to --max'} of what this slot is owed to its payee (it was counted against the cap when it was split; reverts while it still cannot receive). If that split's own push already pays the slot, this reverts NothingOwed and nothing moves: run gang floor distribute ${ref} instead. Gas: ${COMBO_GAS_NOTE}`,
787
+ })
788
+ }
789
+
790
+ // set-payee: only the slot's own payee; the index is the wallet's own slot unless given
791
+ if (!s.payees.length) return fail('this floor module has no payees: there is no slot to move', { module: s.module })
792
+ const wallet = String(me()).toLowerCase()
793
+ const mine = s.payees.find((p) => p.payee.toLowerCase() === wallet)
794
+ let index
795
+ if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
796
+ else if (mine) index = mine.index
797
+ else return fail('this wallet is not a payee of this floor module: only a slot\'s own payee can move it', { wallet: me(), payees: s.payees.map((p) => p.payee) })
798
+ const slot = s.payees[index]
799
+ if (slot.payee.toLowerCase() !== wallet) return fail(HINTS.NotPayee, { index, payee: slot.payee, wallet: me() })
800
+ const to = opt('to')
801
+ if (!isAddress(to ?? '') || to === zeroAddress) fail('--to <0x…> required (checksummed or all lowercase): the address this slot is paid to from now on', { got: to ?? null })
802
+ if (to.toLowerCase() === s.module.toLowerCase()) return fail(HINTS.BadPayee, { to })
803
+ const taken = s.payees.find((p) => p.payee.toLowerCase() === to.toLowerCase())
804
+ if (taken) return fail(taken.index === index ? 'that is this slot\'s payee already' : HINTS.DuplicatePayee, { to, index: taken.index })
805
+ return send('setPayee', [BigInt(index), getAddress(to)], {
806
+ step: 'set-payee', index, pctOfPayees: slot.pctOfPayees, fromPayee: slot.payee, toPayee: getAddress(to),
807
+ ...(s.cap?.reached && { capReached: true }),
808
+ note: `applies at once; the share (${slot.pctOfPayees}% of the payees' part) stays with the slot, and the cap (for all payees together) stays as it is${s.cap?.reached ? ' — it is reached, so the slot gets nothing more' : ''}. The bound quote that arrived before, and what redemptions set aside, is pushed first to the current address; what this slot is owed goes to the new one. Gas: ${COMBO_GAS_NOTE}`,
809
+ })
810
+ }
811
+
812
+ function indexArg(raw, n, fail) {
813
+ const i = Number(raw)
814
+ if (!Number.isInteger(i) || i < 0 || i >= n) fail(`--index must be a payee slot: the contract's 0-based index, 0 to ${n - 1} (gang floor status lists them)`, { got: raw ?? null })
815
+ return i
816
+ }
817
+
818
+ export { capUnits, DEAD }