@gangfun/cli 0.36.1 → 0.38.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/DEVELOPERS.md +12 -0
- package/DEVELOPERS.zh-CN.md +10 -0
- package/README.md +5 -0
- package/README.zh-CN.md +5 -0
- package/package.json +1 -1
- package/src/callbond.js +535 -0
- package/src/capabilities.js +8 -1
- package/src/fair.js +11 -4
- package/src/flags.js +2 -2
- package/src/fly.js +14 -5
- package/src/gangpad.js +8 -2
- package/src/index.js +26 -4
- package/src/mcp.js +16 -14
- package/src/notes.js +2 -1
- package/src/pool.js +6 -1
- package/src/promote.js +21 -0
- package/src/v3.js +40 -15
- package/src/vanity.js +57 -0
package/src/callbond.js
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { createPublicClient, parseAbi, parseAbiItem, encodeFunctionData, decodeEventLog, formatUnits, parseUnits, isAddress, getAddress, keccak256, concat } from 'viem'
|
|
3
|
+
import { decimalsOf, fundingStep as fund, parseAmount, revertOf as revertIn, step, units, GAS_RESERVE } from './steps.js'
|
|
4
|
+
import { gangGens, MERGED_ERRORS_ABI, MERGED_HINTS, PAD3_GEN, padNets, rpcTransport } from './gangpad.js'
|
|
5
|
+
import { bawAddress } from './baw.js'
|
|
6
|
+
import { get as apiGet } from './discover.js'
|
|
7
|
+
import { readNoteCommit } from './notes.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `gang call-bond …` — GangCallBond (喊单保证金, gang-launchpad src/gang/GangCallBond.sol, spec
|
|
11
|
+
* docs/SPEC-AGENT-CALLS-2026-11-09.md §5): an agent bonds its own call (a buy note) on a 3.0 curve token. It posts the
|
|
12
|
+
* token's quote and promises its balance of the token stays at least `hold` until `settle` (48 h – 7 days on).
|
|
13
|
+
* Kept: anyone settles after the deadline (two steps, 1 hour apart) and the whole bond comes back. Broken (the balance
|
|
14
|
+
* below hold before settle, the deadline passed or not): anyone reports it; the reporter gets 1%, half burns at once and
|
|
15
|
+
* the rest pays the note's followers by their loss (a Merkle root the settler posts, 2 days for the Safe to veto, then
|
|
16
|
+
* claims). Nothing of a broken bond ever comes back to the caller.
|
|
17
|
+
* One contract per network, bound to GangLaunchpad 3.0. Env: GANG_CALL_BOND (mainnet), GANG_TESTNET_CALL_BOND (testnet).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const CALL_BOND_ABI = parseAbi([
|
|
21
|
+
'function post(address token, bytes32 noteTx, uint256 amount, uint256 hold, uint64 duration) payable returns (uint256 id)',
|
|
22
|
+
'function report(uint256 id)',
|
|
23
|
+
'function requestSettle(uint256 id)',
|
|
24
|
+
'function settle(uint256 id)',
|
|
25
|
+
'function claim(uint256 id, address account, uint256 amount, bytes32[] proof)',
|
|
26
|
+
'function burnRemainder(uint256 id)',
|
|
27
|
+
'function burnUnpaid(uint256 id)',
|
|
28
|
+
'function bondOf(uint256 id) view returns ((address caller, uint64 postedAt, uint8 state, address token, uint64 deadline, address quote, uint64 settleAt, uint128 amount, uint128 hold, uint64 reportedAt, uint64 reportedBlock, uint64 rootAt, uint64 vetoAt, uint128 pool, uint128 spent, uint128 total, bool remainderBurned, bytes32 noteTx, bytes32 root))',
|
|
29
|
+
'function activeBondOf(address caller, address token) view returns (uint256)',
|
|
30
|
+
'function claimed(uint256 id, address account) view returns (bool)',
|
|
31
|
+
'function leaf(uint256 id, address account, uint256 amount) view returns (bytes32)',
|
|
32
|
+
'function pad() view returns (address)',
|
|
33
|
+
'function wbnb() view returns (address)',
|
|
34
|
+
'function quote1() view returns (address)',
|
|
35
|
+
'function quote2() view returns (address)',
|
|
36
|
+
'function quote3() view returns (address)',
|
|
37
|
+
'event CallBondPosted(uint256 indexed id, address indexed caller, address indexed token, bytes32 noteTx, address quote, uint256 amount, uint256 hold, uint64 deadline)',
|
|
38
|
+
'event CallBondReported(uint256 indexed id, address indexed reporter, uint256 reportedBlock, uint256 balance, uint256 reward, uint256 burned, uint256 pool)',
|
|
39
|
+
'event SettleRequested(uint256 indexed id, uint64 settleAt)',
|
|
40
|
+
'event CallBondSettled(uint256 indexed id, address indexed caller, uint256 amount)',
|
|
41
|
+
'event RootPosted(uint256 indexed id, bytes32 root, uint256 total, uint64 claimableAt)',
|
|
42
|
+
'event RootVetoed(uint256 indexed id, bytes32 root)',
|
|
43
|
+
'event Claimed(uint256 indexed id, address indexed account, uint256 amount)',
|
|
44
|
+
'event RemainderBurned(uint256 indexed id, uint256 amount)',
|
|
45
|
+
'event UnpaidBurned(uint256 indexed id, uint256 amount)',
|
|
46
|
+
'error NotCurveToken()', 'error BadTokenVersion()', 'error AlreadyGraduated()', 'error QuoteNotAllowed()',
|
|
47
|
+
'error BadDuration()', 'error BadHold()', 'error BadNote()', 'error BondLive()', 'error BadValue()', 'error ZeroAmount()',
|
|
48
|
+
'error FeeOnTransferQuote()', 'error NotActive()', 'error NotViolated()', 'error Violated()', 'error FlashSwapActive()',
|
|
49
|
+
'error NotDue()', 'error AlreadyRequested()', 'error NoSettleRequest()', 'error NotReported()', 'error NotClaimable()',
|
|
50
|
+
'error AlreadyClaimed()', 'error BadProof()', 'error OverTotal()', 'error NotFollower()', 'error AlreadyBurned()',
|
|
51
|
+
'error StillPayable()',
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
const PAD_ABI = parseAbi([
|
|
55
|
+
'function kindOf(address token) view returns (uint8)',
|
|
56
|
+
'function tokenVersionOf(address token) view returns (uint8)',
|
|
57
|
+
'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)',
|
|
58
|
+
])
|
|
59
|
+
const ERC20_ABI = parseAbi([
|
|
60
|
+
'function balanceOf(address) view returns (uint256)',
|
|
61
|
+
'function symbol() view returns (string)',
|
|
62
|
+
])
|
|
63
|
+
const TRADE_V1 = parseAbiItem('event TradeV1(address indexed token, address indexed trader, bool isBuy, uint256 quoteAmount, uint256 tokenAmount, uint256 protocolFee, uint256 creatorFee, uint256 postPrice, uint256 realQuote, uint256 sold)')
|
|
64
|
+
|
|
65
|
+
export const STATES = ['none', 'active', 'settled', 'reported', 'closed']
|
|
66
|
+
const HOUR = 3_600
|
|
67
|
+
export const MIN_DURATION = 48 * HOUR
|
|
68
|
+
export const MAX_DURATION = 7 * 24 * HOUR
|
|
69
|
+
const SETTLE_DELAY = HOUR
|
|
70
|
+
const ROOT_DELAY = HOUR + 600
|
|
71
|
+
const DISPUTE = 2 * 24 * HOUR
|
|
72
|
+
const CLAIM_WINDOW = 90 * 24 * HOUR
|
|
73
|
+
// the site shows a bond as 有担保 only when it is posted within this long of its note (spec §5.4)
|
|
74
|
+
export const LABEL_WINDOW = 600
|
|
75
|
+
const FOLLOW_WINDOW = 24 * HOUR
|
|
76
|
+
const NOTE_LOOKBACK_BLOCKS = 3_000n // ~20 min at 0.45 s blocks: the default note is the wallet's latest buy within it
|
|
77
|
+
const BPS = 10_000n
|
|
78
|
+
const REPORTER_BPS = 100n
|
|
79
|
+
const BURN_BPS = 5_000n
|
|
80
|
+
|
|
81
|
+
const HINTS = {
|
|
82
|
+
NotCurveToken: 'only GangLaunchpad 3.0 curve tokens take a call bond (not 打新, 铸币飞轮 or older pads)',
|
|
83
|
+
BadTokenVersion: 'this token was created under a rule set the call bond does not cover',
|
|
84
|
+
AlreadyGraduated: 'the token has graduated: calls (and follows) are curve-only, so it takes no new call bond',
|
|
85
|
+
QuoteNotAllowed: 'the token\'s quote is not WBNB, USDT, USDC or USD1: no call bond on it',
|
|
86
|
+
BadDuration: '--for must be 48h to 7d',
|
|
87
|
+
BadHold: 'hold must be more than 0 and at most what the wallet holds now',
|
|
88
|
+
BadNote: 'the note tx is missing',
|
|
89
|
+
BondLive: 'this wallet already has a running call bond on this token: settle it (or let it be reported) first',
|
|
90
|
+
BadValue: 'BNB sent with the bond must equal its amount, on a WBNB-quoted token only',
|
|
91
|
+
NotActive: 'this call bond is not running (settled, reported or unknown)',
|
|
92
|
+
NotViolated: 'the caller still holds at least what it promised: nothing to report',
|
|
93
|
+
Violated: 'the caller holds less than it promised: it can only be reported now',
|
|
94
|
+
FlashSwapActive: 'the pair is mid flash swap: try again in the next block',
|
|
95
|
+
NotDue: 'too early: see deadline / settleAt',
|
|
96
|
+
AlreadyRequested: 'settle was already asked for: run settle once settleAt has passed',
|
|
97
|
+
NotClaimable: 'nothing to claim yet: no root, its 2-day dispute window is still running, or the claim window is over',
|
|
98
|
+
AlreadyClaimed: 'this account already claimed its payout',
|
|
99
|
+
BadProof: 'the proof does not match the posted root',
|
|
100
|
+
OverTotal: 'the root\'s leaves add up to more than its total: this leaf can\'t be paid',
|
|
101
|
+
NotFollower: 'the caller can never claim from its own broken bond',
|
|
102
|
+
NotReported: 'this call bond is not reported (or already closed)',
|
|
103
|
+
AlreadyBurned: 'the remainder was burnt already',
|
|
104
|
+
StillPayable: 'not yet: the followers can still be paid (a root may still come, or its claim window is open)',
|
|
105
|
+
}
|
|
106
|
+
const revertOf = (e) => revertIn(e, [CALL_BOND_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...HINTS })
|
|
107
|
+
|
|
108
|
+
const same = (a, b) => !!a && !!b && a.toLowerCase() === b.toLowerCase()
|
|
109
|
+
const iso = (s) => (Number(s) ? new Date(Number(s) * 1000).toISOString() : null)
|
|
110
|
+
const tokens = (x) => formatUnits(x, 18)
|
|
111
|
+
|
|
112
|
+
/** GangCallBond of `testnet` / mainnet (env first), bound to the network's 3.0 pad; null when not deployed there. */
|
|
113
|
+
export function callBondAddress(testnet) {
|
|
114
|
+
return gangGens(testnet).find((g) => g.gen === PAD3_GEN)?.callBond || null
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function callBondCtx(testnet) {
|
|
118
|
+
const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
|
|
119
|
+
const g3 = net.gens.find((g) => g.gen === PAD3_GEN)
|
|
120
|
+
const addr = callBondAddress(testnet)
|
|
121
|
+
if (!g3 || !addr) throw new Error(`GangCallBond is not deployed on ${testnet ? 'the BSC testnet' : 'BSC mainnet'} in this CLI version${testnet ? '' : ' (testnet: add --testnet)'}: set ${testnet ? 'GANG_TESTNET_CALL_BOND' : 'GANG_CALL_BOND'} to its address`)
|
|
122
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
123
|
+
return { ...net, pad: g3.pad, callBond: addr, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const walletFor = (ctx, from) => {
|
|
127
|
+
if (from) return from
|
|
128
|
+
try { return bawAddress(ctx.chainId) } catch { return bawAddress('56') }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function simulate(ctx, from, functionName, args, value = 0n) {
|
|
132
|
+
try {
|
|
133
|
+
const { result } = await ctx.client.simulateContract({ account: from, address: ctx.callBond, abi: CALL_BOND_ABI, functionName, args, value })
|
|
134
|
+
return { result }
|
|
135
|
+
} catch (e) {
|
|
136
|
+
const r = revertOf(e)
|
|
137
|
+
return { failed: r ? { reverted: true, ...r } : { reverted: false, error: e.shortMessage || e.message.split('\n')[0] } }
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** --for: 48h–7d, as `72h`, `3d` (a bare number is refused: hours or days must be said). → seconds */
|
|
142
|
+
export function parseFor(raw) {
|
|
143
|
+
const m = String(raw ?? '').trim().match(/^(\d+(?:\.\d+)?)([hd])$/i)
|
|
144
|
+
if (!m) throw new Error(`--for must look like 48h or 3d (48 hours to 7 days; got ${raw ?? 'nothing'})`)
|
|
145
|
+
const s = Math.round(Number(m[1]) * (m[2].toLowerCase() === 'h' ? HOUR : 24 * HOUR))
|
|
146
|
+
if (s < MIN_DURATION || s > MAX_DURATION) throw new Error(`--for must be 48h to 7d (got ${raw})`)
|
|
147
|
+
return s
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** --hold: `all` (default), N% of the balance, or a token amount. → { hold, all } */
|
|
151
|
+
export function parseHold(raw, balance) {
|
|
152
|
+
const v = String(raw ?? 'all').trim().toLowerCase()
|
|
153
|
+
if (v === 'all') return { hold: balance, all: true }
|
|
154
|
+
const pct = v.match(/^(\d+(?:\.\d+)?)%$/)
|
|
155
|
+
if (pct) {
|
|
156
|
+
const bps = BigInt(Math.round(Number(pct[1]) * 100))
|
|
157
|
+
if (bps <= 0n || bps > BPS) throw new Error('--hold N% must be above 0% and at most 100%')
|
|
158
|
+
const hold = (balance * bps) / BPS
|
|
159
|
+
return { hold, all: hold === balance }
|
|
160
|
+
}
|
|
161
|
+
if (!/^\d+(\.\d+)?$/.test(v)) throw new Error(`--hold must be all, N% or a token amount (got ${raw})`)
|
|
162
|
+
const hold = parseUnits(v, 18)
|
|
163
|
+
return { hold, all: hold === balance }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The forfeit split of `amount` (spec §5.2): reporter 1% (burnt when the caller reports itself), half burnt, the rest the pool. */
|
|
167
|
+
export function forfeitSplit(amount, selfReport = false) {
|
|
168
|
+
let reward = (amount * REPORTER_BPS) / BPS
|
|
169
|
+
let burned = (amount * BURN_BPS) / BPS
|
|
170
|
+
if (selfReport) { burned += reward; reward = 0n }
|
|
171
|
+
return { reward, burned, pool: amount - reward - burned }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** OpenZeppelin MerkleProof (sorted pairs) over `leaf`. */
|
|
175
|
+
export function rootFromProof(leaf, proof) {
|
|
176
|
+
let h = leaf
|
|
177
|
+
for (const p of proof) h = BigInt(h) < BigInt(p) ? keccak256(concat([h, p])) : keccak256(concat([p, h]))
|
|
178
|
+
return h
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The leaf the contract checks: StandardMerkleTree's double hash of (contract, chainId, id, account, amount). */
|
|
182
|
+
export function leafOf(contract, chainId, id, account, amount) {
|
|
183
|
+
const enc = (v, t) => (t === 'address' ? v.toLowerCase().slice(2).padStart(64, '0') : BigInt(v).toString(16).padStart(64, '0'))
|
|
184
|
+
const inner = keccak256(`0x${enc(contract, 'address')}${enc(chainId)}${enc(id)}${enc(account, 'address')}${enc(amount)}`)
|
|
185
|
+
return keccak256(inner)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Whether gang.fun will show this bond as 有担保 (spec §5.4), as far as the CLI can tell before it lands:
|
|
190
|
+
* the whole balance held, posted within 10 minutes of its note (no sell since), deadline ≥ the note + 48 h.
|
|
191
|
+
*/
|
|
192
|
+
export function labelCheck({ holdAll, noteTime, now, duration, soldSince }) {
|
|
193
|
+
const why = []
|
|
194
|
+
if (!holdAll) why.push('hold is not the whole balance')
|
|
195
|
+
if (noteTime == null) why.push('the note\'s time is unknown')
|
|
196
|
+
else {
|
|
197
|
+
if (now - noteTime > LABEL_WINDOW) why.push('more than 10 minutes after the note')
|
|
198
|
+
if (now + duration < noteTime + 2 * FOLLOW_WINDOW) why.push('the deadline is earlier than the note + 48 h')
|
|
199
|
+
}
|
|
200
|
+
if (soldSince) why.push('the wallet sold this token after the note')
|
|
201
|
+
return why.length ? { bonded: false, why } : { bonded: true }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The wallet's latest curve buy of `token` on the pad in the last ~20 minutes, and whether it sold since. null when none found. */
|
|
205
|
+
async function latestBuy(ctx, token, me) {
|
|
206
|
+
const to = await ctx.client.getBlockNumber()
|
|
207
|
+
const from = to > NOTE_LOOKBACK_BLOCKS ? to - NOTE_LOOKBACK_BLOCKS : 0n
|
|
208
|
+
const logs = await ctx.client.getLogs({ address: ctx.pad, event: TRADE_V1, args: { token, trader: me }, fromBlock: from, toBlock: to })
|
|
209
|
+
const buys = logs.filter((l) => l.args.isBuy)
|
|
210
|
+
if (!buys.length) return null
|
|
211
|
+
const last = buys[buys.length - 1]
|
|
212
|
+
const soldSince = logs.some((l) => !l.args.isBuy && (l.blockNumber > last.blockNumber || (l.blockNumber === last.blockNumber && l.logIndex > last.logIndex)))
|
|
213
|
+
return { tx: last.transactionHash, block: last.blockNumber, soldSince }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function bondView(ctx, id) {
|
|
217
|
+
const b = await ctx.read(ctx.callBond, CALL_BOND_ABI, 'bondOf', [id])
|
|
218
|
+
const state = STATES[Number(b.state)] ?? `unknown(${b.state})`
|
|
219
|
+
if (state === 'none') return { state, raw: b }
|
|
220
|
+
const [dec, sym, bal, block] = await Promise.all([
|
|
221
|
+
decimalsOf(ctx, b.quote), ctx.read(b.quote, ERC20_ABI, 'symbol').catch(() => null),
|
|
222
|
+
ctx.read(b.token, ERC20_ABI, 'balanceOf', [b.caller]), ctx.client.getBlock(),
|
|
223
|
+
])
|
|
224
|
+
const q = (x) => formatUnits(x, dec)
|
|
225
|
+
const now = Number(block.timestamp)
|
|
226
|
+
const view = {
|
|
227
|
+
id: Number(id), state, caller: b.caller, token: b.token, noteTx: b.noteTx, quote: b.quote, quoteSymbol: sym,
|
|
228
|
+
amount: q(b.amount), hold: tokens(b.hold), callerBalance: tokens(bal), postedAt: iso(b.postedAt), deadline: iso(b.deadline),
|
|
229
|
+
}
|
|
230
|
+
if (state === 'active') {
|
|
231
|
+
const violated = bal < b.hold
|
|
232
|
+
Object.assign(view, {
|
|
233
|
+
violated, headroom: violated ? '0' : tokens(bal - b.hold),
|
|
234
|
+
...(b.settleAt !== 0n && { settleAt: iso(b.settleAt) }),
|
|
235
|
+
phase: violated ? 'broken: anyone can report it' : now < Number(b.deadline) ? 'running' : b.settleAt === 0n ? 'past the deadline: settle (step 1 of 2)' : now < Number(b.settleAt) ? 'settle asked for: waiting 1 hour' : 'settle can run now',
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
if (state === 'reported' || state === 'closed') {
|
|
239
|
+
const claimableAt = b.rootAt ? Number(b.rootAt) + DISPUTE : null
|
|
240
|
+
Object.assign(view, {
|
|
241
|
+
reportedAt: iso(b.reportedAt), reportedBlock: Number(b.reportedBlock), pool: q(b.pool), paidOrBurnt: q(b.spent),
|
|
242
|
+
root: b.root === `0x${'0'.repeat(64)}` ? null : { root: b.root, total: q(b.total), postedAt: iso(b.rootAt), claimableAt: iso(claimableAt), claimsUntil: claimableAt && iso(claimableAt + CLAIM_WINDOW), remainderBurnt: b.remainderBurned },
|
|
243
|
+
...(b.vetoAt !== 0n && { lastVetoAt: iso(b.vetoAt) }),
|
|
244
|
+
...(state === 'reported' && b.rootAt === 0n && { rootsFrom: iso(Number(b.reportedAt) + ROOT_DELAY) }),
|
|
245
|
+
})
|
|
246
|
+
}
|
|
247
|
+
return { ...view, raw: b, dec, now, bal }
|
|
248
|
+
}
|
|
249
|
+
const pub = ({ raw, dec, now, bal, ...v }) => v
|
|
250
|
+
|
|
251
|
+
/** A payout of a reported bond for `account`: from --from-file (the reference script's JSON), else gang.fun. */
|
|
252
|
+
async function proofFor(ctx, id, account, file) {
|
|
253
|
+
if (file) {
|
|
254
|
+
let j
|
|
255
|
+
try { j = JSON.parse(readFileSync(file, 'utf8')) } catch (e) { throw new Error(`--from-file: cannot read ${file}: ${e.message}`) }
|
|
256
|
+
if (Number(j.id) !== Number(id) || !same(j.contract, ctx.callBond)) throw new Error(`--from-file is for bond ${j.id} on ${j.contract}, not ${id} on ${ctx.callBond}`)
|
|
257
|
+
const l = (j.leaves || []).find((x) => same(x.account, account))
|
|
258
|
+
return l ? { amount: BigInt(l.amount), proof: l.proof } : null
|
|
259
|
+
}
|
|
260
|
+
const r = await apiGet(`/callbond/${id}/proof/${account.toLowerCase()}`, undefined, '')
|
|
261
|
+
return r ? { amount: BigInt(r.amount), proof: r.proof } : null
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const SUBS = ['post', 'status', 'report', 'settle', 'claim', 'burn', 'tx']
|
|
265
|
+
const USAGE = 'usage: gang call-bond <post|status|report|settle|claim|burn|tx> [--token <addr> | --id <n>] [--testnet] — see gang help'
|
|
266
|
+
const NOTE_FLAGS = ['conf', 'reveal-after', 'follow']
|
|
267
|
+
|
|
268
|
+
/** Entry for `gang call-bond <sub>`. io: { opt, flag, out, fail, summarize } from index.js. */
|
|
269
|
+
export async function runCallBond(sub, { opt, flag, out, fail, summarize }) {
|
|
270
|
+
if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
|
|
271
|
+
const noteFlag = NOTE_FLAGS.find((f) => flag(f))
|
|
272
|
+
if (noteFlag) return fail(`--${noteFlag}: gang call-bond takes no notes (the call is the buy note it bonds: --note <that tx>)`)
|
|
273
|
+
const testnet = flag('testnet')
|
|
274
|
+
const net = testnet ? ' --testnet' : ''
|
|
275
|
+
const rawOnly = flag('calldata')
|
|
276
|
+
let ctx
|
|
277
|
+
try { ctx = callBondCtx(testnet) } catch (e) { return fail(e.message) }
|
|
278
|
+
const chainId = Number(ctx.chainId)
|
|
279
|
+
let wallet = null
|
|
280
|
+
const me = () => (wallet ??= walletFor(ctx, opt('from')))
|
|
281
|
+
const send = (functionName, args, extra, value = 0n) =>
|
|
282
|
+
step(ctx, { from: me(), to: ctx.callBond, data: encodeFunctionData({ abi: CALL_BOND_ABI, functionName, args }), value }, { chainId, callBondContract: ctx.callBond, ...extra }, rawOnly, summarize)
|
|
283
|
+
const idArg = () => {
|
|
284
|
+
const v = opt('id')
|
|
285
|
+
if (v != null) {
|
|
286
|
+
if (!/^\d+$/.test(v) || v === '0') fail('--id must be a call bond id (1, 2, …)', { got: v })
|
|
287
|
+
return BigInt(v)
|
|
288
|
+
}
|
|
289
|
+
return null
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (sub === 'tx') {
|
|
293
|
+
const hash = opt('hash')
|
|
294
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(hash ?? '')) fail('--hash must be a tx hash')
|
|
295
|
+
const r = await ctx.client.waitForTransactionReceipt({ hash, timeout: 120_000 })
|
|
296
|
+
const events = []
|
|
297
|
+
for (const log of r.logs) {
|
|
298
|
+
if (!same(log.address, ctx.callBond)) continue
|
|
299
|
+
try {
|
|
300
|
+
const ev = decodeEventLog({ abi: CALL_BOND_ABI, data: log.data, topics: log.topics })
|
|
301
|
+
events.push({ event: ev.eventName, ...Object.fromEntries(Object.entries(ev.args).map(([k, v]) => [k, typeof v === 'bigint' ? v.toString() : v])) })
|
|
302
|
+
} catch { /* not a call bond event */ }
|
|
303
|
+
}
|
|
304
|
+
return out({ success: true, chainId, hash, status: r.status, block: Number(r.blockNumber), events, explorer: `${ctx.explorer}/tx/${hash}` })
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (sub === 'post') {
|
|
308
|
+
if (opt('id')) fail('gang call-bond post takes --token, not --id')
|
|
309
|
+
const tokenRaw = opt('token')
|
|
310
|
+
if (!isAddress(tokenRaw ?? '')) fail('--token <3.0 curve token> required')
|
|
311
|
+
const token = getAddress(tokenRaw)
|
|
312
|
+
let duration
|
|
313
|
+
try { duration = parseFor(opt('for')) } catch (e) { fail(e.message) }
|
|
314
|
+
if (!flag('amount')) fail('--amount <bond, in the token\'s quote> required')
|
|
315
|
+
const [kind, version, curve] = await Promise.all([
|
|
316
|
+
ctx.read(ctx.pad, PAD_ABI, 'kindOf', [token]), ctx.read(ctx.pad, PAD_ABI, 'tokenVersionOf', [token]).catch(() => 0),
|
|
317
|
+
ctx.read(ctx.pad, PAD_ABI, 'curves', [token]),
|
|
318
|
+
])
|
|
319
|
+
if (Number(kind) !== 1) fail(HINTS.NotCurveToken, { token, pad: ctx.pad })
|
|
320
|
+
if (Number(version) !== 1) fail(HINTS.BadTokenVersion, { token })
|
|
321
|
+
const [, quote, , , , , graduated] = curve
|
|
322
|
+
if (graduated) fail(HINTS.AlreadyGraduated, { token })
|
|
323
|
+
const allowed = await Promise.all(['wbnb', 'quote1', 'quote2', 'quote3'].map((f) => ctx.read(ctx.callBond, CALL_BOND_ABI, f)))
|
|
324
|
+
if (!allowed.some((a) => same(a, quote))) fail(HINTS.QuoteNotAllowed, { token, quote })
|
|
325
|
+
const wallet_ = me()
|
|
326
|
+
const live = await ctx.read(ctx.callBond, CALL_BOND_ABI, 'activeBondOf', [wallet_, token])
|
|
327
|
+
if (live !== 0n) fail(HINTS.BondLive, { id: Number(live), next: `gang call-bond status --id ${live}${net}` })
|
|
328
|
+
const [dec, sym, bal, block] = await Promise.all([
|
|
329
|
+
decimalsOf(ctx, quote), ctx.read(quote, ERC20_ABI, 'symbol').catch(() => 'quote'),
|
|
330
|
+
ctx.read(token, ERC20_ABI, 'balanceOf', [wallet_]), ctx.client.getBlock(),
|
|
331
|
+
])
|
|
332
|
+
if (bal === 0n) fail('this wallet holds none of the token: buy first (the call is that buy\'s note)', { token, wallet: wallet_ })
|
|
333
|
+
let h
|
|
334
|
+
try { h = parseHold(opt('hold'), bal) } catch (e) { fail(e.message) }
|
|
335
|
+
if (h.hold === 0n || h.hold > bal) fail(HINTS.BadHold, { hold: tokens(h.hold), balance: tokens(bal) })
|
|
336
|
+
const amount = parseUnits(parseAmount(fail, 'amount', opt('amount')), dec)
|
|
337
|
+
if (amount === 0n) fail('--amount must be more than 0')
|
|
338
|
+
// the call: --note <tx>, else the wallet's latest curve buy of this token in the last ~20 minutes
|
|
339
|
+
let noteTx = opt('note')
|
|
340
|
+
let noteTime = null
|
|
341
|
+
let soldSince = false
|
|
342
|
+
if (noteTx != null) {
|
|
343
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(noteTx)) fail('--note must be the tx hash of your buy note (0x + 64 hex)', { got: noteTx })
|
|
344
|
+
// the call must be this wallet's own curve buy of this token: followers of anything else could never be paid
|
|
345
|
+
let rc
|
|
346
|
+
try { rc = await ctx.client.getTransactionReceipt({ hash: noteTx }) } catch (e) {
|
|
347
|
+
fail('could not read --note on chain (unknown tx or RPC error): a call bond must name your own buy of this token', { noteTx, detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' })
|
|
348
|
+
}
|
|
349
|
+
if (!same(rc.from, wallet_)) fail('--note is not this wallet\'s own tx: a call bond backs your own call', { noteFrom: rc.from, wallet: wallet_ })
|
|
350
|
+
const bought = rc.status === 'success' && rc.logs.some((l) => {
|
|
351
|
+
if (!same(l.address, ctx.pad)) return false
|
|
352
|
+
try {
|
|
353
|
+
const ev = decodeEventLog({ abi: [TRADE_V1], data: l.data, topics: l.topics })
|
|
354
|
+
return ev.args.isBuy && same(ev.args.token, token) && same(ev.args.trader, wallet_)
|
|
355
|
+
} catch { return false }
|
|
356
|
+
})
|
|
357
|
+
if (!bought) fail('--note is not a curve buy of this token by this wallet', { noteTx, token })
|
|
358
|
+
noteTime = Number((await ctx.client.getBlock({ blockNumber: rc.blockNumber })).timestamp)
|
|
359
|
+
try {
|
|
360
|
+
const logs = await ctx.client.getLogs({ address: ctx.pad, event: TRADE_V1, args: { token, trader: wallet_ }, fromBlock: rc.blockNumber, toBlock: 'latest' })
|
|
361
|
+
soldSince = logs.some((l) => !l.args.isBuy)
|
|
362
|
+
} catch { /* unread: the server decides from its own index */ }
|
|
363
|
+
} else {
|
|
364
|
+
let found
|
|
365
|
+
try { found = await latestBuy(ctx, token, wallet_) } catch (e) {
|
|
366
|
+
fail('could not look up your latest buy of this token (RPC getLogs): pass --note <your buy tx>', { detail: e.shortMessage || e.message.split('\n')[0] })
|
|
367
|
+
}
|
|
368
|
+
if (!found) fail('no buy of this token by this wallet in the last ~20 minutes: pass --note <your buy note tx>', { token, wallet: wallet_ })
|
|
369
|
+
noteTx = found.tx
|
|
370
|
+
soldSince = found.soldSince
|
|
371
|
+
noteTime = Number((await ctx.client.getBlock({ blockNumber: found.block })).timestamp)
|
|
372
|
+
}
|
|
373
|
+
// a call is a buy that carries a note: a plain buy can't be found to follow, and its bond's pool could only burn
|
|
374
|
+
let input
|
|
375
|
+
try { input = (await ctx.client.getTransaction({ hash: noteTx })).input } catch (e) {
|
|
376
|
+
fail('could not read the note tx (RPC error)', { noteTx, detail: e.shortMessage || e.message.split('\n')[0], retry: 'same command again' })
|
|
377
|
+
}
|
|
378
|
+
if (!readNoteCommit(input)) fail('this buy carries no note (--note on the buy): nobody can follow it, so there is no call to bond', { noteTx, hint: 'buy with --note "<why>" first, then bond that buy within 10 minutes' })
|
|
379
|
+
const now = Number(block.timestamp)
|
|
380
|
+
const label = labelCheck({ holdAll: h.all, noteTime, now, duration, soldSince })
|
|
381
|
+
// pay: native BNB on a WBNB-quoted token (unless --use-wbnb), else approve the quote first
|
|
382
|
+
let value = 0n
|
|
383
|
+
if (same(quote, ctx.wbnb) && !flag('use-wbnb')) {
|
|
384
|
+
const native = await ctx.client.getBalance({ address: wallet_ })
|
|
385
|
+
if (native < amount + GAS_RESERVE) fail('not enough BNB for this bond (native BNB must also cover gas)', { haveBnb: formatUnits(native, 18), needBnb: formatUnits(amount, 18), hint: 'add --use-wbnb to pay from WBNB instead' })
|
|
386
|
+
value = amount
|
|
387
|
+
} else {
|
|
388
|
+
const pre = await fund(ctx, { me: wallet_, token: quote, need: amount, spender: ctx.callBond, sym, approveStep: 'approve-quote' }, rawOnly, summarize)
|
|
389
|
+
if (pre) return out(pre)
|
|
390
|
+
}
|
|
391
|
+
const args = [token, noteTx, amount, h.hold, BigInt(duration)]
|
|
392
|
+
const sim = await simulate(ctx, wallet_, 'post', args, value)
|
|
393
|
+
if (sim.failed) return out({ success: false, step: 'post', ...sim.failed })
|
|
394
|
+
const split = forfeitSplit(amount)
|
|
395
|
+
const q = (x) => formatUnits(x, dec)
|
|
396
|
+
return out(send('post', args, {
|
|
397
|
+
step: 'post', token, noteTx, bond: q(amount), quote: sym, hold: tokens(h.hold), balance: tokens(bal), holdsAll: h.all,
|
|
398
|
+
deadline: iso(now + duration), id: Number(sim.result), ...(noteTime != null && { postBefore: iso(noteTime + LABEL_WINDOW) }),
|
|
399
|
+
ifBroken: { reporter: q(split.reward), burnt: q(split.burned), followers: q(split.pool), callerGetsBack: '0' },
|
|
400
|
+
site: label.bonded
|
|
401
|
+
? { bonded: true, note: `gang.fun shows this call as bonded (有担保) if it lands by postBefore (10 minutes after the note), and if it is the note's first such bond` }
|
|
402
|
+
: { bonded: false, why: label.why, note: 'the bond still binds, but gang.fun will not show this call as bonded' },
|
|
403
|
+
note: `until settle, never let this wallet's balance of the token drop below hold: one sell, vault lock or transfer below it and anyone can report the bond — half burns, ${q(split.pool)} ${sym} goes to the note's followers, nothing comes back. From the deadline, settle (gang call-bond settle --token ${token}${net}, two steps 1 hour apart) before selling`,
|
|
404
|
+
}, value))
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// the other subcommands name one bond: --id, or --token for this wallet's running one
|
|
408
|
+
let id = idArg()
|
|
409
|
+
if (id == null) {
|
|
410
|
+
const tokenRaw = opt('token')
|
|
411
|
+
if (!isAddress(tokenRaw ?? '')) fail('--id <n> (or --token <addr> for your running bond) required')
|
|
412
|
+
id = await ctx.read(ctx.callBond, CALL_BOND_ABI, 'activeBondOf', [me(), getAddress(tokenRaw)])
|
|
413
|
+
if (id === 0n) fail('this wallet has no running call bond on that token; pass --id for a settled or reported one', { token: tokenRaw, wallet: me() })
|
|
414
|
+
}
|
|
415
|
+
const v = await bondView(ctx, id)
|
|
416
|
+
if (v.state === 'none') fail('no call bond with this id', { id: Number(id) })
|
|
417
|
+
const b = v.raw
|
|
418
|
+
const q = (x) => formatUnits(x, v.dec)
|
|
419
|
+
|
|
420
|
+
if (sub === 'status') {
|
|
421
|
+
let mine = null
|
|
422
|
+
if (v.state === 'reported' && v.root) {
|
|
423
|
+
try {
|
|
424
|
+
const acct = opt('account') || me()
|
|
425
|
+
let p = await proofFor(ctx, id, acct, opt('from-file'))
|
|
426
|
+
// a payout list that doesn't prove against the posted root is out of date: say so instead of showing it
|
|
427
|
+
if (p && rootFromProof(leafOf(ctx.callBond, chainId, id, acct, p.amount), p.proof) !== b.root) p = { stale: true }
|
|
428
|
+
const done = await ctx.read(ctx.callBond, CALL_BOND_ABI, 'claimed', [id, acct])
|
|
429
|
+
mine = p?.stale
|
|
430
|
+
? { account: acct, payout: null, claimed: done, note: 'the payout list does not match the posted root (out of date): try again later' }
|
|
431
|
+
: p
|
|
432
|
+
? { account: acct, payout: q(p.amount), claimed: done, ...(!done && { next: `gang call-bond claim --id ${id}${net}` }) }
|
|
433
|
+
: { account: acct, payout: testnet && !opt('from-file') ? null : '0', claimed: done, ...(testnet && !opt('from-file') && { note: 'gang.fun does not index testnet: pass --from-file <the settle script\'s JSON> to see this account\'s payout' }) }
|
|
434
|
+
} catch (e) { mine = { payout: null, note: `could not read the payout (${e.shortMessage || e.message.split('\n')[0]})` } }
|
|
435
|
+
}
|
|
436
|
+
const claimOpen = v.state === 'reported' && b.rootAt !== 0n && v.now >= Number(b.rootAt) + DISPUTE
|
|
437
|
+
const next = v.state === 'active'
|
|
438
|
+
? (v.violated ? `gang call-bond report --id ${id}${net}` : v.now >= Number(b.deadline) ? `gang call-bond settle --id ${id}${net}` : null)
|
|
439
|
+
: claimOpen ? `gang call-bond claim --id ${id}${net}${!b.remainderBurned && b.pool > b.total ? ` | gang call-bond burn --id ${id}${net}` : ''}` : null
|
|
440
|
+
return out({ success: true, chainId, callBondContract: ctx.callBond, ...pub(v), ...(mine && { yourPayout: mine }), ...(next && { next }) })
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (sub === 'report') {
|
|
444
|
+
if (v.state !== 'active') return fail(HINTS.NotActive, pub(v))
|
|
445
|
+
if (!v.violated) return fail(HINTS.NotViolated, { callerBalance: v.callerBalance, hold: v.hold })
|
|
446
|
+
const sim = await simulate(ctx, me(), 'report', [id])
|
|
447
|
+
if (sim.failed) return out({ success: false, step: 'report', ...sim.failed })
|
|
448
|
+
const self = same(me(), b.caller)
|
|
449
|
+
const s = forfeitSplit(b.amount, self)
|
|
450
|
+
return out(send('report', [id], {
|
|
451
|
+
step: 'report', id: Number(id), caller: b.caller, callerBalance: v.callerBalance, hold: v.hold, bond: v.amount, quote: v.quoteSymbol,
|
|
452
|
+
reward: q(s.reward), burnt: q(s.burned), followersPool: q(s.pool),
|
|
453
|
+
note: self ? 'the caller reporting itself gets no reward: that 1% burns too' : 'you get 1% of the bond; half burns now and the rest pays the note\'s followers by their loss once the settler posts a root (2 days for a veto, then claims)',
|
|
454
|
+
}))
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
if (sub === 'settle') {
|
|
458
|
+
if (v.state !== 'active') return fail(HINTS.NotActive, pub(v))
|
|
459
|
+
if (v.violated) return fail(HINTS.Violated, { callerBalance: v.callerBalance, hold: v.hold, next: `gang call-bond report --id ${id}${net}` })
|
|
460
|
+
if (v.now < Number(b.deadline)) return fail('too early: the bond runs until its deadline', { deadline: v.deadline })
|
|
461
|
+
const fn = b.settleAt === 0n ? 'requestSettle' : 'settle'
|
|
462
|
+
if (fn === 'settle' && v.now < Number(b.settleAt)) return fail('settle was asked for: it can run 1 hour after that', { settleAt: v.settleAt, secondsLeft: Number(b.settleAt) - v.now })
|
|
463
|
+
const sim = await simulate(ctx, me(), fn, [id])
|
|
464
|
+
if (sim.failed) return out({ success: false, step: fn, ...sim.failed })
|
|
465
|
+
return out(send(fn, [id], {
|
|
466
|
+
step: fn === 'requestSettle' ? 'request-settle' : 'settle', id: Number(id), caller: b.caller, refund: v.amount, quote: v.quoteSymbol,
|
|
467
|
+
note: fn === 'requestSettle'
|
|
468
|
+
? `step 1 of 2 (anyone may send it): settle can run 1 hour after this lands, if the caller still holds ${v.hold}; until then the bond can still be reported. Re-run this command then`
|
|
469
|
+
: 'the whole bond goes back to the caller (whoever sends this)',
|
|
470
|
+
}))
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
if (sub === 'claim') {
|
|
474
|
+
if (v.state !== 'reported') return fail('only a reported call bond pays followers', pub(v))
|
|
475
|
+
if (!v.root) return fail('no root posted yet: the settler posts one after the report (the payouts by loss)', { rootsFrom: v.rootsFrom })
|
|
476
|
+
if (v.now < Number(b.rootAt) + DISPUTE) return fail('the root is in its 2-day dispute window: claims open after it', { claimableAt: v.root.claimableAt })
|
|
477
|
+
const acct = getAddress(opt('account') || me())
|
|
478
|
+
if (same(acct, b.caller)) return fail(HINTS.NotFollower, { caller: b.caller })
|
|
479
|
+
if (await ctx.read(ctx.callBond, CALL_BOND_ABI, 'claimed', [id, acct])) return fail(HINTS.AlreadyClaimed, { account: acct })
|
|
480
|
+
let p
|
|
481
|
+
try { p = await proofFor(ctx, id, acct, opt('from-file')) } catch (e) { return fail(e.message) }
|
|
482
|
+
if (!p) return fail('this account has no payout in the posted root', { account: acct, id: Number(id), ...(testnet && { hint: 'gang.fun does not index testnet: pass --from-file <the settle script\'s JSON>' }) })
|
|
483
|
+
const leaf = leafOf(ctx.callBond, chainId, id, acct, p.amount)
|
|
484
|
+
if (rootFromProof(leaf, p.proof) !== b.root) return fail('the proof does not match the posted root (the payout list is out of date or wrong)', { account: acct, root: b.root })
|
|
485
|
+
const sim = await simulate(ctx, me(), 'claim', [id, acct, p.amount, p.proof])
|
|
486
|
+
if (sim.failed) return out({ success: false, step: 'claim', ...sim.failed })
|
|
487
|
+
return out(send('claim', [id, acct, p.amount, p.proof], {
|
|
488
|
+
step: 'claim', id: Number(id), account: acct, payout: q(p.amount), quote: v.quoteSymbol,
|
|
489
|
+
note: same(acct, me()) ? 'your payout as a follower of the broken call' : 'anyone may send a claim; the payout goes to the account, not to the sender',
|
|
490
|
+
}))
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (sub === 'burn') {
|
|
494
|
+
// the leftovers of a reported bond: the part a live root doesn't pay out, or all that's left once nothing more can be paid
|
|
495
|
+
if (v.state !== 'reported') return fail('only a reported call bond has leftovers to burn', pub(v))
|
|
496
|
+
const fn = v.root && v.now >= Number(b.rootAt) + DISPUTE && !b.remainderBurned && b.pool > b.total ? 'burnRemainder' : 'burnUnpaid'
|
|
497
|
+
const sim = await simulate(ctx, me(), fn, [id])
|
|
498
|
+
if (sim.failed) return out({ success: false, step: fn, ...sim.failed })
|
|
499
|
+
return out(send(fn, [id], { step: fn === 'burnRemainder' ? 'burn-remainder' : 'burn-unpaid', id: Number(id), note: 'anyone may send it: the quote goes to 0xdead' }))
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Before a sell (curve or pool) of `token` by `me`: is it this wallet's running call bond, and does the sell leave less
|
|
505
|
+
* than its hold? → null (no bond / fine, nothing to add) | { info } | { refuse }. ctx is a 3.0 v3 ctx (pad, client, read).
|
|
506
|
+
* --break-call-bond (its own flag: --break-bond is GangBond's) lets the sell through with the warning. Never lets an
|
|
507
|
+
* unread bond pass.
|
|
508
|
+
*/
|
|
509
|
+
export async function callBondGuard(ctx, { token, me, amount, testnet, breakBond }) {
|
|
510
|
+
const addr = callBondAddress(testnet)
|
|
511
|
+
const pad3 = gangGens(testnet).find((g) => g.gen === PAD3_GEN)?.pad
|
|
512
|
+
if (!addr || !same(ctx.pad, pad3)) return null
|
|
513
|
+
let id, b, bal
|
|
514
|
+
try {
|
|
515
|
+
id = await ctx.read(addr, CALL_BOND_ABI, 'activeBondOf', [me, token])
|
|
516
|
+
if (id === 0n) return null
|
|
517
|
+
;[b, bal] = await Promise.all([ctx.read(addr, CALL_BOND_ABI, 'bondOf', [id]), ctx.read(token, ERC20_ABI, 'balanceOf', [me])])
|
|
518
|
+
} catch (e) {
|
|
519
|
+
if (breakBond) return null
|
|
520
|
+
return { refuse: { error: 'cannot read your call bond (GangCallBond), so the sell is not checked against it', callBondContract: addr, detail: e.shortMessage || e.message.split('\n')[0], hint: 're-run; --break-call-bond skips the check' } }
|
|
521
|
+
}
|
|
522
|
+
const after = bal > amount ? bal - amount : 0n
|
|
523
|
+
const base = { callBondId: Number(id), callBondContract: addr, hold: tokens(b.hold), balanceBefore: tokens(bal), balanceAfter: tokens(after), deadline: iso(b.deadline) }
|
|
524
|
+
if (after >= b.hold) return { info: { callBondCheck: { ...base, headroomAfter: tokens(after - b.hold) } } }
|
|
525
|
+
const net = testnet ? ' --testnet' : ''
|
|
526
|
+
let now = Math.floor(Date.now() / 1000)
|
|
527
|
+
try { now = Number((await ctx.client.getBlock()).timestamp) } catch { /* the local clock is close enough for a hint */ }
|
|
528
|
+
const settleHint = now >= Number(b.deadline) ? ` It is past its deadline: settle it first (gang call-bond settle --id ${id}${net}, two steps 1 hour apart), then sell.` : ''
|
|
529
|
+
const consequence = 'anyone can report it — the reporter takes 1%, half burns and the rest pays your note\'s followers. Nothing of it comes back'
|
|
530
|
+
const warning = bal < b.hold
|
|
531
|
+
? `your call bond #${id} is already broken: you hold ${tokens(bal)} tokens, below its hold (${tokens(b.hold)}), so ${consequence}. Selling more does not change that; buying back to the hold before anyone reports does`
|
|
532
|
+
: `this sell leaves ${tokens(after)} tokens, below the hold of your call bond #${id} (${tokens(b.hold)}): ${consequence}.${settleHint}`
|
|
533
|
+
if (!breakBond) return { refuse: { error: warning, ...base, maxSellKeepingBond: tokens(bal > b.hold ? bal - b.hold : 0n), hint: 'sell at most maxSellKeepingBond, or add --break-call-bond once the user accepts losing the call bond' } }
|
|
534
|
+
return { info: { callBondCheck: { ...base, warning, brokeBond: true } } }
|
|
535
|
+
}
|
package/src/capabilities.js
CHANGED
|
@@ -27,7 +27,7 @@ const ACCESS = {
|
|
|
27
27
|
const TOOL_SINCE = { gang_help: '0.17.2', gang_trending: '0.24.0', gang_portfolio: '0.17.6' }
|
|
28
28
|
const TOOL_KIND = {
|
|
29
29
|
gang_buy: ['preview', 'medium'], gang_follow: ['preview', 'medium'],
|
|
30
|
-
gang_sell: ['preview', 'medium', { breakBond: { risk: 'high', why: 'gives up the whole bond' }, confirmOut: { risk: 'high', why: 'ends the holder reward (Mint Flywheel: until the next mint)' } }],
|
|
30
|
+
gang_sell: ['preview', 'medium', { breakBond: { risk: 'high', why: 'gives up the whole bond' }, breakCallBond: { risk: 'high', why: 'gives up the whole call bond' }, confirmOut: { risk: 'high', why: 'ends the holder reward (Mint Flywheel: until the next mint)' } }],
|
|
31
31
|
gang_watch: ['read', 'none', { webhook: { access: 'publish', risk: 'low', needsUserConfirmation: true, why: 'POSTs each event to that URL: only a URL the user gave' } }],
|
|
32
32
|
gang_execute: ['execute', 'high'],
|
|
33
33
|
gang_tx: ['publish', 'low'],
|
|
@@ -106,6 +106,13 @@ export const COMMANDS = [
|
|
|
106
106
|
c('promote bind', 'preview', 'low', '0.34.0', 'Anyone: bind the module to its token before graduation (a launch does it)'),
|
|
107
107
|
c('promote reclaim', 'preview', 'high', '0.34.0', "Dev: after 30 days of settler silence, take what no root allocated; closes the module for good"),
|
|
108
108
|
c('promote release-dev', 'preview', 'low', '0.34.0', 'Dev: send what failed pushes left in the module'),
|
|
109
|
+
c('call-bond post', 'preview', 'high', '0.37.0', 'Bond your own call (a buy note on a 3.0 curve token): any sell below the hold before settle loses all of it, half burnt, the rest to its followers'),
|
|
110
|
+
c('call-bond status', 'read', 'none', '0.37.0', "A call bond's state, the caller's balance against its hold, the followers' root and an account's payout"),
|
|
111
|
+
c('call-bond report', 'preview', 'low', '0.37.0', 'Anyone: report a caller below its hold; 1% of the bond is the reward'),
|
|
112
|
+
c('call-bond settle', 'preview', 'low', '0.37.0', 'Anyone: give the bond back after the deadline while the hold is kept, in two steps'),
|
|
113
|
+
c('call-bond claim', 'preview', 'low', '0.37.0', "Anyone: pay a follower its share of a broken call's bond (the posted root)"),
|
|
114
|
+
c('call-bond burn', 'preview', 'low', '0.37.0', "Anyone: send a broken call's unpaid leftovers to 0xdead"),
|
|
115
|
+
c('call-bond tx', 'read', 'none', '0.37.0', 'Decode GangCallBond events of a tx'),
|
|
109
116
|
]
|
|
110
117
|
|
|
111
118
|
/** Text anyone can write on-chain or in a note: data for the user to read, never instructions to follow. */
|
package/src/fair.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createPublicClient, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseEther, parseUnits, isAddress, zeroAddress } from 'viem'
|
|
2
|
+
import { VANITY_ABI, vanityCreate, vanityDeployer } from './vanity.js'
|
|
2
3
|
import { bawAddress } from './baw.js'
|
|
3
4
|
import { defaultRefPool, dividendOf, fundingStep as fund, parseAmount, parseIntIn, parseNum, poolSellQuote, POOL_SELL_HINT, revertOf as revertIn, ROUTER_ABI, ROUTER_HINTS, routerDeadline, step, swapBackState, units, viaRouter, GAS_RESERVE } from './steps.js'
|
|
4
5
|
import { API } from './discover.js'
|
|
@@ -125,7 +126,7 @@ export function walletFor(ctx, from) {
|
|
|
125
126
|
}
|
|
126
127
|
|
|
127
128
|
/** Revert name (+ BadConfig reason) of a failed eth_call, or null when it was the RPC. */
|
|
128
|
-
const revertOf = (e) => revertIn(e, [PAD_ABI, ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
|
|
129
|
+
const revertOf = (e) => revertIn(e, [PAD_ABI, VANITY_ABI, ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
|
|
129
130
|
|
|
130
131
|
/** Dry-run `data` from `from`; null when it would pass. */
|
|
131
132
|
async function dryRun(ctx, from, to, data, value = 0n) {
|
|
@@ -329,15 +330,21 @@ export async function runFair(sub, { opt, flag, out, fail, summarize, resolveLog
|
|
|
329
330
|
const createData = (logoURI, metaURI) => encodeFunctionData({
|
|
330
331
|
abi: PAD_ABI, functionName: 'create', args: [name, symbol, logoURI, metaURI, quote, refPool, cfg, BigInt(devShares)],
|
|
331
332
|
})
|
|
333
|
+
const vanity = await vanityDeployer(ctx)
|
|
334
|
+
const handler = vanity ? await ctx.read(ctx.pad, PAD_ABI, 'taxHandler') : zeroAddress
|
|
335
|
+
const prepareCreate = (logoURI, metaURI) => vanityCreate(ctx, me, createData(logoURI, metaURI), {
|
|
336
|
+
args: [name, symbol, metaURI, handler, 100, 100, true],
|
|
337
|
+
})
|
|
332
338
|
// the logo / metadata strings never decide a revert: dry-run without them, so a create that would fail uploads nothing
|
|
333
|
-
const dry = await dryRun(ctx, me, ctx.pad,
|
|
339
|
+
const dry = await dryRun(ctx, me, ctx.pad, (await prepareCreate('', '')).data)
|
|
334
340
|
if (dry) return out({ success: false, step: 'create', ...dry })
|
|
335
341
|
const logo = await resolveLogo()
|
|
336
342
|
const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
|
|
337
|
-
const
|
|
338
|
-
return out(notes.step(ctx, { from: me, to: ctx.pad, data }, {
|
|
343
|
+
const launch = await prepareCreate(logo.logoURI, meta.metaURI)
|
|
344
|
+
return out(notes.step(ctx, { from: me, to: ctx.pad, data: launch.data }, {
|
|
339
345
|
step: 'create', chainId: Number(ctx.chainId), name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
|
|
340
346
|
metaURI: meta.metaURI, metadata: meta.metadata, quote: sym || quote,
|
|
347
|
+
...(launch.token && { tokenIfNext: launch.token, addressSuffix: 'abcd' }),
|
|
341
348
|
raise: await units(ctx, quote, raiseQuote), sharePrice: await units(ctx, quote, sharePrice),
|
|
342
349
|
capShares: cfg.capBps * 2, minWallets: Math.ceil(10_000 / (cfg.capBps * 2)), holdPct, mintFeePct, exitFeePct, devShares,
|
|
343
350
|
devCost: await units(ctx, quote, need),
|
package/src/flags.js
CHANGED
|
@@ -24,11 +24,11 @@ export const CREATE_ACCEPTS = new Set([
|
|
|
24
24
|
// every flag a buy's code reads, whatever the token's kind: a buy refuses the rest, since a misspelled --promoter would fall
|
|
25
25
|
// through to a plain first buy, which uses up the wallet's only chance to bind
|
|
26
26
|
export const BUY_ACCEPTS = new Set([
|
|
27
|
-
'agent', 'all', 'amount', 'bnb', 'board', 'break-bond', 'buy-tax', 'calldata', 'cap', 'conf', 'confirm-out',
|
|
27
|
+
'agent', 'all', 'amount', 'bnb', 'board', 'break-bond', 'break-call-bond', 'buy-tax', 'calldata', 'cap', 'conf', 'confirm-out',
|
|
28
28
|
'description', 'dev-buy', 'dev-cut', 'dev-shares', 'dividend', 'events', 'exit-fee', 'fair', 'file', 'file-logo',
|
|
29
29
|
'fly', 'follow', 'from', 'grad', 'guard', 'hash', 'hold', 'hours', 'include-graduated', 'interval',
|
|
30
30
|
'keep-logo-uri', 'kind', 'limit', 'logo', 'logo-file', 'logo-uri', 'max-age', 'max-events', 'min-hit', 'min-pct',
|
|
31
|
-
'min-shares', 'mint-fee', 'name', 'no-post-mint', 'note', 'notes', 'pair', 'pair-or-quote', 'path', 'pay-bnb',
|
|
31
|
+
'min-shares', 'mint-fee', 'name', 'no-post-mint', 'no-promoter', 'note', 'notes', 'pair', 'pair-or-quote', 'path', 'pay-bnb',
|
|
32
32
|
'pending', 'poll', 'post-mint', 'preset', 'promoter', 'quote', 'raise', 'recipient', 'ref', 'ref-pool',
|
|
33
33
|
'request-id', 'reveal-after', 'sell-tax', 'settle-first', 'shares', 'slippage', 'sort', 'status', 'symbol',
|
|
34
34
|
'taxed', 'testnet', 'tier', 'timeout', 'to-bnb', 'token', 'track', 'twap-window', 'twitter', 'url', 'use-quote',
|