@gangfun/cli 0.18.2 → 0.19.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 +12 -7
- package/README.zh-CN.md +12 -7
- package/package.json +4 -1
- package/src/discover.js +7 -9
- package/src/fly.js +12 -12
- package/src/index.js +62 -27
- package/src/launch.js +112 -21
- package/src/mcp.js +10 -10
- package/src/portfolio.js +3 -3
- package/src/split.js +429 -0
- package/src/steps.js +1 -1
- package/src/v3.js +10 -1
package/src/split.js
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, maxUint256, parseUnits, zeroAddress } from 'viem'
|
|
2
|
+
import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
3
|
+
import { walletFor } from './fair.js'
|
|
4
|
+
import { parseAmount, revertOf as revertIn, step } from './steps.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `gang split …` and `gang create … --split <addr>:<pct>[,…]` — GangSplitModule (多人分账, `split-v1`): a V3 token's tax
|
|
8
|
+
* recipient that splits everything it receives among 1–10 payees at shares fixed when it is cloned (summing to 100%).
|
|
9
|
+
* Nobody — not the dev, not the platform — can change the payees or the shares; a payee can only move its own slot to
|
|
10
|
+
* another address (`setPayee`). GangSplitModuleFactory clones one for the dev (`create(payees, shares, salt)`, at
|
|
11
|
+
* `predict(dev, salt)`) and has GangHandlerAdmin list it, so the dev names it as the recipient at create (launch.js does
|
|
12
|
+
* the three steps: clone → create → bind, as for --buyback).
|
|
13
|
+
* Every asset that reaches the module is split at the same shares (`distribute(asset)`, anyone); the keeper splits only
|
|
14
|
+
* the bound quote, and only when it serves that quote (`keeperServes`: WBNB, GANG, a QuoteRegistry quote).
|
|
15
|
+
* Gas: each payee's push needs about 365k gas left before it (PUSH_GAS 300k × 64/63 + a 60k reserve), so a split needs a
|
|
16
|
+
* gas limit far above the gas it uses. The CLI never sets or lowers one: the wallet / node estimates it (eth_estimateGas
|
|
17
|
+
* searches for a limit that passes); a lower limit reverts PushStarved, and nothing moves.
|
|
18
|
+
* Env: GANG_SPLIT_FACTORY / GANG_TESTNET_SPLIT_FACTORY override the built-in factory addresses.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
// BSC 56: deployed 2026-10-30, allowed on GangHandlerAdmin by the platform's Safe the same day (docs/MAINNET-SPLIT-MODULE-2026-10-30.md)
|
|
22
|
+
export const MAINNET_SPLIT_FACTORY = '0x27e08271E52B2D129c824CD245e69471a8d3067c'
|
|
23
|
+
// BSC 97, set 10 (docs/TESTNET-SPLIT-MODULE-2026-10-30.md)
|
|
24
|
+
export const TESTNET_SPLIT_FACTORY = '0x5F7dC7502E945A860Cf49cca72dA8bD60Fb1567E'
|
|
25
|
+
export const SPLIT_TYPE = 'split-v1'
|
|
26
|
+
export const MAX_PAYEES = 10
|
|
27
|
+
const BPS = 10_000
|
|
28
|
+
|
|
29
|
+
const ERRORS = [
|
|
30
|
+
'error ZeroAddress()', 'error NotClone()', 'error NotFactory()', 'error AlreadyInitialized()', 'error BadPayees()',
|
|
31
|
+
'error BadShares()', 'error BadPayee()', 'error DuplicatePayee()', 'error BadIndex()', 'error NotPayee()',
|
|
32
|
+
'error AlreadyBound()', 'error NotCurve()', 'error NotCreator()', 'error NotRecipient()', 'error NothingOwed()',
|
|
33
|
+
'error PushStarved()',
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
export const SPLIT_FACTORY_ABI = parseAbi([
|
|
37
|
+
'function create(address[] payees, uint16[] shares, bytes32 salt) returns (address module)',
|
|
38
|
+
'function predict(address dev, bytes32 salt) view returns (address)',
|
|
39
|
+
'function pad() view returns (address)',
|
|
40
|
+
'error NotAgent()', 'error WrongHandler()',
|
|
41
|
+
'event Created(address indexed dev, address indexed module, address[] payees, uint16[] shares)',
|
|
42
|
+
...ERRORS,
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
export const SPLIT_ABI = parseAbi([
|
|
46
|
+
'function moduleType() view returns (bytes32)',
|
|
47
|
+
'function dev() view returns (address)',
|
|
48
|
+
'function token() view returns (address)',
|
|
49
|
+
'function quote() view returns (address)',
|
|
50
|
+
'function gangQuote() view returns (address)',
|
|
51
|
+
'function payeesOf() view returns (address[] payees, uint16[] shares)',
|
|
52
|
+
'function payeeCount() view returns (uint256)',
|
|
53
|
+
'function owedOf(address asset, uint256 index) view returns (uint256)',
|
|
54
|
+
'function owedTotal(address asset) view returns (uint256)',
|
|
55
|
+
'function undistributed(address asset) view returns (uint256)',
|
|
56
|
+
'function keeperServes(address q) view returns (bool)',
|
|
57
|
+
'function previewWork() view returns (bool due, uint256 minOut)',
|
|
58
|
+
'function lastDistributedAt() view returns (uint64)',
|
|
59
|
+
'function bind(address token)',
|
|
60
|
+
'function distribute(address asset) returns (uint256 incoming)',
|
|
61
|
+
'function release(address asset, uint256 index, uint256 maxAmount) returns (uint256 amount)',
|
|
62
|
+
'function setPayee(uint256 index, address newPayee)',
|
|
63
|
+
'event Bound(address indexed token, address indexed quote)',
|
|
64
|
+
'event Distributed(address indexed asset, uint256 incoming)',
|
|
65
|
+
'event PayeeOwed(address indexed asset, uint256 indexed index, uint256 amount)',
|
|
66
|
+
'event PayeeReleased(address indexed asset, uint256 indexed index, uint256 amount)',
|
|
67
|
+
'event PayeeChanged(uint256 indexed index, address indexed oldPayee, address indexed newPayee)',
|
|
68
|
+
'event Shortfall(address indexed asset, uint256 amount)',
|
|
69
|
+
...ERRORS,
|
|
70
|
+
])
|
|
71
|
+
/** gang tx decodes these (the factory's Created and the module's events). */
|
|
72
|
+
export const SPLIT_EVENT_ABIS = [SPLIT_FACTORY_ABI, SPLIT_ABI]
|
|
73
|
+
|
|
74
|
+
const PAD_ABI = parseAbi([
|
|
75
|
+
'function taxConfigOf(address token) view returns (uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)',
|
|
76
|
+
'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)',
|
|
77
|
+
])
|
|
78
|
+
const ERC20_ABI = parseAbi(['function symbol() view returns (string)', 'function decimals() view returns (uint8)'])
|
|
79
|
+
|
|
80
|
+
export const GAS_NOTE = 'let the wallet estimate the gas limit (eth_estimateGas) and do not lower it: each payee\'s push needs about 365k gas left before it, so the limit is far above the gas used; a lower limit reverts PushStarved (nothing moves)'
|
|
81
|
+
|
|
82
|
+
export const HINTS = {
|
|
83
|
+
NotAgent: 'only an Agent can create a V3 token, so only an Agent gets a split module',
|
|
84
|
+
NotFactory: 'this split factory is not allowed on the platform\'s GangHandlerAdmin: it cannot list a split module as a tax recipient. If GANG_SPLIT_FACTORY / GANG_TESTNET_SPLIT_FACTORY is set, unset it to use the built-in factory; otherwise launch without --split',
|
|
85
|
+
BadPayees: '1–10 payees, one share each',
|
|
86
|
+
BadShares: 'each share at least 0.01% (1 bps), all adding up to 100%',
|
|
87
|
+
BadPayee: 'a payee cannot be the split module itself',
|
|
88
|
+
DuplicatePayee: 'that address is a payee already (each address holds at most one slot)',
|
|
89
|
+
ZeroAddress: 'the zero address cannot be a payee',
|
|
90
|
+
BadIndex: 'no payee slot with that index (gang split status lists them, from 0)',
|
|
91
|
+
NotPayee: 'only the current payee of a slot can move it to another address',
|
|
92
|
+
AlreadyBound: 'the module is bound to a token already',
|
|
93
|
+
NotCurve: 'not a V3 (curve) token on this pad',
|
|
94
|
+
NotCreator: 'the token was not created by this module\'s dev',
|
|
95
|
+
NotRecipient: 'the token does not pay its tax to this module',
|
|
96
|
+
NothingOwed: 'nothing is owed to that slot in this asset (gang split status shows what each slot is owed)',
|
|
97
|
+
PushStarved: `the tx's gas limit was too low for the split: ${GAS_NOTE}`,
|
|
98
|
+
}
|
|
99
|
+
export const revertOf = (e) => revertIn(e, [SPLIT_ABI, SPLIT_FACTORY_ABI], HINTS)
|
|
100
|
+
|
|
101
|
+
/** Dry-run a call; { failed } with the revert when it would not pass. */
|
|
102
|
+
export async function simulateSplit(client, from, address, abi, functionName, args = []) {
|
|
103
|
+
try {
|
|
104
|
+
const { result } = await client.simulateContract({ account: from, address, abi, functionName, args })
|
|
105
|
+
return { result }
|
|
106
|
+
} catch (e) {
|
|
107
|
+
const r = revertOf(e)
|
|
108
|
+
return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function splitFactoryAddress(testnet) {
|
|
113
|
+
return (testnet ? process.env.GANG_TESTNET_SPLIT_FACTORY || TESTNET_SPLIT_FACTORY
|
|
114
|
+
: process.env.GANG_SPLIT_FACTORY || MAINNET_SPLIT_FACTORY) || null
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export const splitNotDeployed = (testnet) =>
|
|
118
|
+
`GangSplitModuleFactory is not deployed on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version: set ${testnet ? 'GANG_TESTNET_SPLIT_FACTORY' : 'GANG_SPLIT_FACTORY'} to its address`
|
|
119
|
+
|
|
120
|
+
const SPLIT_USAGE = '--split takes <addr>:<pct>[,<addr>:<pct>…]: 1–10 payees, each share in % (up to 2 decimals, at least 0.01), adding up to 100; self (or me) = your wallet. E.g. --split self:60,0xAbc…:30,0xDef…:10'
|
|
121
|
+
const PCT_RE = /^(\d{1,3})(?:\.(\d{1,2}))?$/
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* --split <addr>:<pct>[,…] → { payees, shares (bps), list } or { error, got }, checked as GangSplitModule.initialize checks
|
|
125
|
+
* them (1–10 payees, none 0, no repeats, each share ≥ 1 bps, summing to 10,000). `self` (alias `me`) is the creating wallet;
|
|
126
|
+
* the order is kept (the first payee also takes the rounding dust of each split). Whether a payee is the module itself
|
|
127
|
+
* is checked once its address is known (launch.js, from predict).
|
|
128
|
+
*/
|
|
129
|
+
export function parseSplitSpec(raw, me) {
|
|
130
|
+
const s = String(raw ?? '').trim()
|
|
131
|
+
if (!s || s.startsWith('--')) return { error: SPLIT_USAGE, got: raw ?? null }
|
|
132
|
+
const parts = s.split(',').map((x) => x.trim())
|
|
133
|
+
if (parts.some((p) => !p)) return { error: `${SPLIT_USAGE} (an empty entry between commas)`, got: raw }
|
|
134
|
+
if (parts.length > MAX_PAYEES) return { error: `--split takes at most ${MAX_PAYEES} payees`, got: parts.length }
|
|
135
|
+
const list = []
|
|
136
|
+
for (const p of parts) {
|
|
137
|
+
const i = p.lastIndexOf(':')
|
|
138
|
+
if (i < 0) return { error: `--split: "${p}" is not <addr>:<pct>`, hint: SPLIT_USAGE }
|
|
139
|
+
const who = p.slice(0, i).trim(), pctRaw = p.slice(i + 1).trim()
|
|
140
|
+
let payee, you = false
|
|
141
|
+
if (/^(me|self)$/i.test(who)) {
|
|
142
|
+
if (!isAddress(me ?? '')) return { error: `--split: "${who}" needs your wallet address (sign in with baw, or give --from)` }
|
|
143
|
+
payee = getAddress(me); you = true
|
|
144
|
+
} else if (!isAddress(who)) {
|
|
145
|
+
return { error: `--split: "${who}" is not a 0x address (checksummed or all lowercase) or self`, hint: SPLIT_USAGE }
|
|
146
|
+
} else payee = getAddress(who)
|
|
147
|
+
if (payee === zeroAddress) return { error: '--split: the zero address cannot be a payee' }
|
|
148
|
+
const m = PCT_RE.exec(pctRaw)
|
|
149
|
+
if (!m) return { error: `--split: "${pctRaw}" (for ${who}) is not a share in % with at most 2 decimals (e.g. 60 or 33.33)`, hint: SPLIT_USAGE }
|
|
150
|
+
const bps = Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0'))
|
|
151
|
+
if (bps < 1) return { error: `--split: ${who} has a 0% share; each payee needs at least 0.01%` }
|
|
152
|
+
if (bps > BPS) return { error: `--split: ${who} has more than 100%` }
|
|
153
|
+
if (!you && me && isAddress(me) && payee === getAddress(me)) you = true
|
|
154
|
+
list.push({ payee, bps, you })
|
|
155
|
+
}
|
|
156
|
+
const seen = new Set()
|
|
157
|
+
for (const { payee } of list) {
|
|
158
|
+
if (seen.has(payee)) return { error: `--split: ${payee} appears twice (self is your wallet ${me}); each address holds one slot`, got: raw }
|
|
159
|
+
seen.add(payee)
|
|
160
|
+
}
|
|
161
|
+
const sum = list.reduce((a, x) => a + x.bps, 0)
|
|
162
|
+
if (sum !== BPS) return { error: `--split: the shares add up to ${sum / 100}%, not 100%`, got: raw }
|
|
163
|
+
return {
|
|
164
|
+
payees: list.map((x) => x.payee), shares: list.map((x) => x.bps),
|
|
165
|
+
list: list.map((x, index) => ({ index, payee: x.payee, pct: x.bps / 100, ...(x.you && { you: true }) })),
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The split as a one-line summary: "0xAb…:60%, 0xCd…:40%". */
|
|
170
|
+
export const splitLine = (payees, shares) => payees.map((p, i) => `${p}: ${Number(shares[i]) / 100}%`).join(', ')
|
|
171
|
+
|
|
172
|
+
const iso = (s) => (Number(s) > 0 ? new Date(Number(s) * 1000).toISOString() : null)
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The module's state for printing, from the raw reads (pure: unit-tested). `raw`: { module, dev, token, quote, payees,
|
|
176
|
+
* shares, lastDistributedAt, keeperServesQuote, due, assets: [{ asset, symbol, decimals, undistributed, owedTotal,
|
|
177
|
+
* owed: bigint[] | null }] }. `ref`: how later commands name it (e.g. `--token 0x… --testnet`).
|
|
178
|
+
*/
|
|
179
|
+
export function formatSplit(raw, ref) {
|
|
180
|
+
const token = raw.token && raw.token !== zeroAddress ? raw.token : null
|
|
181
|
+
const quote = token && raw.quote && raw.quote !== zeroAddress ? raw.quote : null
|
|
182
|
+
const isQuote = (a) => !!quote && a.toLowerCase() === quote.toLowerCase()
|
|
183
|
+
const dev = String(raw.dev).toLowerCase()
|
|
184
|
+
const payees = raw.payees.map((payee, index) => ({
|
|
185
|
+
index, payee, pct: Number(raw.shares[index]) / 100, bps: Number(raw.shares[index]), ...(payee.toLowerCase() === dev && { isDev: true }),
|
|
186
|
+
}))
|
|
187
|
+
const next = []
|
|
188
|
+
const assets = []
|
|
189
|
+
for (const a of raw.assets) {
|
|
190
|
+
const owedTotal = a.owedTotal ?? 0n
|
|
191
|
+
const undistributed = a.undistributed ?? 0n
|
|
192
|
+
// the bound quote always; another asset only when something of it is here
|
|
193
|
+
if (!isQuote(a.asset) && undistributed === 0n && owedTotal === 0n) continue
|
|
194
|
+
const f = (x) => formatUnits(x, a.decimals ?? 18)
|
|
195
|
+
const owed = owedTotal > 0n && a.owed
|
|
196
|
+
? a.owed.map((x, index) => ({ index, payee: raw.payees[index], amount: f(x) })).filter((_, i) => a.owed[i] > 0n) : []
|
|
197
|
+
const byKeeper = isQuote(a.asset) && raw.keeperServesQuote
|
|
198
|
+
assets.push({
|
|
199
|
+
asset: a.asset, symbol: a.symbol ?? null, ...(isQuote(a.asset) && { boundQuote: true }),
|
|
200
|
+
undistributed: f(undistributed), owedTotal: f(owedTotal), ...(owed.length && { owed }),
|
|
201
|
+
splitBy: byKeeper ? 'keeper (or anyone, gang split distribute)' : 'hand: gang split distribute (anyone)',
|
|
202
|
+
})
|
|
203
|
+
if (undistributed > 0n && !byKeeper) next.push(`gang split distribute ${ref} --asset ${a.asset}`)
|
|
204
|
+
for (const o of owed) next.push(`gang split release ${ref} --asset ${a.asset} --index ${o.index}`)
|
|
205
|
+
}
|
|
206
|
+
const sym = (assets.find((x) => x.boundQuote)?.symbol) || quote
|
|
207
|
+
const distribution = !token ? 'unbound' : raw.keeperServesQuote ? 'keeper' : 'manual'
|
|
208
|
+
const keeperLine = distribution === 'unbound'
|
|
209
|
+
? `Not bound to a token yet (gang split bind --token <the token>): the keeper splits nothing until then; anyone can split by hand (gang split distribute --asset <addr>)`
|
|
210
|
+
: distribution === 'keeper'
|
|
211
|
+
? `The keeper splits the bound quote (${sym}) once enough has gathered (0.05% of the pool's quote reserve, or after a day once it reaches 1/100 of that); anyone can split it sooner (gang split distribute)`
|
|
212
|
+
: `The keeper does not serve this quote (${sym}): distribution is manual — run gang split distribute (anyone) to pay the payees`
|
|
213
|
+
return {
|
|
214
|
+
module: raw.module, moduleType: SPLIT_TYPE, dev: raw.dev, token, quote, ...(quote && { quoteSymbol: sym }),
|
|
215
|
+
payees, distribution,
|
|
216
|
+
keeper: { servesQuote: token ? !!raw.keeperServesQuote : null, due: !!raw.due, lastDistributedAt: iso(raw.lastDistributedAt) },
|
|
217
|
+
assets,
|
|
218
|
+
...(next.length && { next }),
|
|
219
|
+
note: 'the payees and shares are fixed for good: nobody (not the dev, not the platform) can change them; a payee can only '
|
|
220
|
+
+ 'move its own slot to another address (gang split set-payee). Every asset that reaches the module is split at these '
|
|
221
|
+
+ `shares, the first payee also taking the rounding dust. ${keeperLine}. Any other asset sent to it is split by hand `
|
|
222
|
+
+ '(gang split distribute --asset <addr>). A failed push is owed to that slot and paid with its next push, or by gang split release',
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Reads `asset`'s side of the module; null when it is not an ERC20 the module can read. */
|
|
227
|
+
async function assetRaw(read, module, asset, n) {
|
|
228
|
+
let undistributed, owedTotal
|
|
229
|
+
try {
|
|
230
|
+
[undistributed, owedTotal] = await Promise.all([
|
|
231
|
+
read(module, SPLIT_ABI, 'undistributed', [asset]), read(module, SPLIT_ABI, 'owedTotal', [asset]),
|
|
232
|
+
])
|
|
233
|
+
} catch { return null }
|
|
234
|
+
const [symbol, decimals, owed] = await Promise.all([
|
|
235
|
+
read(asset, ERC20_ABI, 'symbol').catch(() => null),
|
|
236
|
+
read(asset, ERC20_ABI, 'decimals').then(Number).catch(() => 18),
|
|
237
|
+
owedTotal > 0n ? Promise.all(Array.from({ length: n }, (_, i) => read(module, SPLIT_ABI, 'owedOf', [asset, BigInt(i)]))) : null,
|
|
238
|
+
])
|
|
239
|
+
return { asset, symbol, decimals, undistributed, owedTotal, owed }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The module's state when `addr` is a GangSplitModule (split-v1); null when it is not (an EOA, a partner, another
|
|
244
|
+
* module). Assets read: the bound quote, WBNB, the module's GANG (mainnet) and `extraAssets` (e.g. the quote of a token
|
|
245
|
+
* paying it that is not the bound one).
|
|
246
|
+
*/
|
|
247
|
+
export async function splitOf(read, addr, { wbnb, extraAssets = [], ref } = {}) {
|
|
248
|
+
if (!addr || addr === zeroAddress) return null
|
|
249
|
+
let type
|
|
250
|
+
try { type = await read(addr, SPLIT_ABI, 'moduleType') } catch { return null }
|
|
251
|
+
if (hexToString(type, { size: 32 }).replace(/\0+$/, '') !== SPLIT_TYPE) return null
|
|
252
|
+
const [dev, token, quote, [payees, shares], last, gangQuote, preview] = await Promise.all([
|
|
253
|
+
read(addr, SPLIT_ABI, 'dev'), read(addr, SPLIT_ABI, 'token'), read(addr, SPLIT_ABI, 'quote'), read(addr, SPLIT_ABI, 'payeesOf'),
|
|
254
|
+
read(addr, SPLIT_ABI, 'lastDistributedAt'), read(addr, SPLIT_ABI, 'gangQuote').catch(() => zeroAddress),
|
|
255
|
+
read(addr, SPLIT_ABI, 'previewWork').catch(() => [false, 0n]),
|
|
256
|
+
])
|
|
257
|
+
const keeperServesQuote = quote !== zeroAddress ? await read(addr, SPLIT_ABI, 'keeperServes', [quote]).catch(() => false) : false
|
|
258
|
+
const seen = new Set()
|
|
259
|
+
const list = [quote, wbnb, gangQuote, ...extraAssets].filter((a) => {
|
|
260
|
+
if (!a || a === zeroAddress || seen.has(a.toLowerCase())) return false
|
|
261
|
+
seen.add(a.toLowerCase())
|
|
262
|
+
return true
|
|
263
|
+
})
|
|
264
|
+
const assets = (await Promise.all(list.map((a) => assetRaw(read, addr, a, payees.length)))).filter(Boolean)
|
|
265
|
+
return formatSplit({
|
|
266
|
+
module: addr, dev, token, quote, payees, shares, lastDistributedAt: last, keeperServesQuote, due: preview[0], assets,
|
|
267
|
+
}, ref ?? (token !== zeroAddress ? `--token ${token}` : `--module ${addr}`))
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function splitCtx(testnet) {
|
|
271
|
+
const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
|
|
272
|
+
if (!net.pad) throw new Error(NOT_ON_MAINNET)
|
|
273
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
274
|
+
return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const SUBS = ['status', 'distribute', 'release', 'set-payee', 'bind']
|
|
278
|
+
const USAGE = 'usage: gang split <status|distribute|release|set-payee|bind> --token <addr> (or --module <addr>) [--asset <addr>] [--index <i>] [--to <addr>] [--max <amount>] [--testnet] — see gang help'
|
|
279
|
+
|
|
280
|
+
/** `gang split <sub>`: the split module of a V3 token (its tax recipient), found from --token (or named by --module). */
|
|
281
|
+
export async function runSplit(sub, { opt, flag, out, fail, summarize }) {
|
|
282
|
+
if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
|
|
283
|
+
const testnet = flag('testnet')
|
|
284
|
+
const rawOnly = flag('calldata')
|
|
285
|
+
let ctx
|
|
286
|
+
try { ctx = splitCtx(testnet) } catch (e) { return fail(e.message) }
|
|
287
|
+
const chainId = Number(ctx.chainId)
|
|
288
|
+
const tn = testnet ? ' --testnet' : ''
|
|
289
|
+
if (flag('token') && flag('module')) fail('give --token (its tax recipient is the module) or --module, not both')
|
|
290
|
+
let token = null, module, tokenQuote = null
|
|
291
|
+
if (flag('module')) {
|
|
292
|
+
if (sub === 'bind') fail('gang split bind needs --token <the token> (it binds the token\'s own recipient)')
|
|
293
|
+
module = opt('module')
|
|
294
|
+
if (!isAddress(module ?? '')) fail('--module must be a split module address (0x…)', { got: module ?? null })
|
|
295
|
+
} else {
|
|
296
|
+
token = opt('token')
|
|
297
|
+
if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…), or name the module with --module <addr>', { got: token ?? null })
|
|
298
|
+
try {
|
|
299
|
+
const [creator, quote] = await ctx.read(ctx.pad, PAD_ABI, 'curves', [token])
|
|
300
|
+
if (creator === zeroAddress) throw new Error('not a curve')
|
|
301
|
+
tokenQuote = quote
|
|
302
|
+
module = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3]
|
|
303
|
+
} catch {
|
|
304
|
+
return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet'}${testnet ? '' : '; add --testnet for a testnet token'})`, { token, chainId })
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const ref = `${token ? `--token ${token}` : `--module ${module}`}${tn}`
|
|
308
|
+
const s = await splitOf(ctx.read, module, { wbnb: ctx.wbnb, extraAssets: tokenQuote && tokenQuote !== zeroAddress ? [tokenQuote] : [], ref })
|
|
309
|
+
if (!s) {
|
|
310
|
+
return fail(token ? 'this token\'s tax recipient is not a split module' : 'not a split module (split-v1)',
|
|
311
|
+
{ ...(token && { token }), recipient: module === zeroAddress ? null : module })
|
|
312
|
+
}
|
|
313
|
+
// the token pays this module but the module is bound to another one: the keeper never splits this token's tax
|
|
314
|
+
const decoy = token && s.token && s.token.toLowerCase() !== token.toLowerCase()
|
|
315
|
+
const warning = decoy
|
|
316
|
+
? `this token pays its tax to the module, but the module is bound to another token (${s.token}): the keeper splits only that token's quote; this token's tax (${tokenQuote}) is split only by hand (gang split distribute ${ref} --asset ${tokenQuote})`
|
|
317
|
+
: null
|
|
318
|
+
const me = () => walletFor(ctx, opt('from'))
|
|
319
|
+
const send = async (functionName, args, extra) => {
|
|
320
|
+
const sim = await simulateSplit(ctx.client, me(), s.module, SPLIT_ABI, functionName, args)
|
|
321
|
+
if (sim.failed) return out({ success: false, step: extra.step, ...sim.failed })
|
|
322
|
+
const data = encodeFunctionData({ abi: SPLIT_ABI, functionName, args })
|
|
323
|
+
// no gas field: the wallet / node estimates it (GAS_NOTE)
|
|
324
|
+
return out(step(ctx, { from: me(), to: s.module, data }, { chainId, ...(token && { token }), module: s.module, ...extra }, rawOnly, summarize))
|
|
325
|
+
}
|
|
326
|
+
/** --asset <addr | wbnb>, else `def` (the bound quote, or the token's own quote while unbound). */
|
|
327
|
+
const assetArg = (def) => {
|
|
328
|
+
if (!flag('asset')) {
|
|
329
|
+
if (!def) fail('the module is not bound to a token yet: give --asset <addr> (what to split), or bind it first (gang split bind --token <the token>)')
|
|
330
|
+
return def
|
|
331
|
+
}
|
|
332
|
+
const a = opt('asset')
|
|
333
|
+
if (/^wbnb$/i.test(a ?? '')) return ctx.wbnb
|
|
334
|
+
if (!isAddress(a ?? '') || a === zeroAddress) fail('--asset must be a token address (0x…, checksummed or all lowercase) or wbnb', { got: a ?? null })
|
|
335
|
+
return getAddress(a)
|
|
336
|
+
}
|
|
337
|
+
const assetState = async (asset) => {
|
|
338
|
+
const known = s.assets.find((x) => x.asset.toLowerCase() === asset.toLowerCase())
|
|
339
|
+
const r = await assetRaw(ctx.read, s.module, asset, s.payees.length)
|
|
340
|
+
if (!r) fail('the module cannot read that asset\'s balance (not an ERC20?)', { asset })
|
|
341
|
+
return { ...r, symbol: r.symbol ?? known?.symbol ?? null, f: (x) => formatUnits(x, r.decimals) }
|
|
342
|
+
}
|
|
343
|
+
const defaultAsset = s.quote ?? (tokenQuote && tokenQuote !== zeroAddress ? tokenQuote : null)
|
|
344
|
+
|
|
345
|
+
if (sub === 'status') return out({ success: true, chainId, ...s, ...(warning && { warning }) })
|
|
346
|
+
|
|
347
|
+
if (sub === 'bind') {
|
|
348
|
+
if (s.token) return fail('already bound', { boundTo: s.token, ...(warning && { warning }) })
|
|
349
|
+
return send('bind', [token], { step: 'bind', note: 'anyone may bind (once); the token must be the dev\'s and pay its tax to this module. It decides which quote the keeper splits' })
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (sub === 'distribute') {
|
|
353
|
+
const asset = assetArg(defaultAsset)
|
|
354
|
+
const a = await assetState(asset)
|
|
355
|
+
if (a.undistributed === 0n) {
|
|
356
|
+
return fail('nothing of this asset is waiting to be split', {
|
|
357
|
+
asset, symbol: a.symbol, owedTotal: a.f(a.owedTotal),
|
|
358
|
+
...(a.owedTotal > 0n && { hint: `what is held is owed to payees after failed pushes: gang split release ${ref} --asset ${asset} --index <i>` }),
|
|
359
|
+
})
|
|
360
|
+
}
|
|
361
|
+
// as the contract: the others rounded down, the first payee the rest
|
|
362
|
+
const amounts = s.payees.map((p) => (a.undistributed * BigInt(p.bps)) / BigInt(BPS))
|
|
363
|
+
amounts[0] = a.undistributed - amounts.slice(1).reduce((x, y) => x + y, 0n)
|
|
364
|
+
const parts = s.payees.map((p, i) => ({ index: p.index, payee: p.payee, pct: p.pct, gets: a.f(amounts[i]) }))
|
|
365
|
+
return send('distribute', [asset], {
|
|
366
|
+
step: 'distribute', asset, symbol: a.symbol, amount: a.f(a.undistributed), parts,
|
|
367
|
+
note: `anyone may: splits what of this asset arrived since its last split at the fixed shares (the first payee also takes the rounding dust); a push that fails is owed to that slot. Gas: ${GAS_NOTE}`,
|
|
368
|
+
})
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (sub === 'release') {
|
|
372
|
+
const asset = assetArg(defaultAsset)
|
|
373
|
+
const a = await assetState(asset)
|
|
374
|
+
let index
|
|
375
|
+
if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
|
|
376
|
+
else {
|
|
377
|
+
const mine = s.payees.find((p) => p.payee.toLowerCase() === String(me()).toLowerCase())
|
|
378
|
+
const owedSlots = (a.owed ?? []).map((x, i) => (x > 0n ? i : -1)).filter((i) => i >= 0)
|
|
379
|
+
if (mine) index = mine.index
|
|
380
|
+
else if (owedSlots.length === 1) index = owedSlots[0]
|
|
381
|
+
else fail('--index <i> required: which payee slot to pay (gang split status lists what each is owed)', { owedSlots })
|
|
382
|
+
}
|
|
383
|
+
const owed = a.owed ? a.owed[index] : 0n
|
|
384
|
+
if (owed === 0n) return fail(HINTS.NothingOwed, { asset, symbol: a.symbol, index, payee: s.payees[index].payee })
|
|
385
|
+
let max = maxUint256
|
|
386
|
+
if (flag('max')) max = parseUnits(parseAmount(fail, 'max', opt('max')), a.decimals)
|
|
387
|
+
const amount = owed < max ? owed : max
|
|
388
|
+
return send('release', [asset, BigInt(index), max], {
|
|
389
|
+
step: 'release', asset, symbol: a.symbol, index, payee: s.payees[index].payee, amount: a.f(amount), owed: a.f(owed),
|
|
390
|
+
note: `anyone may: splits what newly arrived of this asset first, then pushes ${max === maxUint256 ? 'all' : 'up to --max'} of what this slot is owed to its payee (reverts while it still cannot receive; nothing owed is lost). Gas: ${GAS_NOTE}`,
|
|
391
|
+
})
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// set-payee: only the slot's own payee; the index is the wallet's own slot unless given
|
|
395
|
+
const wallet = String(me()).toLowerCase()
|
|
396
|
+
const mine = s.payees.find((p) => p.payee.toLowerCase() === wallet)
|
|
397
|
+
let index
|
|
398
|
+
if (flag('index')) index = indexArg(opt('index'), s.payees.length, fail)
|
|
399
|
+
else if (mine) index = mine.index
|
|
400
|
+
else return fail('this wallet is not a payee of this module: only a slot\'s own payee can move it', { wallet: me(), payees: s.payees.map((p) => p.payee) })
|
|
401
|
+
const slot = s.payees[index]
|
|
402
|
+
if (slot.payee.toLowerCase() !== wallet) return fail(HINTS.NotPayee, { index, payee: slot.payee, wallet: me() })
|
|
403
|
+
const to = opt('to')
|
|
404
|
+
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 })
|
|
405
|
+
if (to.toLowerCase() === s.module.toLowerCase()) return fail(HINTS.BadPayee, { to })
|
|
406
|
+
const taken = s.payees.find((p) => p.payee.toLowerCase() === to.toLowerCase())
|
|
407
|
+
if (taken) return fail(taken.index === index ? 'that is this slot\'s payee already' : HINTS.DuplicatePayee, { to, index: taken.index })
|
|
408
|
+
// the contract splits only the bound quote before the move: what else arrived would go to the new address, so split
|
|
409
|
+
// those first (review I-3); each is its own tx, then the same command again
|
|
410
|
+
const unsplit = s.assets.filter((x) => !x.boundQuote && Number(x.undistributed) > 0)
|
|
411
|
+
if (unsplit.length) {
|
|
412
|
+
const first = unsplit[0]
|
|
413
|
+
return send('distribute', [first.asset], {
|
|
414
|
+
step: 'distribute-first', asset: first.asset, symbol: first.symbol, amount: first.undistributed,
|
|
415
|
+
...(unsplit.length > 1 && { thenAlso: unsplit.slice(1).map((x) => ({ asset: x.asset, symbol: x.symbol, amount: x.undistributed })) }),
|
|
416
|
+
note: `before the move: ${first.symbol || first.asset} that arrived earlier is split to the current payees (the contract splits only the bound quote itself). After executing, re-run the same command. Gas: ${GAS_NOTE}`,
|
|
417
|
+
})
|
|
418
|
+
}
|
|
419
|
+
return send('setPayee', [BigInt(index), getAddress(to)], {
|
|
420
|
+
step: 'set-payee', index, pct: slot.pct, fromPayee: slot.payee, toPayee: getAddress(to),
|
|
421
|
+
note: `applies at once; the share (${slot.pct}%) stays with the slot. The bound quote that arrived before is split first (to the current address); what this slot is owed (any asset) goes to the new one. Gas: ${GAS_NOTE}`,
|
|
422
|
+
})
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function indexArg(raw, n, fail) {
|
|
426
|
+
const i = Number(raw)
|
|
427
|
+
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 split status lists them)`, { got: raw ?? null })
|
|
428
|
+
return i
|
|
429
|
+
}
|
package/src/steps.js
CHANGED
|
@@ -44,7 +44,7 @@ export const ROUTER_HINTS = {
|
|
|
44
44
|
UnknownToken: 'the router does not know this token on its pad (the other kind of token, or not a gang token)',
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
|
-
* A gas limit with room for a call whose cost moves between the estimate and the block it lands in (a
|
|
47
|
+
* A gas limit with room for a call whose cost moves between the estimate and the block it lands in (a 铸币飞轮 token's
|
|
48
48
|
* first pool touch in a block writes its price checkpoints) and whose nested calls need more than an exact limit leaves
|
|
49
49
|
* them (63/64 rule): 1.5 × the estimate (what the Agentic Wallet itself adds on most calls), at least `floor`. A
|
|
50
50
|
* reverting estimate is thrown (the caller reports its reason; nothing is sent); only an RPC failure falls back to the floor.
|
package/src/v3.js
CHANGED
|
@@ -7,6 +7,7 @@ import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets,
|
|
|
7
7
|
import { poolPayBnb, poolTrade } from './pool.js'
|
|
8
8
|
import { bondGuard } from './bond.js'
|
|
9
9
|
import { splitterOf } from './buyback.js'
|
|
10
|
+
import { splitOf } from './split.js'
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* `gang v3 …` — LaunchpadV3 (tax recipient): a token with its own buy / sell tax (1–5% each), a dividend share and a
|
|
@@ -278,7 +279,15 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
278
279
|
: `untaxed; curve trades pay the ${fees.curveFeePct}% fee`
|
|
279
280
|
// a recipient that is the dev's buy-back splitter: its ratio and what waits to be bought back
|
|
280
281
|
const buyback = c.recipient && !c.recipientIsCreator ? await splitterOf(ctx.read, c.recipient) : null
|
|
281
|
-
|
|
282
|
+
// or the dev's split module (split-v1): its fixed payees and shares, what waits to be split
|
|
283
|
+
const split = c.recipient && !c.recipientIsCreator && !buyback
|
|
284
|
+
? await splitOf(ctx.read, c.recipient, { wbnb: ctx.wbnb, extraAssets: [c.quote], ref: `--token ${token}${net}` }) : null
|
|
285
|
+
const splitWarn = split && split.token && split.token.toLowerCase() !== token.toLowerCase()
|
|
286
|
+
? { warning: `this token pays its tax to the split module, but the module is bound to another token (${split.token}): the keeper never splits this token's tax (${c.quote}); it is split only by hand (gang split distribute --token ${token}${net} --asset ${c.quote})` } : null
|
|
287
|
+
return out({
|
|
288
|
+
success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
|
|
289
|
+
...(split && { split: { ...split, ...splitWarn } }),
|
|
290
|
+
})
|
|
282
291
|
}
|
|
283
292
|
|
|
284
293
|
if (sub === 'status') {
|