@gangfun/cli 0.34.0 → 0.35.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/README.md +6 -1
- package/README.zh-CN.md +5 -0
- package/package.json +1 -1
- package/src/capabilities.js +4 -0
- package/src/capped.js +717 -0
- package/src/combo.js +1 -1
- package/src/creatorfee.js +25 -8
- package/src/gangpad.js +16 -5
- package/src/index.js +61 -9
- package/src/launch.js +193 -20
- package/src/mcp.js +4 -4
- package/src/promote.js +3 -3
- package/src/telemetry.js +1 -1
- package/src/v3.js +6 -0
package/src/capped.js
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, maxUint128, maxUint256, 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 { parseAmount, parseNum, revertOf as revertIn, step } from './steps.js'
|
|
5
|
+
import { parseSplitSpec } from './split.js'
|
|
6
|
+
import { COMBO_GAS_NOTE, decodeWorkPlan, kindOf } from './combo.js'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `gang capped …` and `gang create … --tax-cap <amount> [--tax-cap-share <pct>] [--split <addr>:<pct>,…] [--after-cap buyback:<pct>,lp:<pct>]`
|
|
10
|
+
* — GangCappedSplitter (税收封顶, `capped-v1`): one V3 token's tax recipient whose payees' take has a cap fixed for good.
|
|
11
|
+
* Of each payment of the bound quote, `payBps` (--tax-cap-share) is pushed to 1–10 payees at fixed shares until they have
|
|
12
|
+
* been credited `capAmount` (--tax-cap, in `capQuote`'s own decimals) in all — counted when split, pushed or owed alike; the
|
|
13
|
+
* split that crosses the cap pays exactly what is left of it. The rest, and after the cap all of it, is set aside:
|
|
14
|
+
* `buybackOfRestBps` for buy-back-and-burn, the remainder for liquidity whose LP goes to 0xdead (--after-cap). A copy of
|
|
15
|
+
* GangComboSplitter (combo.js): the chunks, the keeper's `work(minOut)` plan and the pushes are its own.
|
|
16
|
+
* EVERYTHING is fixed when it is cloned (the cap, its quote, the ratios, the payees, their shares); a payee can only move
|
|
17
|
+
* its own slot (`setPayee`), which leaves the cap as it is. `bind` takes only a token quoted in `capQuote` (WrongQuote).
|
|
18
|
+
* Any other asset: `distribute(asset)` sends all of it to 0xdead (left in the module when that transfer fails), never to
|
|
19
|
+
* the payees, so a decoy bind can't route the real token's tax around the cap; payees are owed only the bound quote.
|
|
20
|
+
* `initialize` reverts BadQuote unless the keeper serves capQuote (WBNB, the module's GANG, a QuoteRegistry quote): the
|
|
21
|
+
* launch refuses any other quote before the clone (launch.js untrustedBuybackQuote, the rule of every module).
|
|
22
|
+
* The cap covers only this recipient's part of the pool tax: not the creator's share of the curve fee (gang creator-fee),
|
|
23
|
+
* not the dev's own tokens, not the holders' dividend (COVERAGE_NOTE; docs/SPEC-CAPPED-MODULE-2026-11-08.md §2).
|
|
24
|
+
* GangCappedSplitterFactory clones one for the dev (`create(capQuote, capAmount, payBps, buybackOfRestBps, payees,
|
|
25
|
+
* shares, salt)`, at `predict(dev, salt)`) and has GangHandlerAdmin list it (launch.js: clone → create → bind).
|
|
26
|
+
* Gas: as combo's (COMBO_GAS_NOTE). Env: GANG_CAPPED_FACTORY / GANG_TESTNET_CAPPED_FACTORY (gangpad.js).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
// one factory per GangLaunchpad generation: the create target's (GANG_GENS in gangpad.js; null until it is deployed)
|
|
30
|
+
export const MAINNET_CAPPED_FACTORY = GANG_GENS.mainnet[0].cappedFactory ?? null
|
|
31
|
+
export const TESTNET_CAPPED_FACTORY = GANG_GENS.testnet[0].cappedFactory ?? null
|
|
32
|
+
export const CAPPED_TYPE = 'capped-v1'
|
|
33
|
+
const BPS = 10_000
|
|
34
|
+
const CHUNK_GAP_S = 4 * 60
|
|
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 NotCurve()', 'error NotCreator()',
|
|
40
|
+
'error NotRecipient()', 'error NothingOwed()', 'error NothingToChunk()', 'error ChunkTooSoon()', 'error NotTradable()',
|
|
41
|
+
'error Slippage()', 'error PushStarved()', 'error BadCap()', 'error WrongQuote()', 'error BadQuote()',
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
export const CAPPED_FACTORY_ABI = parseAbi([
|
|
45
|
+
'function create(address capQuote, uint256 capAmount, uint16 payBps, uint16 buybackOfRestBps, address[] payees, uint16[] shares, bytes32 salt) returns (address module)',
|
|
46
|
+
'function predict(address dev, bytes32 salt) view returns (address)',
|
|
47
|
+
'function pad() view returns (address)',
|
|
48
|
+
'error NotAgent()', 'error WrongHandler()',
|
|
49
|
+
'event Created(address indexed dev, address indexed module, address indexed capQuote, uint256 capAmount, uint16 payBps, uint16 buybackOfRestBps, address[] payees, uint16[] shares)',
|
|
50
|
+
...ERRORS,
|
|
51
|
+
])
|
|
52
|
+
|
|
53
|
+
export const CAPPED_ABI = parseAbi([
|
|
54
|
+
'function moduleType() view returns (bytes32)',
|
|
55
|
+
'function pad() view returns (address)',
|
|
56
|
+
'function dev() view returns (address)',
|
|
57
|
+
'function token() view returns (address)',
|
|
58
|
+
'function quote() view returns (address)',
|
|
59
|
+
'function pair() view returns (address)',
|
|
60
|
+
'function gangQuote() view returns (address)',
|
|
61
|
+
'function capQuote() view returns (address)',
|
|
62
|
+
'function capAmount() view returns (uint256)',
|
|
63
|
+
'function paidTotal() view returns (uint256)',
|
|
64
|
+
'function payBps() view returns (uint16)',
|
|
65
|
+
'function buybackOfRestBps() view returns (uint16)',
|
|
66
|
+
'function capLeft() view returns (uint256)',
|
|
67
|
+
'function capReached() view returns (bool)',
|
|
68
|
+
'function payeesOf() view returns (address[] payees, uint16[] shares)',
|
|
69
|
+
'function buybackLeft() view returns (uint256)',
|
|
70
|
+
'function lpLeft() view returns (uint256)',
|
|
71
|
+
'function owedOf(address asset, uint256 index) view returns (uint256)',
|
|
72
|
+
'function owedTotal(address asset) view returns (uint256)',
|
|
73
|
+
'function unsplit() view returns (uint256)',
|
|
74
|
+
'function undistributed(address asset) view returns (uint256)',
|
|
75
|
+
'function keeperServes(address q) view returns (bool)',
|
|
76
|
+
'function previewChunk() view returns (bool ready, bool burn, uint256 amount, uint256 tokensOut)',
|
|
77
|
+
'function previewWork() view returns (bool due, uint256 minOut)',
|
|
78
|
+
'function lastChunkAt() view returns (uint64)',
|
|
79
|
+
'function lastPaidAt() view returns (uint64)',
|
|
80
|
+
'function bind(address token)',
|
|
81
|
+
'function split()',
|
|
82
|
+
'function distribute(address asset) returns (uint256 incoming)',
|
|
83
|
+
'function release(address asset, uint256 index, uint256 maxAmount) returns (uint256 amount)',
|
|
84
|
+
'function setPayee(uint256 index, address newPayee)',
|
|
85
|
+
'function chunk(uint256 minTokensOut) returns (bool burn, uint256 quoteIn, uint256 tokensOut, uint256 liquidity)',
|
|
86
|
+
'function work(uint256 minOut)',
|
|
87
|
+
'event Bound(address indexed token, address indexed quote)',
|
|
88
|
+
'event Split(uint256 incoming, uint256 toBuyback, uint256 toLp, uint256 toPayees)',
|
|
89
|
+
'event CapReached(uint256 capAmount)',
|
|
90
|
+
'event Distributed(address indexed asset, uint256 incoming, uint256 toDead)',
|
|
91
|
+
'event PayeeOwed(address indexed asset, uint256 indexed index, uint256 amount)',
|
|
92
|
+
'event PayeeReleased(address indexed asset, uint256 indexed index, uint256 amount)',
|
|
93
|
+
'event PayeeChanged(uint256 indexed index, address indexed oldPayee, address indexed newPayee)',
|
|
94
|
+
'event Shortfall(address indexed asset, uint256 amount)',
|
|
95
|
+
'event BoughtBack(uint256 quoteIn, uint256 burned, uint256 left)',
|
|
96
|
+
'event LiquidityAdded(uint256 quoteIn, uint256 tokensIn, uint256 liquidity, uint256 left)',
|
|
97
|
+
...ERRORS,
|
|
98
|
+
])
|
|
99
|
+
/** gang tx decodes these (the factory's Created and the module's events; Split and the rest share combo's topics). */
|
|
100
|
+
export const CAPPED_EVENT_ABIS = [CAPPED_FACTORY_ABI, CAPPED_ABI]
|
|
101
|
+
|
|
102
|
+
const PAD_ABI = parseAbi([
|
|
103
|
+
'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
|
|
104
|
+
'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)',
|
|
105
|
+
])
|
|
106
|
+
const ERC20_ABI = parseAbi(['function symbol() view returns (string)', 'function decimals() view returns (uint8)'])
|
|
107
|
+
|
|
108
|
+
/** Gas for a call that moves another asset to 0xdead: one transfer, checked like a push. */
|
|
109
|
+
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)'
|
|
110
|
+
|
|
111
|
+
export const HINTS = {
|
|
112
|
+
NotAgent: 'only an Agent can create a V3 token, so only an Agent gets a capped recipient',
|
|
113
|
+
NotFactory: 'this capped factory is not allowed on the platform\'s GangHandlerAdmin: it cannot list a capped recipient as a tax recipient. If GANG_CAPPED_FACTORY / GANG_TESTNET_CAPPED_FACTORY is set, unset or fix it; otherwise launch without --tax-cap',
|
|
114
|
+
BadCap: '--tax-cap must be above 0',
|
|
115
|
+
BadBps: '--tax-cap-share is 0.01–100% of the recipient\'s part, and each --after-cap part 0–100%',
|
|
116
|
+
BadPayees: '1–10 payees (--split), one share each',
|
|
117
|
+
BadShares: 'each payee share at least 0.01% (1 bps) of the payees\' part, all adding up to 100% of it',
|
|
118
|
+
BadPayee: 'a payee cannot be the capped recipient itself',
|
|
119
|
+
DuplicatePayee: 'that address is a payee already (each address holds at most one slot)',
|
|
120
|
+
ZeroAddress: 'the zero address cannot be a payee or the cap\'s quote',
|
|
121
|
+
BadIndex: 'no payee slot with that index (gang capped status lists them, from 0)',
|
|
122
|
+
NotPayee: 'only the current payee of a slot can move it to another address',
|
|
123
|
+
AlreadyBound: 'the capped recipient is bound to a token already',
|
|
124
|
+
NotBound: 'the capped recipient is not bound to a token yet (gang capped bind --token <the token>): nothing is split before that',
|
|
125
|
+
NotCurve: 'not a V3 (curve) token on this pad',
|
|
126
|
+
NotCreator: 'the token was not created by this capped recipient\'s dev',
|
|
127
|
+
NotRecipient: 'the token does not pay its tax to this capped recipient',
|
|
128
|
+
WrongQuote: 'the token\'s quote is not the capped recipient\'s capQuote (the quote its cap is counted in): it can never be bound to this token. A launch with --tax-cap clones it with the launch\'s own quote',
|
|
129
|
+
BadQuote: 'the cap\'s quote must be WBNB, GANG or a quote in the pad\'s QuoteRegistry: a launch with --tax-cap needs one of those as its quote',
|
|
130
|
+
NothingOwed: 'nothing is owed to that slot (payees are only ever owed the bound quote; gang capped status shows what each slot is owed)',
|
|
131
|
+
NothingToChunk: 'nothing is set aside for a buy-back or liquidity chunk yet (buybackLeft / lpLeft): it fills as the tax arrives',
|
|
132
|
+
ChunkTooSoon: 'one chunk (buy-back or liquidity, together) per 4 minutes: wait until 4 minutes after the last one (lastChunkAt)',
|
|
133
|
+
NotTradable: 'the token has not graduated: chunks start once it trades in its PancakeSwap pair',
|
|
134
|
+
Slippage: 'the pool price moved since the preview (fewer tokens than the minimum): run gang capped chunk again',
|
|
135
|
+
PushStarved: `the tx's gas limit was too low for the payee pushes: ${COMBO_GAS_NOTE}`,
|
|
136
|
+
}
|
|
137
|
+
export const revertOf = (e) => revertIn(e, [CAPPED_ABI, CAPPED_FACTORY_ABI], HINTS)
|
|
138
|
+
|
|
139
|
+
/** Dry-run a call; { failed } with the revert when it would not pass. */
|
|
140
|
+
export async function simulateCapped(client, from, address, abi, functionName, args = []) {
|
|
141
|
+
try {
|
|
142
|
+
const { result } = await client.simulateContract({ account: from, address, abi, functionName, args })
|
|
143
|
+
return { result }
|
|
144
|
+
} catch (e) {
|
|
145
|
+
const r = revertOf(e)
|
|
146
|
+
return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The create target's capped factory (a launch clones its capped recipient there), or null when not deployed. */
|
|
151
|
+
export function cappedFactoryAddress(testnet) {
|
|
152
|
+
return gangGens(testnet)[0].cappedFactory || null
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const cappedNotDeployed = (testnet) => (testnet
|
|
156
|
+
? 'GangCappedSplitterFactory (the capped recipient, --tax-cap) is not deployed on the BSC testnet in this CLI version: set GANG_TESTNET_CAPPED_FACTORY to its address, or launch without --tax-cap'
|
|
157
|
+
: 'GangCappedSplitterFactory (the capped recipient, --tax-cap) is not deployed on BSC mainnet in this CLI version: set GANG_CAPPED_FACTORY to its address, or launch without --tax-cap')
|
|
158
|
+
|
|
159
|
+
export const PERMANENT_NOTE = 'PERMANENT: the cap, its quote, the payees\' %, the buy-back / liquidity split, 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 capped set-payee), which leaves the cap as it is'
|
|
160
|
+
export const COVERAGE_NOTE = 'The cap covers only this recipient\'s part of the pool tax. It does not cover the creator\'s share of the curve fee (kept on the pad and claimed apart: gang creator-fee), nor the dev\'s own tokens (it is not a lock: the dev can still hold or sell them), nor the holders\' dividend (fixed at the create, the same before and after the cap)'
|
|
161
|
+
export const OTHER_ASSETS_NOTE = 'any other asset sent to it (not the token\'s quote) cannot count against the cap: all of it goes to 0xdead when it is distributed (gang capped distribute --asset <addr>, anyone), never to the payees; one that cannot be sent there stays in the module'
|
|
162
|
+
|
|
163
|
+
// ---- the launch's flags
|
|
164
|
+
|
|
165
|
+
const PCT_RE = /^(\d{1,3})(?:\.(\d{1,2}))?$/
|
|
166
|
+
const pctBps = (raw) => {
|
|
167
|
+
const m = PCT_RE.exec(String(raw ?? '').trim())
|
|
168
|
+
return m ? Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0')) : null
|
|
169
|
+
}
|
|
170
|
+
const AFTER_USAGE = '--after-cap takes buyback:<pct>,lp:<pct>, adding up to 100 (how what the payees don\'t get is split: buy-back and burn / liquidity), e.g. --after-cap buyback:70,lp:30 or --after-cap lp:100; left out: buyback:100'
|
|
171
|
+
const CAP_SHARE_USAGE = '--tax-cap-share is the payees\' % of the recipient\'s part until the cap: 0.01 to 100, at most 2 decimals (left out: 100)'
|
|
172
|
+
const CAPPED_SPLIT_NOTE = 'with --tax-cap, --split lists the payees of the capped part, their shares adding up to 100 (of that part)'
|
|
173
|
+
|
|
174
|
+
/** --after-cap → { buybackOfRestBps } or { error, … }. Left out: everything to the buy-back. */
|
|
175
|
+
export function parseAfter(raw) {
|
|
176
|
+
if (raw === undefined) return { buybackOfRestBps: BPS }
|
|
177
|
+
const s = String(raw ?? '').trim()
|
|
178
|
+
if (!s || s.startsWith('--')) return { error: AFTER_USAGE, got: raw ?? null }
|
|
179
|
+
const parts = {}
|
|
180
|
+
for (const p of s.split(',').map((x) => x.trim())) {
|
|
181
|
+
const i = p.indexOf(':')
|
|
182
|
+
const key = (i < 0 ? p : p.slice(0, i)).trim().toLowerCase()
|
|
183
|
+
if (i < 0 || !['buyback', 'lp'].includes(key)) return { error: `--after-cap: "${p}" is not buyback:<pct> or lp:<pct>`, hint: AFTER_USAGE }
|
|
184
|
+
if (key in parts) return { error: `--after-cap: ${key} appears twice`, hint: AFTER_USAGE }
|
|
185
|
+
const bps = pctBps(p.slice(i + 1))
|
|
186
|
+
if (bps === null || bps > BPS) return { error: `--after-cap: "${p.slice(i + 1).trim()}" (for ${key}) is not a share in % from 0 to 100 with at most 2 decimals`, hint: AFTER_USAGE }
|
|
187
|
+
parts[key] = bps
|
|
188
|
+
}
|
|
189
|
+
const sum = (parts.buyback ?? 0) + (parts.lp ?? 0)
|
|
190
|
+
if (sum !== BPS) return { error: `--after-cap: the parts add up to ${sum / 100}%, not 100%`, got: raw, hint: AFTER_USAGE }
|
|
191
|
+
return { buybackOfRestBps: parts.buyback ?? 0 }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** --tax-cap-share → { payBps } (1–10,000) or { error }. Left out: 100%. */
|
|
195
|
+
export function parseCapShare(raw) {
|
|
196
|
+
if (raw === undefined) return { payBps: BPS }
|
|
197
|
+
const bps = pctBps(raw)
|
|
198
|
+
if (bps === null || bps < 1 || bps > BPS) return { error: CAP_SHARE_USAGE, got: raw ?? null }
|
|
199
|
+
return { payBps: bps }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* --tax-cap's text → its amount in the quote's smallest unit (`decimals`: the quote's own) or { error }. Without
|
|
204
|
+
* `decimals` (the quote not read yet) only its form is checked: { ok: true }.
|
|
205
|
+
*/
|
|
206
|
+
export function capUnits(text, decimals, symbol) {
|
|
207
|
+
const s = String(text ?? '').trim()
|
|
208
|
+
if (!/^(\d+(\.\d*)?|\.\d+)$/.test(s)) return { error: '--tax-cap must be a positive amount of the token\'s quote (e.g. 20): the most the payees ever get, in all', got: text ?? null }
|
|
209
|
+
const [whole, frac = ''] = s.split('.')
|
|
210
|
+
if (!/[1-9]/.test(s)) return { error: '--tax-cap must be above 0', got: text }
|
|
211
|
+
// no quote has supply anywhere near this: a figure this long is a typo, and above 2^256 it can't be sent at all
|
|
212
|
+
if (whole.replace(/^0+/, '').length > 30) return { error: '--tax-cap is far too large (more than 30 digits before the point): give the cap in whole units of the quote, e.g. 20', got: text }
|
|
213
|
+
if (decimals == null) return { ok: true }
|
|
214
|
+
if (frac.replace(/0+$/, '').length > decimals) return { error: `--tax-cap: ${symbol ?? 'the quote'} has ${decimals} decimals, ${s} has more`, got: text }
|
|
215
|
+
const amount = parseUnits(s, decimals)
|
|
216
|
+
if (amount === 0n) return { error: '--tax-cap must be above 0', got: text }
|
|
217
|
+
if (amount > maxUint256) return { error: '--tax-cap is far too large for this quote', got: text }
|
|
218
|
+
return { amount }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A payee's share (bps of the payees' part) as a % of the recipient's whole part, until the cap. */
|
|
222
|
+
const ofRecipient = (share, payBps) => Math.round((Number(share) * Number(payBps)) / 1e2) / 1e4
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* A capped launch's flags → { payBps, buybackOfRestBps, payees, shares, list } or { error, … }, checked as
|
|
226
|
+
* GangCappedSplitter.initialize checks them. `capShare` / `split` / `after`: the raw flags (undefined when absent); `me`:
|
|
227
|
+
* the creating wallet (`self`, and the only payee by default). The cap itself needs the quote's decimals: capUnits.
|
|
228
|
+
*/
|
|
229
|
+
export function parseCappedSpec({ capShare, split, after } = {}, me) {
|
|
230
|
+
const share = parseCapShare(capShare)
|
|
231
|
+
if (share.error) return share
|
|
232
|
+
const rest = parseAfter(after)
|
|
233
|
+
if (rest.error) return rest
|
|
234
|
+
let spec
|
|
235
|
+
if (split === undefined) {
|
|
236
|
+
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)' }
|
|
237
|
+
spec = { payees: [getAddress(me)], shares: [BPS], list: [{ index: 0, payee: getAddress(me), pct: 100, you: true }] }
|
|
238
|
+
} else {
|
|
239
|
+
spec = parseSplitSpec(split, me)
|
|
240
|
+
if (spec.error) return { ...spec, hint: spec.hint ? `${spec.hint}. ${CAPPED_SPLIT_NOTE}` : CAPPED_SPLIT_NOTE }
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
payBps: share.payBps, buybackOfRestBps: rest.buybackOfRestBps, payees: spec.payees, shares: spec.shares,
|
|
244
|
+
list: spec.list.map(({ pct: p, ...x }) => ({ ...x, pctOfPayees: p, pctOfRecipientUntilCap: ofRecipient(spec.shares[x.index], share.payBps) })),
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ---- the contract's math (pure: unit-tested to the wei)
|
|
249
|
+
|
|
250
|
+
/** _partsOf: how `incoming` of the bound quote splits with `paid` already credited against `capAmount`. */
|
|
251
|
+
export function partsOf(incoming, paid, capAmount, payBps, buybackOfRestBps) {
|
|
252
|
+
let toPayees = (BigInt(incoming) * BigInt(payBps)) / 10_000n
|
|
253
|
+
const left = BigInt(capAmount) - BigInt(paid)
|
|
254
|
+
if (toPayees > left) toPayees = left
|
|
255
|
+
const rest = BigInt(incoming) - toPayees
|
|
256
|
+
const toBuyback = (rest * BigInt(buybackOfRestBps)) / 10_000n
|
|
257
|
+
return { toPayees, toBuyback, toLp: rest - toBuyback }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** _payAll: `amount` to the payees at their shares (bps), the others rounded down, the first the rest. */
|
|
261
|
+
export function payeeAmounts(amount, shares) {
|
|
262
|
+
if (!shares.length) return []
|
|
263
|
+
const a = shares.map((s) => (BigInt(amount) * BigInt(s)) / 10_000n)
|
|
264
|
+
a[0] = BigInt(amount) - a.slice(1).reduce((x, y) => x + y, 0n)
|
|
265
|
+
return a
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The split as % of the recipient's part, until the cap and after it. */
|
|
269
|
+
export function splitPcts(payBps, buybackOfRestBps) {
|
|
270
|
+
const rest = BPS - Number(payBps), bb = Number(buybackOfRestBps)
|
|
271
|
+
const untilBb = ofRecipient(rest, bb)
|
|
272
|
+
return {
|
|
273
|
+
untilCap: { payeesPct: Number(payBps) / 100, buybackPct: untilBb, lpPct: Math.round((rest / 100 - untilBb) * 1e4) / 1e4 },
|
|
274
|
+
afterCap: { payeesPct: 0, buybackPct: bb / 100, lpPct: (BPS - bb) / 100 },
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const fmtNum = (n) => n.toLocaleString('en-US', { maximumSignificantDigits: 4 })
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Roughly how much pool volume reaches the cap (spec §1): cap / ((tax − platform tax) × (1 − dividend) × pay share), in
|
|
282
|
+
* the quote. Buys pay the buy tax and sells the sell tax: different rates give a range. null when nothing goes to payees.
|
|
283
|
+
*/
|
|
284
|
+
export function capVolume({ capAmount, decimals, symbol, buyTaxPct, sellTaxPct, platformTaxPct = 0.5, dividendPct = 0, payBps }) {
|
|
285
|
+
const cap = Number(formatUnits(BigInt(capAmount), decimals))
|
|
286
|
+
const at = (tax) => {
|
|
287
|
+
const f = ((tax - platformTaxPct) / 100) * (1 - dividendPct / 100) * (Number(payBps) / BPS)
|
|
288
|
+
return f > 0 ? cap / f : null
|
|
289
|
+
}
|
|
290
|
+
const hi = Math.max(buyTaxPct, sellTaxPct), lo = Math.min(buyTaxPct, sellTaxPct)
|
|
291
|
+
const [few, many] = [at(hi), at(lo)]
|
|
292
|
+
if (few === null || many === null) return null
|
|
293
|
+
const sym = symbol ?? 'of the quote'
|
|
294
|
+
const how = `cap / ((tax − ${platformTaxPct}% platform) × (1 − ${dividendPct}% dividend) × ${Number(payBps) / 100}% to the payees). An estimate: the tax arrives in chunks sold for the quote, and the cap comes sooner while the holders' part falls back to the recipient (no holder with 10,000+ tokens)`
|
|
295
|
+
return hi === lo
|
|
296
|
+
? { poolVolume: `about ${fmtNum(few)} ${sym}`, how }
|
|
297
|
+
: { poolVolume: `about ${fmtNum(few)} ${sym} (every trade at the ${hi}% tax) to ${fmtNum(many)} ${sym} (every trade at ${lo}%)`, how }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The capped split as one line, for a launch preview and a re-run's refusal. */
|
|
301
|
+
export function cappedLine({ cap, symbol, payBps, buybackOfRestBps, payees, shares }) {
|
|
302
|
+
const p = splitPcts(payBps, buybackOfRestBps)
|
|
303
|
+
const after = `${p.afterCap.buybackPct}% buy-back and burn, ${p.afterCap.lpPct}% liquidity (LP to 0xdead)`
|
|
304
|
+
const who = payees.map((x, i) => `${x}: ${Number(shares[i]) / 100}% of it`).join(', ')
|
|
305
|
+
const until = Number(payBps) === BPS ? `all of it to ${who}` : `${p.untilCap.payeesPct}% to ${who}; the rest ${after}`
|
|
306
|
+
return `until the payees have been credited ${cap} ${symbol ?? 'of the quote'} in all: ${until}. From then on all of it: ${after}`
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** What the capped recipient does with each part, and with any other asset (the preview and status note). */
|
|
310
|
+
export function cappedParts(payBps, buybackOfRestBps) {
|
|
311
|
+
const p = splitPcts(payBps, buybackOfRestBps)
|
|
312
|
+
return {
|
|
313
|
+
untilCap: `${p.untilCap.payeesPct}% of each tax payment to this recipient (in the token's quote) is pushed to the payees at their shares (the first also takes the rounding dust) until they have been credited the cap in all (pushed or owed alike); the split that crosses it pays exactly what is left of it`,
|
|
314
|
+
rest: `the rest, and once the cap is reached all of it, is set aside: ${p.afterCap.buybackPct}% of it bought back in the PancakeSwap pair and the tokens burned (0xdead), ${p.afterCap.lpPct}% added to the pair as liquidity (half buys the token, all of it goes back in with the matching quote), the LP sent to 0xdead (locked for good)`,
|
|
315
|
+
chunks: 'after graduation, one chunk per 4 minutes for both kinds together (always the larger set-aside part), at most 0.5% of the pair\'s quote reserve, none while the price is more than 2% above its 10-minute average',
|
|
316
|
+
otherAssets: OTHER_ASSETS_NOTE,
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The module's state for printing, from the raw reads (pure: unit-tested). `raw`: { module, dev, token, quote, capQuote,
|
|
324
|
+
* capSymbol, capDecimals, capAmount, paidTotal, payBps, buybackOfRestBps, payees, shares, buybackLeft, lpLeft, unsplit,
|
|
325
|
+
* lastChunkAt, lastPaidAt, keeperServesQuote, preview: [ready, burn, amount, tokensOut] | null, work: [due, minOut] | null,
|
|
326
|
+
* graduated: bool | null, assets: [{ asset, symbol, decimals, undistributed, owedTotal, owed: bigint[] | null }], now }.
|
|
327
|
+
* Quote amounts are in the cap quote's decimals (bind takes only that quote), tokens in 18. `ref`: how later commands
|
|
328
|
+
* name it (e.g. `--token 0x… --testnet`).
|
|
329
|
+
*/
|
|
330
|
+
export function formatCapped(raw, ref) {
|
|
331
|
+
const token = raw.token && raw.token !== zeroAddress ? raw.token : null
|
|
332
|
+
const quote = token && raw.quote && raw.quote !== zeroAddress ? raw.quote : null
|
|
333
|
+
const isQuote = (a) => !!quote && a.toLowerCase() === quote.toLowerCase()
|
|
334
|
+
const dec = raw.capDecimals ?? 18
|
|
335
|
+
const fq = (x) => formatUnits(BigInt(x ?? 0n), dec)
|
|
336
|
+
const payBps = Number(raw.payBps), bbBps = Number(raw.buybackOfRestBps)
|
|
337
|
+
const capAmount = BigInt(raw.capAmount), paid = BigInt(raw.paidTotal)
|
|
338
|
+
const left = capAmount - paid
|
|
339
|
+
const reached = left <= 0n
|
|
340
|
+
const progressPct = capAmount > 0n ? Number((paid * 10_000n) / capAmount) / 100 : 0
|
|
341
|
+
const dev = String(raw.dev).toLowerCase()
|
|
342
|
+
const payees = raw.payees.map((payee, index) => ({
|
|
343
|
+
index, payee, pctOfPayees: Number(raw.shares[index]) / 100, pctOfRecipientUntilCap: ofRecipient(raw.shares[index], payBps),
|
|
344
|
+
bps: Number(raw.shares[index]), ...(payee.toLowerCase() === dev && { isDev: true }),
|
|
345
|
+
}))
|
|
346
|
+
const now = Number(raw.now ?? Math.floor(Date.now() / 1000))
|
|
347
|
+
const last = Number(raw.lastChunkAt ?? 0n)
|
|
348
|
+
|
|
349
|
+
// the waiting quote once split (as the contract's _afterSplit, without a shortfall)
|
|
350
|
+
const unsplit = BigInt(raw.unsplit ?? 0n)
|
|
351
|
+
const pending = partsOf(unsplit, paid, capAmount, payBps, bbBps)
|
|
352
|
+
const bbAfter = BigInt(raw.buybackLeft) + pending.toBuyback, lpAfter = BigInt(raw.lpLeft) + pending.toLp
|
|
353
|
+
const kind = kindOf(bbAfter, lpAfter)
|
|
354
|
+
const [ready, burn, amount, tokensOut] = raw.preview ?? [false, false, 0n, 0n]
|
|
355
|
+
let waiting = null
|
|
356
|
+
if (!ready) {
|
|
357
|
+
waiting = !token ? 'not bound to a token yet (gang capped bind --token <the token>)'
|
|
358
|
+
: raw.graduated === false ? 'the token has not graduated: chunks start once it trades in its PancakeSwap pair (the pool tax starts then too)'
|
|
359
|
+
: !kind ? 'nothing set aside for a buy-back or liquidity chunk yet: it fills as the tax arrives'
|
|
360
|
+
: last > 0 && now < last + CHUNK_GAP_S ? `one chunk per 4 minutes (both kinds together): the next from ${iso(last + CHUNK_GAP_S)}`
|
|
361
|
+
: 'the price check: a 10-minute average of the pair\'s price (the next call records it, if none is running) and a price no more than 2% above it'
|
|
362
|
+
}
|
|
363
|
+
const nextChunk = ready
|
|
364
|
+
? burn
|
|
365
|
+
? { kind: 'buy-back', quoteIn: fq(amount), tokensBurned: formatUnits(tokensOut, 18) }
|
|
366
|
+
: { kind: 'liquidity', quoteChunk: fq(amount), buyHalf: fq(BigInt(amount) / 2n), tokensBought: formatUnits(tokensOut, 18) }
|
|
367
|
+
: { kind, ready: false }
|
|
368
|
+
|
|
369
|
+
const next = []
|
|
370
|
+
const assets = []
|
|
371
|
+
for (const a of raw.assets ?? []) {
|
|
372
|
+
const owedTotal = a.owedTotal ?? 0n
|
|
373
|
+
const undistributed = a.undistributed ?? 0n
|
|
374
|
+
if (!isQuote(a.asset) && undistributed === 0n && owedTotal === 0n) continue
|
|
375
|
+
const f = (x) => formatUnits(x, a.decimals ?? 18)
|
|
376
|
+
const owed = owedTotal > 0n && a.owed
|
|
377
|
+
? a.owed.map((x, index) => ({ index, payee: raw.payees[index], amount: f(x) })).filter((_, i) => a.owed[i] > 0n) : []
|
|
378
|
+
const byKeeper = isQuote(a.asset) && raw.keeperServesQuote
|
|
379
|
+
// unlike combo-v1, distributing another asset burns it: say so wherever the command is offered
|
|
380
|
+
const burns = !!token && !isQuote(a.asset) && undistributed > 0n
|
|
381
|
+
assets.push({
|
|
382
|
+
asset: a.asset, symbol: a.symbol ?? null, ...(isQuote(a.asset) && { boundQuote: true }),
|
|
383
|
+
undistributed: f(undistributed), owedTotal: f(owedTotal), ...(owed.length && { owed }),
|
|
384
|
+
splitBy: !token ? 'nobody until bound (distribute reverts NotBound)'
|
|
385
|
+
: byKeeper ? 'the keeper (the quote is one it serves) or anyone: gang capped distribute'
|
|
386
|
+
: isQuote(a.asset) ? 'hand: gang capped distribute (anyone)'
|
|
387
|
+
: 'hand: gang capped distribute (anyone): all of it to 0xdead, never to the payees',
|
|
388
|
+
...(burns && { burns: true }),
|
|
389
|
+
})
|
|
390
|
+
if (token && undistributed > 0n && !byKeeper) {
|
|
391
|
+
next.push(burns
|
|
392
|
+
? `gang capped distribute ${ref} --asset ${a.asset} (BURNS all of it: sends it to 0xdead, paid to nobody; only if that is wanted)`
|
|
393
|
+
: `gang capped distribute ${ref} --asset ${a.asset}`)
|
|
394
|
+
}
|
|
395
|
+
for (const o of owed) next.push(`gang capped release ${ref} --asset ${a.asset} --index ${o.index}`)
|
|
396
|
+
}
|
|
397
|
+
if (!token) next.unshift(String(ref ?? '').startsWith('--token ') ? `gang capped bind ${ref}` : 'gang capped bind --token <the token>')
|
|
398
|
+
if (ready) next.push(`gang capped chunk ${ref}`)
|
|
399
|
+
|
|
400
|
+
const sym = (assets.find((x) => x.boundQuote)?.symbol) || raw.capSymbol || raw.capQuote
|
|
401
|
+
const distribution = !token ? 'unbound' : raw.keeperServesQuote ? 'keeper' : 'manual'
|
|
402
|
+
const keeperLine = distribution === 'unbound'
|
|
403
|
+
? 'Not bound to a token yet: nothing is split, paid, bought back or added until gang capped bind --token <the token>'
|
|
404
|
+
: distribution === 'keeper'
|
|
405
|
+
? `The quote (${sym}) is one the keeper serves: where the keeper runs capped-v1 it does the chunks${reached ? '' : ' and pays the payees (once their part reaches 0.05% of the pair\'s quote reserve, or after a day once it reaches 1/100 of that)'}; anyone can do it at any time (gang capped chunk / gang capped distribute)`
|
|
406
|
+
: `The keeper does not serve this quote (${sym}): everything is manual — gang capped chunk and gang capped distribute (anyone)`
|
|
407
|
+
const capLine = reached
|
|
408
|
+
? `The cap is reached: the payees were credited ${fq(capAmount)} ${sym} in all, and every payment now goes to the buy-back and liquidity`
|
|
409
|
+
: `${fq(paid)} of the ${fq(capAmount)} ${sym} cap credited to the payees so far (${progressPct}%), ${fq(left)} left`
|
|
410
|
+
const [due, minOut] = raw.work ?? [false, 0n]
|
|
411
|
+
const crosses = !reached && unsplit > 0n && pending.toPayees === left
|
|
412
|
+
return {
|
|
413
|
+
module: raw.module, moduleType: CAPPED_TYPE, dev: raw.dev, token, quote, ...(quote && sym && { quoteSymbol: sym }),
|
|
414
|
+
cap: {
|
|
415
|
+
quote: raw.capQuote, symbol: raw.capSymbol ?? null, decimals: dec, amount: fq(capAmount), paid: fq(paid), left: fq(left),
|
|
416
|
+
progressPct, reached, ...(raw.capDecimalsUnread && { decimalsNote: 'the quote\'s decimals could not be read: amounts assume 18' }),
|
|
417
|
+
},
|
|
418
|
+
payPct: payBps / 100, payBps, buybackOfRestBps: bbBps, split: { ...splitPcts(payBps, bbBps), now: reached ? 'afterCap' : 'untilCap' },
|
|
419
|
+
permanent: true, payees,
|
|
420
|
+
buybackLeft: fq(raw.buybackLeft), lpLeft: fq(raw.lpLeft), unsplit: fq(unsplit),
|
|
421
|
+
...(unsplit > 0n && { unsplitGoes: { toPayees: fq(pending.toPayees), toBuyback: fq(pending.toBuyback), toLp: fq(pending.toLp), ...(crosses && { reachesCap: true }) } }),
|
|
422
|
+
nextChunk, ...(waiting && { nextChunkWaitsFor: waiting }),
|
|
423
|
+
lastChunkAt: iso(last), lastPaidAt: iso(raw.lastPaidAt ?? 0n),
|
|
424
|
+
distribution,
|
|
425
|
+
keeper: {
|
|
426
|
+
servesQuote: token ? !!raw.keeperServesQuote : null, due: !!due,
|
|
427
|
+
...(due && { plan: decodeWorkPlan(minOut) }),
|
|
428
|
+
},
|
|
429
|
+
assets,
|
|
430
|
+
...(next.length && { next }),
|
|
431
|
+
parts: cappedParts(payBps, bbBps),
|
|
432
|
+
covers: COVERAGE_NOTE,
|
|
433
|
+
note: `${PERMANENT_NOTE}. ${capLine}. ${keeperLine}. A failed payee push is owed to that slot (it counts against the cap already) and paid with its next push, or by gang capped release`,
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Reads `asset`'s side of the module; null when it is not an ERC20 the module can read. */
|
|
438
|
+
async function assetRaw(read, module, asset, n) {
|
|
439
|
+
let undistributed, owedTotal
|
|
440
|
+
try {
|
|
441
|
+
[undistributed, owedTotal] = await Promise.all([
|
|
442
|
+
read(module, CAPPED_ABI, 'undistributed', [asset]), read(module, CAPPED_ABI, 'owedTotal', [asset]),
|
|
443
|
+
])
|
|
444
|
+
} catch { return null }
|
|
445
|
+
const [symbol, decimals, owed] = await Promise.all([
|
|
446
|
+
read(asset, ERC20_ABI, 'symbol').catch(() => null),
|
|
447
|
+
read(asset, ERC20_ABI, 'decimals').then(Number).catch(() => 18),
|
|
448
|
+
owedTotal > 0n ? Promise.all(Array.from({ length: n }, (_, i) => read(module, CAPPED_ABI, 'owedOf', [asset, BigInt(i)]))) : null,
|
|
449
|
+
])
|
|
450
|
+
return { asset, symbol, decimals, undistributed, owedTotal, owed }
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** The quote's symbol and decimals (its own, never assumed); decimals null when unread. */
|
|
454
|
+
export async function quoteUnits(read, quote) {
|
|
455
|
+
const [symbol, decimals] = await Promise.all([
|
|
456
|
+
read(quote, ERC20_ABI, 'symbol').catch(() => null),
|
|
457
|
+
read(quote, ERC20_ABI, 'decimals').then(Number).catch(() => null),
|
|
458
|
+
])
|
|
459
|
+
return { symbol, decimals }
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* The module's state when `addr` is a GangCappedSplitter (capped-v1); null when it is not. Assets read: the bound quote,
|
|
464
|
+
* the cap's quote, WBNB, the module's GANG and `extraAssets` (e.g. the quote of a token paying it that is not the bound
|
|
465
|
+
* one). `pad`: to read graduation.
|
|
466
|
+
*/
|
|
467
|
+
export async function cappedOf(read, addr, { wbnb, pad, extraAssets = [], ref } = {}) {
|
|
468
|
+
if (!addr || addr === zeroAddress) return null
|
|
469
|
+
let type
|
|
470
|
+
try { type = await read(addr, CAPPED_ABI, 'moduleType') } catch { return null }
|
|
471
|
+
if (hexToString(type, { size: 32 }).replace(/\0+$/, '') !== CAPPED_TYPE) return null
|
|
472
|
+
const FIELDS = ['dev', 'token', 'quote', 'capQuote', 'capAmount', 'paidTotal', 'payBps', 'buybackOfRestBps', 'payeesOf', 'buybackLeft', 'lpLeft', 'unsplit', 'lastChunkAt', 'lastPaidAt']
|
|
473
|
+
const [vals, gangQuote] = await Promise.all([
|
|
474
|
+
Promise.all(FIELDS.map((f) => read(addr, CAPPED_ABI, f))),
|
|
475
|
+
read(addr, CAPPED_ABI, 'gangQuote').catch(() => zeroAddress),
|
|
476
|
+
])
|
|
477
|
+
const r = Object.fromEntries(FIELDS.map((f, i) => [f, vals[i]]))
|
|
478
|
+
const [payees, shares] = r.payeesOf
|
|
479
|
+
const bound = r.token !== zeroAddress
|
|
480
|
+
const [preview, work, keeperServesQuote, graduated, units] = await Promise.all([
|
|
481
|
+
bound ? read(addr, CAPPED_ABI, 'previewChunk').catch(() => null) : null,
|
|
482
|
+
bound ? read(addr, CAPPED_ABI, 'previewWork').catch(() => null) : null,
|
|
483
|
+
bound ? read(addr, CAPPED_ABI, 'keeperServes', [r.quote]).catch(() => false) : false,
|
|
484
|
+
bound && pad ? read(pad, PAD_ABI, 'curves', [r.token]).then((c) => c[6]).catch(() => null) : null,
|
|
485
|
+
quoteUnits(read, r.capQuote),
|
|
486
|
+
])
|
|
487
|
+
const seen = new Set()
|
|
488
|
+
const list = [r.quote, r.capQuote, wbnb, gangQuote, ...extraAssets].filter((a) => {
|
|
489
|
+
if (!a || a === zeroAddress || seen.has(a.toLowerCase())) return false
|
|
490
|
+
seen.add(a.toLowerCase())
|
|
491
|
+
return true
|
|
492
|
+
})
|
|
493
|
+
const assets = (await Promise.all(list.map((a) => assetRaw(read, addr, a, payees.length)))).filter(Boolean)
|
|
494
|
+
return formatCapped({
|
|
495
|
+
module: addr, dev: r.dev, token: r.token, quote: r.quote, capQuote: r.capQuote, capSymbol: units.symbol,
|
|
496
|
+
capDecimals: units.decimals ?? 18, ...(units.decimals === null && { capDecimalsUnread: true }),
|
|
497
|
+
capAmount: r.capAmount, paidTotal: r.paidTotal, payBps: r.payBps, buybackOfRestBps: r.buybackOfRestBps, payees, shares,
|
|
498
|
+
buybackLeft: r.buybackLeft, lpLeft: r.lpLeft, unsplit: r.unsplit, lastChunkAt: r.lastChunkAt, lastPaidAt: r.lastPaidAt,
|
|
499
|
+
keeperServesQuote, preview, work, graduated, assets,
|
|
500
|
+
}, ref ?? (bound ? `--token ${r.token}` : `--module ${addr}`))
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* When `token` pays its tax to the capped recipient but the module is bound to another token (a decoy bind): what to say.
|
|
505
|
+
* The same quote is split under the one cap, its buy-backs going to the other pair; another quote is all burned.
|
|
506
|
+
*/
|
|
507
|
+
export function decoyWarning(s, token, tokenQuote, ref) {
|
|
508
|
+
if (!token || !s.token || s.token.toLowerCase() === token.toLowerCase()) return null
|
|
509
|
+
const sameQuote = !!tokenQuote && !!s.quote && tokenQuote.toLowerCase() === s.quote.toLowerCase()
|
|
510
|
+
return sameQuote
|
|
511
|
+
? `this token pays its tax to the capped recipient, but it is bound to another token (${s.token}): this token's tax, in the same quote, is split with that token's under the one cap, and its buy-backs and liquidity go to that token's pair, not this one's`
|
|
512
|
+
: `this token pays its tax to the capped recipient, but it is bound to another token (${s.token}): this token's tax (${tokenQuote ?? 'its quote'}) is not the bound quote, so it never reaches the payees, the buy-back or the liquidity — all of it goes to 0xdead (gang capped distribute ${ref} --asset ${tokenQuote ?? '<its quote>'})`
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function cappedCtx(testnet) {
|
|
516
|
+
const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
|
|
517
|
+
if (!net.pad) throw new Error(NOT_ON_MAINNET)
|
|
518
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
519
|
+
return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const SUBS = ['status', 'distribute', 'release', 'set-payee', 'bind', 'chunk']
|
|
523
|
+
const USAGE = 'usage: gang capped <status|distribute|release|set-payee|bind|chunk> --token <addr> (or --module <addr>) [--asset <addr>|wbnb] [--index <i>] [--to <addr>] [--max <amount>] [--slippage 1] [--testnet] — see gang help'
|
|
524
|
+
|
|
525
|
+
/** `gang capped <sub>`: the capped recipient of a V3 token (its tax recipient), found from --token (or named by --module). */
|
|
526
|
+
export async function runCapped(sub, { opt, flag, out, fail, summarize }) {
|
|
527
|
+
if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
|
|
528
|
+
const testnet = flag('testnet')
|
|
529
|
+
const rawOnly = flag('calldata')
|
|
530
|
+
let ctx
|
|
531
|
+
try { ctx = cappedCtx(testnet) } catch (e) { return fail(e.message) }
|
|
532
|
+
const chainId = Number(ctx.chainId)
|
|
533
|
+
const tn = testnet ? ' --testnet' : ''
|
|
534
|
+
if (flag('token') && flag('module')) fail('give --token (its tax recipient is the capped recipient) or --module, not both')
|
|
535
|
+
let token = null, module, tokenQuote = null, padKnown = true
|
|
536
|
+
if (flag('module')) {
|
|
537
|
+
if (sub === 'bind') fail('gang capped bind needs --token <the token> (it binds the token\'s own recipient)')
|
|
538
|
+
module = opt('module')
|
|
539
|
+
if (!isAddress(module ?? '')) fail('--module must be a capped recipient address (0x…)', { got: module ?? null })
|
|
540
|
+
// the module's own generation: any other pad answers curves() of its token with zeros, which reads as "not graduated"
|
|
541
|
+
const pad = await ctx.read(module, CAPPED_ABI, 'pad').catch(() => null)
|
|
542
|
+
padKnown = !!pad && atPad(ctx, pad, testnet)
|
|
543
|
+
} else {
|
|
544
|
+
token = opt('token')
|
|
545
|
+
if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…), or name the module with --module <addr>', { got: token ?? null })
|
|
546
|
+
if ((await atTokenPad(ctx, token)) === null) return fail(KIND_UNREAD.error, { token, retry: KIND_UNREAD.retry }) // else on the pad of the token's generation
|
|
547
|
+
try {
|
|
548
|
+
const [creator, quote] = await ctx.read(ctx.pad, PAD_ABI, 'curves', [token])
|
|
549
|
+
if (creator === zeroAddress) throw new Error('not a curve')
|
|
550
|
+
tokenQuote = quote
|
|
551
|
+
module = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3]
|
|
552
|
+
} catch {
|
|
553
|
+
return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet; add --testnet for a testnet token'})`, { token, chainId })
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const ref = `${token ? `--token ${token}` : `--module ${module}`}${tn}`
|
|
557
|
+
// status --asset <addr>: read that asset too (a stray one the default list doesn't cover)
|
|
558
|
+
const extra = sub === 'status' && flag('asset') && isAddress(opt('asset') ?? '') ? [getAddress(opt('asset'))] : []
|
|
559
|
+
const s = await cappedOf(ctx.read, module, {
|
|
560
|
+
wbnb: ctx.wbnb, pad: padKnown ? ctx.pad : null, extraAssets: [...(tokenQuote && tokenQuote !== zeroAddress ? [tokenQuote] : []), ...extra], ref,
|
|
561
|
+
})
|
|
562
|
+
if (!s) {
|
|
563
|
+
return fail(token ? 'this token\'s tax recipient is not a capped recipient (capped-v1)' : 'not a capped recipient (capped-v1)',
|
|
564
|
+
{ ...(token && { token }), recipient: module === zeroAddress ? null : module })
|
|
565
|
+
}
|
|
566
|
+
const warning = decoyWarning(s, token, tokenQuote, ref)
|
|
567
|
+
const me = () => walletFor(ctx, opt('from'))
|
|
568
|
+
const send = async (functionName, args, extra) => {
|
|
569
|
+
const sim = await simulateCapped(ctx.client, me(), s.module, CAPPED_ABI, functionName, args)
|
|
570
|
+
if (sim.failed) return out({ success: false, step: extra.step, ...sim.failed, ...(warning && { warning }) })
|
|
571
|
+
const data = encodeFunctionData({ abi: CAPPED_ABI, functionName, args })
|
|
572
|
+
// no gas field: the wallet / node estimates it (COMBO_GAS_NOTE)
|
|
573
|
+
return out(step(ctx, { from: me(), to: s.module, data }, { chainId, ...(token && { token }), module: s.module, ...extra, ...(warning && { warning }) }, rawOnly, summarize))
|
|
574
|
+
}
|
|
575
|
+
const assetArg = (def) => {
|
|
576
|
+
if (!flag('asset')) return def
|
|
577
|
+
const a = opt('asset')
|
|
578
|
+
if (/^wbnb$/i.test(a ?? '')) return ctx.wbnb
|
|
579
|
+
if (!isAddress(a ?? '') || a === zeroAddress) fail('--asset must be a token address (0x…, checksummed or all lowercase) or wbnb', { got: a ?? null })
|
|
580
|
+
return getAddress(a)
|
|
581
|
+
}
|
|
582
|
+
const assetState = async (asset) => {
|
|
583
|
+
const known = s.assets.find((x) => x.asset.toLowerCase() === asset.toLowerCase())
|
|
584
|
+
const r = await assetRaw(ctx.read, s.module, asset, s.payees.length)
|
|
585
|
+
if (!r) fail('the module cannot read that asset\'s balance (not an ERC20?)', { asset })
|
|
586
|
+
return { ...r, symbol: r.symbol ?? known?.symbol ?? null, f: (x) => formatUnits(x, r.decimals) }
|
|
587
|
+
}
|
|
588
|
+
const needBound = () => {
|
|
589
|
+
if (!s.token) fail(HINTS.NotBound, { module: s.module, ...(token && { next: `gang capped bind --token ${token}${tn}` }) })
|
|
590
|
+
}
|
|
591
|
+
const fq = (x) => formatUnits(x, s.cap.decimals)
|
|
592
|
+
const sym = s.quoteSymbol ?? s.cap.symbol ?? 'of the quote'
|
|
593
|
+
|
|
594
|
+
if (sub === 'status') return out({ success: true, chainId, ...s, ...(s.token === null && { bound: false }), ...(warning && { warning }) })
|
|
595
|
+
|
|
596
|
+
if (sub === 'bind') {
|
|
597
|
+
if (s.token) return fail('already bound', { boundTo: s.token, ...(warning && { warning }) })
|
|
598
|
+
if (tokenQuote && tokenQuote.toLowerCase() !== String(s.cap.quote).toLowerCase()) {
|
|
599
|
+
return fail(HINTS.WrongQuote, { token, tokenQuote, capQuote: s.cap.quote })
|
|
600
|
+
}
|
|
601
|
+
return send('bind', [token], { step: 'bind', note: `anyone may bind (once); the token must be the dev's, pay its tax to this module and be quoted in the cap's quote (${s.cap.symbol ?? s.cap.quote}). It decides which pair the buy-backs and liquidity go to` })
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
if (sub === 'distribute') {
|
|
605
|
+
needBound()
|
|
606
|
+
const asset = assetArg(s.quote)
|
|
607
|
+
const a = await assetState(asset)
|
|
608
|
+
if (a.undistributed === 0n) {
|
|
609
|
+
return fail('nothing of this asset is waiting to be split', {
|
|
610
|
+
asset, symbol: a.symbol, owedTotal: a.f(a.owedTotal),
|
|
611
|
+
...(a.owedTotal > 0n && { hint: `what is held is owed to payees after failed pushes: gang capped release ${ref} --index <i>` }),
|
|
612
|
+
})
|
|
613
|
+
}
|
|
614
|
+
if (asset.toLowerCase() === s.quote.toLowerCase()) {
|
|
615
|
+
// the split as the contract makes it: the payees' part capped by what is left of the cap
|
|
616
|
+
const [paid, capAmount] = await Promise.all([ctx.read(s.module, CAPPED_ABI, 'paidTotal'), ctx.read(s.module, CAPPED_ABI, 'capAmount')])
|
|
617
|
+
const p = partsOf(a.undistributed, paid, capAmount, s.payBps, s.buybackOfRestBps)
|
|
618
|
+
const reachesCap = paid < capAmount && paid + p.toPayees === capAmount
|
|
619
|
+
const amounts = payeeAmounts(p.toPayees, s.payees.map((x) => x.bps))
|
|
620
|
+
return send('distribute', [asset], {
|
|
621
|
+
step: 'distribute', asset, symbol: a.symbol, boundQuote: true, amount: fq(a.undistributed),
|
|
622
|
+
toPayees: fq(p.toPayees), toBuyback: fq(p.toBuyback), toLp: fq(p.toLp),
|
|
623
|
+
parts: s.payees.map((x, i) => ({ index: x.index, payee: x.payee, pctOfPayees: x.pctOfPayees, gets: fq(amounts[i]) })),
|
|
624
|
+
cap: { amount: fq(capAmount), paidBefore: fq(paid), paidAfter: fq(paid + p.toPayees), leftAfter: fq(capAmount - paid - p.toPayees), ...(reachesCap && { reachesCap: true }) },
|
|
625
|
+
note: `anyone may: splits the bound quote that arrived (as split()): ${s.payPct}% to the payees, but never more than what is left of the cap (${fq(capAmount - paid)} ${sym}), pushed now; the rest set aside, ${s.split.afterCap.buybackPct}% of it for buy-back and ${s.split.afterCap.lpPct}% for liquidity${reachesCap ? '. This split reaches the cap: from then on all of it goes to the buy-back and liquidity' : paid >= capAmount ? ' (the cap is reached: nothing goes to the payees)' : ''}; a push that fails is owed to that slot and counts against the cap. Gas: ${COMBO_GAS_NOTE}`,
|
|
626
|
+
})
|
|
627
|
+
}
|
|
628
|
+
return send('distribute', [asset], {
|
|
629
|
+
step: 'distribute', asset, symbol: a.symbol, amount: a.f(a.undistributed), toDead: a.f(a.undistributed), toPayees: a.f(0n),
|
|
630
|
+
note: `anyone may: this is not the bound quote, so it cannot count against the cap: all of it goes to 0xdead, none to the payees (when it cannot be sent there it stays in the module). Gas: ${DEAD_GAS_NOTE}`,
|
|
631
|
+
})
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
if (sub === 'release') {
|
|
635
|
+
needBound()
|
|
636
|
+
const asset = assetArg(s.quote)
|
|
637
|
+
if (asset.toLowerCase() !== s.quote.toLowerCase()) {
|
|
638
|
+
return fail('payees are only ever owed the bound quote: any other asset goes to 0xdead, never to a payee (gang capped distribute --asset)', { asset, boundQuote: s.quote })
|
|
639
|
+
}
|
|
640
|
+
const a = await assetState(asset)
|
|
641
|
+
let index
|
|
642
|
+
if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
|
|
643
|
+
else {
|
|
644
|
+
const mine = s.payees.find((p) => p.payee.toLowerCase() === String(me()).toLowerCase())
|
|
645
|
+
const owedSlots = (a.owed ?? []).map((x, i) => (x > 0n ? i : -1)).filter((i) => i >= 0)
|
|
646
|
+
if (mine) index = mine.index
|
|
647
|
+
else if (owedSlots.length === 1) index = owedSlots[0]
|
|
648
|
+
else fail('--index <i> required: which payee slot to pay (gang capped status lists what each is owed)', { owedSlots })
|
|
649
|
+
}
|
|
650
|
+
const owed = a.owed ? a.owed[index] : 0n
|
|
651
|
+
if (owed === 0n) return fail(HINTS.NothingOwed, { asset, symbol: a.symbol, index, payee: s.payees[index].payee })
|
|
652
|
+
let max = maxUint256
|
|
653
|
+
if (flag('max')) max = parseUnits(parseAmount(fail, 'max', opt('max')), a.decimals)
|
|
654
|
+
const amount = owed < max ? owed : max
|
|
655
|
+
return send('release', [asset, BigInt(index), max], {
|
|
656
|
+
step: 'release', asset, symbol: a.symbol, index, payee: s.payees[index].payee, amount: a.f(amount), owed: a.f(owed),
|
|
657
|
+
note: `anyone may: splits what newly arrived of the bound quote 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; nothing owed is lost). Gas: ${COMBO_GAS_NOTE}`,
|
|
658
|
+
})
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
if (sub === 'chunk') {
|
|
662
|
+
needBound()
|
|
663
|
+
const slippage = parseNum(fail, 'slippage', opt('slippage', '1'), 0, 50)
|
|
664
|
+
const [ready, burn, amount, tokensOut] = await ctx.read(s.module, CAPPED_ABI, 'previewChunk')
|
|
665
|
+
if (ready) {
|
|
666
|
+
// previewChunk prices the buy (a liquidity chunk: its half) after the buy tax; the contract scales the minimum
|
|
667
|
+
// down when the pair got less
|
|
668
|
+
const minOut = (tokensOut * BigInt(Math.round((100 - slippage) * 100))) / 10_000n
|
|
669
|
+
return send('chunk', [minOut], burn
|
|
670
|
+
? {
|
|
671
|
+
step: 'chunk', kind: 'buy-back', quoteIn: fq(amount), expectTokensBurned: formatUnits(tokensOut, 18),
|
|
672
|
+
minTokens: formatUnits(minOut, 18), slippagePct: slippage, buybackLeft: s.buybackLeft, lpLeft: s.lpLeft,
|
|
673
|
+
note: `anyone may: splits what arrived, then one buy-back chunk (the larger set-aside part): buys the token in the pair and burns it at 0xdead (gang tx shows BoughtBack). The keeper does the same every few minutes. Gas: ${COMBO_GAS_NOTE}`,
|
|
674
|
+
}
|
|
675
|
+
: {
|
|
676
|
+
step: 'chunk', kind: 'liquidity', quoteChunk: fq(amount), buyHalf: fq(amount / 2n), expectTokensBought: formatUnits(tokensOut, 18),
|
|
677
|
+
minTokens: formatUnits(minOut, 18), slippagePct: slippage, buybackLeft: s.buybackLeft, lpLeft: s.lpLeft,
|
|
678
|
+
note: `anyone may: splits what arrived, then one liquidity chunk (the larger set-aside part): half buys the token, all of it goes back into the pair with the matching quote, the LP to 0xdead (gang tx shows LiquidityAdded). The keeper does the same every few minutes. Gas: ${COMBO_GAS_NOTE}`,
|
|
679
|
+
})
|
|
680
|
+
}
|
|
681
|
+
// not ready: only a call that records the price observation can pass; a minimum no chunk can meet makes it revert
|
|
682
|
+
// (Slippage) rather than trade unchecked if a chunk became possible before it lands
|
|
683
|
+
const sim = await simulateCapped(ctx.client, me(), s.module, CAPPED_ABI, 'chunk', [maxUint128])
|
|
684
|
+
if (sim.failed) return out({ success: false, step: 'chunk', ...sim.failed, ...(s.nextChunkWaitsFor && { waitsFor: s.nextChunkWaitsFor }), buybackLeft: s.buybackLeft, lpLeft: s.lpLeft, ...(warning && { warning }) })
|
|
685
|
+
return send('chunk', [maxUint128], {
|
|
686
|
+
step: 'record-price', trades: false, waitsFor: s.nextChunkWaitsFor,
|
|
687
|
+
note: 'no chunk this time: the call splits what arrived and records the pair\'s price observation (or waits for the 10-minute average / a price no more than 2% above it). The keeper calls it too. If a chunk becomes possible before it lands, it reverts (Slippage) rather than trade without a minimum: run gang capped chunk again then, about 10 minutes after the first observation',
|
|
688
|
+
})
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// set-payee: only the slot's own payee; the index is the wallet's own slot unless given. Unlike combo-v1 nothing else
|
|
692
|
+
// needs distributing first: other assets never go to payees, and the contract splits the bound quote before the move
|
|
693
|
+
const wallet = String(me()).toLowerCase()
|
|
694
|
+
const mine = s.payees.find((p) => p.payee.toLowerCase() === wallet)
|
|
695
|
+
let index
|
|
696
|
+
if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
|
|
697
|
+
else if (mine) index = mine.index
|
|
698
|
+
else return fail('this wallet is not a payee of this capped recipient: only a slot\'s own payee can move it', { wallet: me(), payees: s.payees.map((p) => p.payee) })
|
|
699
|
+
const slot = s.payees[index]
|
|
700
|
+
if (slot.payee.toLowerCase() !== wallet) return fail(HINTS.NotPayee, { index, payee: slot.payee, wallet: me() })
|
|
701
|
+
const to = opt('to')
|
|
702
|
+
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 })
|
|
703
|
+
if (to.toLowerCase() === s.module.toLowerCase()) return fail(HINTS.BadPayee, { to })
|
|
704
|
+
const taken = s.payees.find((p) => p.payee.toLowerCase() === to.toLowerCase())
|
|
705
|
+
if (taken) return fail(taken.index === index ? 'that is this slot\'s payee already' : HINTS.DuplicatePayee, { to, index: taken.index })
|
|
706
|
+
return send('setPayee', [BigInt(index), getAddress(to)], {
|
|
707
|
+
step: 'set-payee', index, pctOfPayees: slot.pctOfPayees, fromPayee: slot.payee, toPayee: getAddress(to),
|
|
708
|
+
...(s.cap.reached && { capReached: true }),
|
|
709
|
+
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 is split first (to the current address); what this slot is owed goes to the new one. Gas: ${COMBO_GAS_NOTE}`,
|
|
710
|
+
})
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function indexArg(raw, n, fail) {
|
|
714
|
+
const i = Number(raw)
|
|
715
|
+
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 capped status lists them)`, { got: raw ?? null })
|
|
716
|
+
return i
|
|
717
|
+
}
|