@gangfun/cli 0.17.7 → 0.18.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 +19 -6
- package/README.zh-CN.md +18 -5
- package/package.json +1 -1
- package/src/baw.js +30 -5
- package/src/discover.js +21 -11
- package/src/fly.js +932 -0
- package/src/index.js +127 -29
- package/src/mcp.js +9 -8
- package/src/pool.js +15 -7
- package/src/portfolio.js +30 -5
- package/src/steps.js +22 -5
package/src/fly.js
ADDED
|
@@ -0,0 +1,932 @@
|
|
|
1
|
+
import { createPublicClient, parseAbi, encodeFunctionData, decodeEventLog, formatUnits, parseEther, parseUnits, isAddress, zeroAddress } from 'viem'
|
|
2
|
+
import { defaultRefPool, dividendOf, VAULT_ABI, fundingStep as fund, parseAmount, parseIntIn, parseNum, poolSellQuote, POOL_SELL_HINT, revertOf as revertIn, roomyGas, ROUTER_ABI, ROUTER_HINTS, step, swapBackState, units, GAS_RESERVE } from './steps.js'
|
|
3
|
+
import { API, get as apiGet } from './discover.js'
|
|
4
|
+
import { walletFor } from './fair.js'
|
|
5
|
+
import { MERGED_ERRORS_ABI, MERGED_HINTS, padNets, rpcTransport } from './gangpad.js'
|
|
6
|
+
import { poolPayBnb, poolTrade } from './pool.js'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `gang fly …` — 持续打新 (continuous mint, track `fly`): GangFlywheelPad, its own pad (kind 3) beside GangLaunchpad.
|
|
10
|
+
* Before launch: 10,000 shares at one price (sale.basePrice), a quota per wallet (baseQuota + invite bonus), sell-back
|
|
11
|
+
* at the mint price less an exit fee. The sale fills (or the creator opens it early at ≥ 30%), then anyone launches it
|
|
12
|
+
* `launchDelay` later: a PancakeSwap pool at the mint price, with a protection window (Agent ID + a per-wallet buy cap).
|
|
13
|
+
* After launch (sale.postMint) minting goes on at the tier price: the money goes into the pool (part of it buys), the
|
|
14
|
+
* tokens are minted. Pool tax: buy 1%, sell 1–2%; holders who minted share part of it (the hold line, `holdBps`).
|
|
15
|
+
* No GangBond and no buy-back splitter on these tokens (phase 1).
|
|
16
|
+
* Contracts: gang-launchpad src/flywheel (GangFlywheelPad, FlywheelTaxHandler, GangMintToken; issue #75).
|
|
17
|
+
* Env: GANG_FLY_PAD / GANG_TESTNET_FLY_PAD override the pad; the RPCs and the GangRouter (pool trades) are GangLaunchpad's.
|
|
18
|
+
*/
|
|
19
|
+
export const FLY_PADS = {
|
|
20
|
+
mainnet: { pad: '0x631e66560F4FAE4e486B65349edE48189E48B029', startBlock: 130634782n },
|
|
21
|
+
// testnet set 2 (2026-10-30, after the pre-mainnet audit fixes)
|
|
22
|
+
testnet: { pad: '0xD6482850aCAC74BA889804931Fc797294777951c', startBlock: 139749672n },
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const CFG = '(uint256 raiseBnb, uint16 baseQuota, uint8 inviteBonus, uint8 maxPerTx, uint16 holdBps, uint16 mintFeeBps, uint16 exitFeeBps, uint16 devCutBps, uint16 buyBps, uint16 sellTaxBps, uint32 launchDelay, uint32 window, uint8 windowCapMul, bool postMint, uint8 tierMode, uint16 stepBps, uint32 stepShares, uint16 maxMulX100, uint16 supplyCapMul)'
|
|
26
|
+
const SALE = '(address creator, address quote, address gate, address pair, uint128 basePrice, uint64 totalShares, uint64 filledAt, uint64 progressAt, uint16 sold, uint16 creatorShares, uint16 markSold, uint16 baseQuota, uint16 holdBps, uint16 mintFeeBps, uint16 exitFeeBps, uint16 devCutBps, uint16 buyBps, uint32 launchDelay, uint32 window, uint8 inviteBonus, uint8 maxPerTx, uint8 windowCapMul, uint8 tierMode, uint16 stepBps, uint32 stepShares, uint16 maxMulX100, bool postMint, bool launched)'
|
|
27
|
+
export const FLY_PAD_ABI = parseAbi([
|
|
28
|
+
`function create(string[4] text, address quote, address refPool, ${CFG} cfg, uint256 devShares) returns (address token)`,
|
|
29
|
+
`function checkConfig(${CFG} cfg, uint256 devShares) view returns (bool ok, string reason)`,
|
|
30
|
+
'function mint(address token, uint256 shares, uint256 minShares, address referrer) returns (uint256 spent)',
|
|
31
|
+
'function mintWithBnb(address token, uint256 shares, uint256 minShares, address referrer) payable returns (uint256 spent)',
|
|
32
|
+
'function withdraw(address token, uint256 shares, uint256 minPayout) returns (uint256 payout)',
|
|
33
|
+
'function openEarly(address token)',
|
|
34
|
+
'function launch(address token)',
|
|
35
|
+
'function mintPost(address token, uint256 shares, uint256 minTokensOut, uint256 maxSpent, address referrer) returns (uint256 tokensOut, uint256 spent)',
|
|
36
|
+
'function mintPostWithBnb(address token, uint256 shares, uint256 minTokensOut, address referrer) payable returns (uint256 tokensOut, uint256 spent)',
|
|
37
|
+
'function claimDev(address token) returns (uint256 amount)',
|
|
38
|
+
`function sales(address token) view returns (${SALE})`,
|
|
39
|
+
'function accounts(address token, address user) view returns (uint32 preShares, uint32 used, uint32 bonus, bool minted, uint64 windowStart, uint128 windowSpent, uint256 baseline)',
|
|
40
|
+
'function quotaLeft(address token, address user) view returns (uint256)',
|
|
41
|
+
'function sharePrice(address token, uint256 shares) view returns (uint256)',
|
|
42
|
+
'function previewMint(address token, address user, uint256 shares) view returns (uint256 accepted, uint256 cost, uint256 fee)',
|
|
43
|
+
'function previewMintPost(address token, address user, uint256 shares) view returns (uint256 accepted, uint256 paid, uint256 fee, uint256 tokensOut, bool ok)',
|
|
44
|
+
'function previewWithdraw(address token, address user, uint256 shares) view returns (uint256 payout, uint256 fee)',
|
|
45
|
+
'function prices(address token) view returns (uint256 spot, uint256 blockStart, uint256 high, uint256 average)',
|
|
46
|
+
'function exitFeeBpsOf(address token) view returns (uint256)',
|
|
47
|
+
'function owedDev(address token) view returns (uint256)',
|
|
48
|
+
'function kindOf(address token) view returns (uint8)',
|
|
49
|
+
'function isAgent(address account) view returns (bool)',
|
|
50
|
+
'function migrator() view returns (address)',
|
|
51
|
+
'function taxHandler() view returns (address)',
|
|
52
|
+
'function dividendVault() view returns (address)',
|
|
53
|
+
'function agentGateEnabled() view returns (bool)',
|
|
54
|
+
'function tokenCount() view returns (uint256)',
|
|
55
|
+
'function allTokens(uint256) view returns (address)',
|
|
56
|
+
'function logoURIOf(address token) view returns (string)',
|
|
57
|
+
'error ZeroAddress()', 'error ZeroAmount()', 'error BadAmount()', 'error BadConfig(string reason)', 'error UnknownToken()',
|
|
58
|
+
'error NotAgent()', 'error NotMinting()', 'error NotLaunched()', 'error NotFilled()', 'error TooEarly()', 'error OnlyCreator()',
|
|
59
|
+
'error Slippage()', 'error PriceBelowAverage()', 'error PriceBelowRecentHigh()', 'error PriceAbovePool()', 'error PaceExceeded()',
|
|
60
|
+
'error PostMintOff()', 'error MigratorNotSet()', 'error VaultFloorTooHigh()', 'error PriceTooSmall()', 'error NothingOwed()',
|
|
61
|
+
'error BnbNotQuote()', 'error BnbShort()', 'error OnlyRouter()', 'error TraderNotOrigin()', 'error RouterNeedsGate()',
|
|
62
|
+
'error TooFewShares()', 'error QuoteNotAllowed()', 'error RefPoolRequired()', 'error NoBridgePool()', 'error BridgeNotWbnb()',
|
|
63
|
+
'error PoolNotFactory()', 'error QuoteNotInPool()', 'error PoolNoLiquidity()', 'error ThinReferencePool()', 'error NotContract()',
|
|
64
|
+
'error UnknownPoolType()', 'error V3FactoryNotSet()', 'error FeeOnTransferQuote()', 'error CapExceeded()',
|
|
65
|
+
`event Created(address indexed token, address indexed creator, string name, string symbol, string logoURI, address quote, uint256 basePrice, ${CFG} cfg)`,
|
|
66
|
+
'event Minted(address indexed token, address indexed trader, uint256 shares, uint256 cost, uint256 fee, uint256 sold)',
|
|
67
|
+
'event Withdrawn(address indexed token, address indexed trader, uint256 shares, uint256 payout, uint256 fee)',
|
|
68
|
+
'event Referred(address indexed token, address indexed referrer, address indexed invitee, uint256 bonus)',
|
|
69
|
+
'event Filled(address indexed token, uint256 sold, bool early)',
|
|
70
|
+
'event Launched(address indexed token, address pair, uint256 poolTokens, uint256 poolQuote, uint256 devCut)',
|
|
71
|
+
'event PostMinted(address indexed token, address indexed trader, uint256 shares, uint256 paid, uint256 fee, uint256 devCut, uint256 tokensOut, uint256 boughtQuote)',
|
|
72
|
+
'event DevPaid(address indexed token, address indexed creator, uint256 amount)',
|
|
73
|
+
'event DevOwed(address indexed token, address indexed creator, uint256 amount)',
|
|
74
|
+
'event FeeOwed(address indexed quote, uint256 amount)',
|
|
75
|
+
'event FeesFlushed(address indexed quote, uint256 amount)',
|
|
76
|
+
'event ShareWriteFailed(address indexed token, address indexed user, uint256 share)',
|
|
77
|
+
])
|
|
78
|
+
export const FLY_HANDLER_ABI = parseAbi([
|
|
79
|
+
'function protectionOf(address token) view returns (uint64 until, address gate, uint256 cap)',
|
|
80
|
+
'function boughtInWindow(address token, address user) view returns (uint256)',
|
|
81
|
+
'function isOut(address token, address user) view returns (bool)',
|
|
82
|
+
'function eligibleShare(address token, address user) view returns (uint256)',
|
|
83
|
+
'function owedOf(address token) view returns (uint256)',
|
|
84
|
+
'function release(address token) returns (uint256 amount)',
|
|
85
|
+
'error ProtectionNotAgent()', 'error ProtectionCapExceeded()', 'error PriceBelowReference()', 'error NothingOwed()',
|
|
86
|
+
'error SellDuringFlashSwap()', 'error OutOfGas()',
|
|
87
|
+
'event Launched(address indexed token, uint256 protectedUntil, address gate, uint256 cap, uint256 launchPrice)',
|
|
88
|
+
'event Disqualified(address indexed token, address indexed user, uint256 balance, uint256 baseline)',
|
|
89
|
+
'event Requalified(address indexed token, address indexed user)',
|
|
90
|
+
'event TaxAccrued(address indexed token, address indexed from, address indexed to, uint256 taxAmount, uint256 accrued)',
|
|
91
|
+
'event TaxChunkSold(address indexed token, uint256 taxTokens, uint256 quoteOut, uint256 holderUnits, bool swapBack)',
|
|
92
|
+
'event TaxDistributed(address indexed token, uint256 taxTokens, uint256 quoteOut, uint256 toHolders, uint256 toPlatform, uint256 toDev)',
|
|
93
|
+
'event TaxPaid(address indexed token, address indexed recipient, address indexed quote, uint256 amount)',
|
|
94
|
+
'event TaxOwed(address indexed token, address indexed recipient, address indexed quote, uint256 amount)',
|
|
95
|
+
'event PlatformOwed(address indexed quote, uint256 amount)',
|
|
96
|
+
'event PlatformFlushed(address indexed quote, uint256 amount)',
|
|
97
|
+
'event HolderConversionDeferred(address indexed token, uint256 units, uint256 quote)',
|
|
98
|
+
'event ShareWriteFailed(address indexed token, address indexed user, uint256 share)',
|
|
99
|
+
])
|
|
100
|
+
const TOKEN_ABI = parseAbi([
|
|
101
|
+
'function balanceOf(address) view returns (uint256)',
|
|
102
|
+
'function symbol() view returns (string)',
|
|
103
|
+
'function totalSupply() view returns (uint256)',
|
|
104
|
+
'function maxSupply() view returns (uint256)',
|
|
105
|
+
'function mintRoom() view returns (uint256)',
|
|
106
|
+
'function buyTaxBps() view returns (uint16)',
|
|
107
|
+
'function sellTaxBps() view returns (uint16)',
|
|
108
|
+
'error CapExceeded()', 'error TransfersLocked()',
|
|
109
|
+
])
|
|
110
|
+
const ERC721_ABI = parseAbi(['function balanceOf(address) view returns (uint256)'])
|
|
111
|
+
const PAIR_ABI = parseAbi(['function getReserves() view returns (uint112, uint112, uint32)', 'function token0() view returns (address)'])
|
|
112
|
+
const DEX_ABI = parseAbi(['function getAmountsOut(uint256 amountIn, address[] path) view returns (uint256[] amounts)'])
|
|
113
|
+
const GANG_ROUTER_VIEW = parseAbi(['function pancakeRouter() view returns (address)'])
|
|
114
|
+
|
|
115
|
+
/** What `gang tx` decodes a 持续打新 tx's logs with (the pad, the tax handler, the holder-reward vault). */
|
|
116
|
+
export const FLY_EVENT_ABIS = [FLY_PAD_ABI, FLY_HANDLER_ABI, VAULT_ABI]
|
|
117
|
+
|
|
118
|
+
// platform constants (FlywheelLogic): the pad's own numbers, fixed in the contract
|
|
119
|
+
const TOTAL_SHARES = 10_000
|
|
120
|
+
const TOKENS_PER_SHARE = 100_000n * 10n ** 18n
|
|
121
|
+
const EARLY_OPEN_SHARES = 3_000
|
|
122
|
+
const LAUNCH_GRACE = 7 * 86_400
|
|
123
|
+
const STALE_AFTER = 7 * 86_400
|
|
124
|
+
const BUY_TAX_PCT = 1
|
|
125
|
+
const Q112 = 1n << 112n
|
|
126
|
+
const TIERS = ['flat', 'standard', 'linear']
|
|
127
|
+
// gas-limit floors (roomyGas; alone when a pending approve leaves nothing to estimate): a pool trade or post-launch mint
|
|
128
|
+
// can be the token's first pool touch in its block, which costs more than an estimate made against the block before.
|
|
129
|
+
// Chapel fork: a pool buy at its bare estimate (431k) ran out of gas inside the holder-share sync and used 428k with
|
|
130
|
+
// room; a sell that also sold a tax chunk ran out at 750k and used 661k with room (estimate 755k)
|
|
131
|
+
const GAS_FLOOR = { buy: 750_000n, sell: 1_200_000n, mintPost: 900_000n, launch: 3_500_000n }
|
|
132
|
+
const GAS_NOTE = 'gas limit set with room: a hot token\'s first trade in a block costs more than the estimate shows'
|
|
133
|
+
|
|
134
|
+
const HINTS = {
|
|
135
|
+
BadConfig: 'a setting is out of bounds: see reason',
|
|
136
|
+
NotAgent: 'this wallet holds no Agent ID; 持续打新 is Agent-only',
|
|
137
|
+
NotMinting: 'the sale no longer takes pre-launch mints / sell-backs (filled, opened early or launched): gang info shows its state',
|
|
138
|
+
NotLaunched: 'the token has not launched yet',
|
|
139
|
+
NotFilled: 'the sale has not filled (or been opened early) yet: nothing to launch',
|
|
140
|
+
TooEarly: 'too early: launch waits launchDelay after the fill; open-early needs at least 30% (3,000 shares) sold',
|
|
141
|
+
OnlyCreator: 'only the creator can open the sale early',
|
|
142
|
+
Slippage: 'fewer shares / tokens than the minimum: the sale or the price moved; re-run to re-quote',
|
|
143
|
+
PriceBelowAverage: 'the pool price is more than 10% below its 30-minute average: post-launch mints pause until it recovers',
|
|
144
|
+
PriceBelowRecentHigh: 'the pool price is more than 10% below its recent high: post-launch mints pause until it recovers (the high decays 0.5% a minute)',
|
|
145
|
+
PriceAbovePool: 'the mint price is more than 10% above the pool price right now (the pool just dropped): try again shortly',
|
|
146
|
+
PaceExceeded: 'this wallet minted too much too fast: recent post-launch mints (decaying over 30 minutes) plus this one may be at most 2% of the pool\'s quote side; mint fewer shares or wait',
|
|
147
|
+
PostMintOff: 'this sale has no post-launch minting: trade the token in the pool (gang buy / gang sell)',
|
|
148
|
+
MigratorNotSet: 'the 持续打新 pad is not open on this network yet',
|
|
149
|
+
BnbShort: 'the BNB sent does not cover the mint (the tier price moved up): re-run to re-quote',
|
|
150
|
+
BnbNotQuote: 'this sale is not WBNB-quoted: pay in its quote (leave out BNB payment)',
|
|
151
|
+
TooFewShares: 'fewer than 3,000 shares are still held 7 days after the fill: the sale can no longer launch, only refund (gang withdraw)',
|
|
152
|
+
NothingOwed: 'nothing is owed',
|
|
153
|
+
CapExceeded: 'the token\'s supply cap is reached: post-launch minting is over, trade in the pool',
|
|
154
|
+
ProtectionNotAgent: 'launch protection: only Agent ID holders can buy from the pool until it ends (gang info: protection.until)',
|
|
155
|
+
ProtectionCapExceeded: 'launch protection: this buy goes past the wallet\'s protected buy cap (gang status: protection.capLeftTokens)',
|
|
156
|
+
VaultFloorTooHigh: 'the platform\'s dividend vault requires a larger holding than this pad allows, so no sale can be created right now; ask gang to fix the vault setting',
|
|
157
|
+
QuoteNotAllowed: '--quote must be WBNB or a listed 18-decimal ERC-20 (leave it out to use WBNB)',
|
|
158
|
+
RefPoolRequired: 'this quote needs --ref-pool (a Pancake pool pricing it)',
|
|
159
|
+
PriceTooSmall: 'the raise in this quote is too small to split into 10,000 shares',
|
|
160
|
+
FeeOnTransferQuote: 'the quote token takes a fee on transfer; it cannot be used',
|
|
161
|
+
RouterNeedsGate: 'this sale has no Agent gate, so router entries are off',
|
|
162
|
+
}
|
|
163
|
+
const revertOf = (e) => revertIn(e, [FLY_PAD_ABI, FLY_HANDLER_ABI, TOKEN_ABI, ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
|
|
164
|
+
|
|
165
|
+
/** Network settings: GangLaunchpad's chain, RPCs, WBNB and GangRouter (pool trades), with the fly pad. */
|
|
166
|
+
export function flyCtx(testnet) {
|
|
167
|
+
const net = padNets('v3')[testnet ? 'testnet' : 'mainnet']
|
|
168
|
+
const fly = FLY_PADS[testnet ? 'testnet' : 'mainnet']
|
|
169
|
+
const pad = process.env[testnet ? 'GANG_TESTNET_FLY_PAD' : 'GANG_FLY_PAD'] || fly.pad
|
|
170
|
+
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
171
|
+
return {
|
|
172
|
+
...net, pad, startBlock: fly.startBlock, client,
|
|
173
|
+
read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }),
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** true when `token` is a 持续打新 token on this pad; null on an RPC error. */
|
|
178
|
+
export async function isFlyToken(ctx, token) {
|
|
179
|
+
try {
|
|
180
|
+
return Number(await ctx.read(ctx.pad, FLY_PAD_ABI, 'kindOf', [token])) === 3
|
|
181
|
+
} catch {
|
|
182
|
+
return null
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** The pad takes creates only once its migrator is set (mainnet: when the Safe opens it). */
|
|
187
|
+
export async function padOpen(ctx) {
|
|
188
|
+
return (await ctx.read(ctx.pad, FLY_PAD_ABI, 'migrator')) !== zeroAddress
|
|
189
|
+
}
|
|
190
|
+
const CLOSED = 'the 持续打新 (continuous mint) pad on BSC mainnet is not open yet: it opens once testing on BSC testnet is done. Use --testnet to try it there'
|
|
191
|
+
|
|
192
|
+
const symbolOf = async (ctx, token) => { try { return await ctx.read(token, TOKEN_ABI, 'symbol') } catch { return null } }
|
|
193
|
+
const pct = (bps) => Number(bps) / 100
|
|
194
|
+
/** The fewest tokens that keep a wallet in: the handler puts it out when balance × 10,000 < baseline × holdBps, so round up. */
|
|
195
|
+
const holdLine = (baseline, holdPct) => (baseline * BigInt(Math.round(holdPct * 100)) + 9_999n) / 10_000n
|
|
196
|
+
const minOf = (x, slippagePct) => (x * BigInt(Math.round((100 - slippagePct) * 100))) / 10_000n
|
|
197
|
+
/** The chain's time (the latest block's timestamp, read once per command): the rules are judged by it, not this machine's clock. */
|
|
198
|
+
const chainNow = (ctx) => (ctx.nowP ??= ctx.client.getBlock().then((b) => Number(b.timestamp), () => Math.floor(Date.now() / 1000)))
|
|
199
|
+
const iso = (t) => (t ? new Date(Number(t) * 1000).toISOString() : null)
|
|
200
|
+
/** A Q112 price (quote wei per token wei × 2^112) → quote per token, as a decimal string. */
|
|
201
|
+
const q112 = (p) => formatUnits((p * 10n ** 18n) / Q112, 18)
|
|
202
|
+
const same = (a, b) => String(a).toLowerCase() === String(b).toLowerCase()
|
|
203
|
+
const short = (e) => e?.shortMessage || String(e?.message || e).split('\n')[0]
|
|
204
|
+
|
|
205
|
+
/** The site's invite link for `token` (the site reads ?ref= and passes it to the wallet's first mint). */
|
|
206
|
+
export const inviteLink = (token, referrer) => `https://gang.fun/token/${token}?ref=${referrer}`
|
|
207
|
+
|
|
208
|
+
/** A sale as the pad stores it, with what it means now. null when the token is not on this pad. */
|
|
209
|
+
export async function saleOf(ctx, token) {
|
|
210
|
+
const s = await ctx.read(ctx.pad, FLY_PAD_ABI, 'sales', [token])
|
|
211
|
+
if (s.creator === zeroAddress) return null
|
|
212
|
+
const [exitNowBps, quoteSymbol, t] = await Promise.all([ctx.read(ctx.pad, FLY_PAD_ABI, 'exitFeeBpsOf', [token]), symbolOf(ctx, s.quote), chainNow(ctx)])
|
|
213
|
+
const filledAt = Number(s.filledAt)
|
|
214
|
+
const launchAt = filledAt ? filledAt + Number(s.launchDelay) : null
|
|
215
|
+
const graceEnds = filledAt ? launchAt + LAUNCH_GRACE : null
|
|
216
|
+
const sold = Number(s.sold)
|
|
217
|
+
// minting → filled (waiting for launch) → launched; a filled sale not launched within 7 days reopens sell-backs and
|
|
218
|
+
// launches only while ≥ 3,000 shares are held (refund: below that it only refunds)
|
|
219
|
+
const status = s.launched ? 'launched'
|
|
220
|
+
: !filledAt ? 'minting'
|
|
221
|
+
: t >= graceEnds ? (sold >= EARLY_OPEN_SHARES ? 'stalled' : 'refund')
|
|
222
|
+
: 'filled'
|
|
223
|
+
return {
|
|
224
|
+
token, status, creator: s.creator, quote: s.quote, quoteSymbol, gate: s.gate === zeroAddress ? null : s.gate,
|
|
225
|
+
pair: s.pair === zeroAddress ? null : s.pair, launched: s.launched,
|
|
226
|
+
sharePriceRaw: s.basePrice, sharePrice: await units(ctx, s.quote, s.basePrice),
|
|
227
|
+
raise: await units(ctx, s.quote, s.basePrice * BigInt(TOTAL_SHARES)),
|
|
228
|
+
tokensPerShare: formatUnits(TOKENS_PER_SHARE, 18),
|
|
229
|
+
sold, totalShares: TOTAL_SHARES, sharesLeft: s.launched || filledAt ? 0 : TOTAL_SHARES - sold,
|
|
230
|
+
mintedShares: Number(s.totalShares), creatorShares: Number(s.creatorShares),
|
|
231
|
+
minWalletsLeft: s.launched || filledAt ? 0 : Math.ceil((TOTAL_SHARES - sold) / Number(s.baseQuota)),
|
|
232
|
+
canOpenEarly: !s.launched && !filledAt && sold >= EARLY_OPEN_SHARES,
|
|
233
|
+
filledAt: iso(filledAt), launchAt: iso(launchAt),
|
|
234
|
+
...(filledAt && !s.launched && {
|
|
235
|
+
launchableNow: t >= launchAt && sold >= EARLY_OPEN_SHARES, launchIn: Math.max(0, launchAt - t),
|
|
236
|
+
sellBackReopensAt: iso(graceEnds),
|
|
237
|
+
}),
|
|
238
|
+
sellBackOpen: !s.launched && (!filledAt || t >= graceEnds),
|
|
239
|
+
progressAt: iso(Number(s.progressAt)),
|
|
240
|
+
stale: !s.launched && Number(exitNowBps) === 0,
|
|
241
|
+
exitFeeFreeIn: s.launched ? 0 : Math.max(0, Number(s.progressAt) + STALE_AFTER - t),
|
|
242
|
+
rules: {
|
|
243
|
+
baseQuota: Number(s.baseQuota), inviteBonus: Number(s.inviteBonus), maxPerTx: Number(s.maxPerTx),
|
|
244
|
+
holdPct: pct(s.holdBps), mintFeePct: pct(s.mintFeeBps), exitFeePct: pct(s.exitFeeBps), exitFeeNowPct: pct(exitNowBps),
|
|
245
|
+
devCutPct: pct(s.devCutBps), buyPct: pct(s.buyBps), buyTaxPct: BUY_TAX_PCT, launchDelaySec: Number(s.launchDelay),
|
|
246
|
+
protectionSec: Number(s.window), protectionCapTokens: formatUnits(BigInt(s.baseQuota) * BigInt(s.windowCapMul) * TOKENS_PER_SHARE, 18),
|
|
247
|
+
postMint: s.postMint, tier: TIERS[Number(s.tierMode)] ?? Number(s.tierMode),
|
|
248
|
+
...(Number(s.tierMode) === 2 && { stepPct: pct(s.stepBps), stepShares: Number(s.stepShares), maxMul: Number(s.maxMulX100) / 100 }),
|
|
249
|
+
},
|
|
250
|
+
raw: s,
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const pub = ({ raw: _raw, sharePriceRaw: _p, ...s }) => s
|
|
254
|
+
|
|
255
|
+
/** The pool side of a launched sale: prices (Q112), protection, the token's supply room, and the tax rates. */
|
|
256
|
+
async function poolSide(ctx, token, sale, handler) {
|
|
257
|
+
const [[spot, blockStart, high, average], [until, gate, cap], sellTaxBps, supply, maxSupply, room] = await Promise.all([
|
|
258
|
+
ctx.read(ctx.pad, FLY_PAD_ABI, 'prices', [token]),
|
|
259
|
+
ctx.read(handler, FLY_HANDLER_ABI, 'protectionOf', [token]),
|
|
260
|
+
ctx.read(token, TOKEN_ABI, 'sellTaxBps'),
|
|
261
|
+
ctx.read(token, TOKEN_ABI, 'totalSupply'), ctx.read(token, TOKEN_ABI, 'maxSupply'), ctx.read(token, TOKEN_ABI, 'mintRoom'),
|
|
262
|
+
])
|
|
263
|
+
const t = await chainNow(ctx)
|
|
264
|
+
return {
|
|
265
|
+
prices: {
|
|
266
|
+
unit: `${sale.quoteSymbol || 'quote'} per token`,
|
|
267
|
+
pool: q112(spot), blockStart: q112(blockStart), recentHigh: q112(high), average30m: q112(average),
|
|
268
|
+
launchMintPerToken: formatUnits((sale.sharePriceRaw * 10n ** 18n) / TOKENS_PER_SHARE, 18),
|
|
269
|
+
note: 'a post-launch mint never pays less per token than the pool price; mints pause while the pool is more than 10% below its 30-minute average or its recent high',
|
|
270
|
+
},
|
|
271
|
+
protection: {
|
|
272
|
+
active: t < Number(until), until: iso(Number(until)), endsIn: Math.max(0, Number(until) - t),
|
|
273
|
+
agentIdRequired: gate !== zeroAddress, capTokensPerWallet: formatUnits(cap, 18),
|
|
274
|
+
note: 'during protection a pool buy needs an Agent ID and a wallet buys at most the cap (gross tokens from the pool)',
|
|
275
|
+
},
|
|
276
|
+
tax: { buyPct: BUY_TAX_PCT, sellPct: pct(sellTaxBps), split: 'the first 1%: holders 50% / platform 25% / creator 25%; sell tax above 1%: holders' },
|
|
277
|
+
supply: { total: formatUnits(supply, 18), max: formatUnits(maxSupply, 18), mintRoom: formatUnits(room, 18) },
|
|
278
|
+
raw: { spot, until: Number(until), gate, cap, sellTaxBps: Number(sellTaxBps), room },
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function poolReserves(ctx, token, pair) {
|
|
283
|
+
if (!pair) return [0n, 0n]
|
|
284
|
+
const [[r0, r1], t0] = await Promise.all([ctx.read(pair, PAIR_ABI, 'getReserves'), ctx.read(pair, PAIR_ABI, 'token0')])
|
|
285
|
+
return same(t0, token) ? [r0, r1] : [r1, r0]
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const hasAgent = async (ctx, gate, who) => !gate || (await ctx.read(gate, ERC721_ABI, 'balanceOf', [who])) > 0n
|
|
289
|
+
|
|
290
|
+
/** Dry-run `data` from `from`; null when it would pass. `rich`: pretend the wallet holds enough BNB (a diagnosis only). */
|
|
291
|
+
async function dryRun(ctx, from, to, data, value = 0n, rich = false) {
|
|
292
|
+
try {
|
|
293
|
+
await ctx.client.call({
|
|
294
|
+
account: from, to, data, value,
|
|
295
|
+
...(rich && { stateOverride: [{ address: from, balance: value + parseEther('1000') }] }),
|
|
296
|
+
})
|
|
297
|
+
return null
|
|
298
|
+
} catch (e) {
|
|
299
|
+
const r = revertOf(e)
|
|
300
|
+
return r ? { reverted: true, ...r } : { reverted: false, error: short(e) }
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** --ref <addr>: the rules the pad applies silently, checked up front so a referrer that would not count is said. */
|
|
305
|
+
async function checkReferrer(ctx, token, sale, me, myAccount, raw, fail) {
|
|
306
|
+
if (raw == null) return zeroAddress
|
|
307
|
+
if (!isAddress(raw)) fail('--ref must be the inviter\'s 0x address', { got: raw })
|
|
308
|
+
if (same(raw, me)) fail('--ref is this wallet itself: a wallet cannot invite itself')
|
|
309
|
+
if (myAccount.minted) {
|
|
310
|
+
fail('this wallet already minted in this token: an inviter only counts on a wallet\'s first mint here; leave --ref out', { token, wallet: me })
|
|
311
|
+
}
|
|
312
|
+
if (Number(sale.raw.inviteBonus) === 0) fail('this sale gives no invite bonus (inviteBonus 0): --ref would do nothing; leave it out', { token })
|
|
313
|
+
const ref = await ctx.read(ctx.pad, FLY_PAD_ABI, 'accounts', [token, raw])
|
|
314
|
+
if (!ref[3]) fail('the inviter has not minted in this token yet, so it cannot invite here; leave --ref out or ask it to mint first', { token, ref: raw })
|
|
315
|
+
if (sale.gate && !(await hasAgent(ctx, sale.gate, raw))) fail('the inviter holds no Agent ID, so its invite would not count; leave --ref out', { token, ref: raw })
|
|
316
|
+
return raw
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** One wallet in one sale (the pad's account) and its quota. */
|
|
320
|
+
async function accountOf(ctx, token, sale, who) {
|
|
321
|
+
const [a, left] = await Promise.all([
|
|
322
|
+
ctx.read(ctx.pad, FLY_PAD_ABI, 'accounts', [token, who]), ctx.read(ctx.pad, FLY_PAD_ABI, 'quotaLeft', [token, who]),
|
|
323
|
+
])
|
|
324
|
+
const [preShares, used, bonus, minted, , , baseline] = a
|
|
325
|
+
const inviteBonus = sale.rules.inviteBonus
|
|
326
|
+
return {
|
|
327
|
+
raw: { preShares, used, bonus, minted, baseline },
|
|
328
|
+
view: {
|
|
329
|
+
quota: sale.rules.baseQuota + Number(bonus), quotaUsed: Number(used), quotaLeft: Number(left),
|
|
330
|
+
inviteBonusShares: Number(bonus), invited: inviteBonus ? Number(bonus) / inviteBonus : 0,
|
|
331
|
+
preShares: Number(preShares), minted, canRefer: minted, baselineTokens: formatUnits(baseline, 18),
|
|
332
|
+
},
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** What a GangRouter pool buy takes out of the pair before the buy tax (the protection cap counts that). */
|
|
337
|
+
async function grossBuy(ctx, token, quote, payBnb, amount) {
|
|
338
|
+
const dex = await ctx.read(ctx.router, GANG_ROUTER_VIEW, 'pancakeRouter')
|
|
339
|
+
const path = payBnb && !same(quote, ctx.wbnb) ? [ctx.wbnb, quote, token] : [quote, token]
|
|
340
|
+
const amounts = await ctx.read(dex, DEX_ABI, 'getAmountsOut', [amount, path])
|
|
341
|
+
return amounts[amounts.length - 1]
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const SUBS = ['list', 'info', 'status', 'create', 'mint', 'withdraw', 'open-early', 'launch', 'buy', 'sell', 'claim', 'release', 'claim-dev', 'invite', 'tx']
|
|
345
|
+
const USAGE = 'usage: gang fly <list|info|status|create|mint|withdraw|open-early|launch|buy|sell|claim|release|claim-dev|invite|tx> [--testnet] — see gang help'
|
|
346
|
+
/** withdraw reverts below the preview minus this (bps): it catches an exit fee coming back. */
|
|
347
|
+
const WITHDRAW_TOLERANCE_BPS = 10n
|
|
348
|
+
|
|
349
|
+
/** J-template preset (spec §3–4) and the plain one; every field a flag can override. */
|
|
350
|
+
export const FLY_PRESETS = {
|
|
351
|
+
j: { raise: 20, quota: 10, invite: 1, maxPerTx: 10, hold: 60, mintFee: 1, exitFee: 1, devCut: 10, buyPct: 30, sellTax: 2, launchDelay: 60, window: 600, capMul: 1, postMint: true, tier: 'standard', supplyCap: 100 },
|
|
352
|
+
steady: { raise: 20, quota: 100, invite: 0, maxPerTx: 10, hold: 60, mintFee: 1, exitFee: 1, devCut: 0, buyPct: 0, sellTax: 1, launchDelay: 60, window: 600, capMul: 1, postMint: false, tier: 'flat', supplyCap: 100 },
|
|
353
|
+
}
|
|
354
|
+
// flag → [preset key, min, max, kind]
|
|
355
|
+
const CREATE_FLAGS = {
|
|
356
|
+
raise: ['raise', 3, 50, 'num'], quota: ['quota', 5, 100, 'int'], 'invite-bonus': ['invite', 0, 3, 'int'],
|
|
357
|
+
'max-per-tx': ['maxPerTx', 1, 10, 'int'], hold: ['hold', 60, 90, 'num'], 'mint-fee': ['mintFee', 1, 3, 'num'],
|
|
358
|
+
'exit-fee': ['exitFee', 1, 2, 'num'], 'dev-cut': ['devCut', 0, 10, 'num'], 'buy-pct': ['buyPct', 0, 50, 'num'],
|
|
359
|
+
'sell-tax': ['sellTax', 1, 2, 'num'], 'launch-delay': ['launchDelay', 0, 300, 'int'], window: ['window', 300, 1800, 'int'],
|
|
360
|
+
'cap-mul': ['capMul', 1, 2, 'int'], 'supply-cap': ['supplyCap', 10, 500, 'int'],
|
|
361
|
+
'step-pct': ['stepPct', 0, 10, 'num'], 'step-shares': ['stepShares', 100, 100_000, 'int'], 'max-mul': ['maxMul', 1, 10, 'num'],
|
|
362
|
+
}
|
|
363
|
+
export const FLY_CREATE_FLAGS = [...Object.keys(CREATE_FLAGS), 'preset', 'tier', 'post-mint', 'no-post-mint', 'dev-shares']
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Entry for `gang fly <sub>` (and the routed verbs of a fly token). io: { opt, flag, out, fail, summarize, resolveLogo,
|
|
367
|
+
* checkMeta, resolveMeta } from index.js.
|
|
368
|
+
*/
|
|
369
|
+
export async function runFly(sub, { opt, flag, out, fail, summarize, resolveLogo, checkMeta, resolveMeta }) {
|
|
370
|
+
if (sub === 'claim-dev') sub = 'release'
|
|
371
|
+
if (!SUBS.includes(sub)) return fail(USAGE, { got: sub ?? null })
|
|
372
|
+
const testnet = flag('testnet')
|
|
373
|
+
const net = testnet ? ' --testnet' : ''
|
|
374
|
+
const rawOnly = flag('calldata')
|
|
375
|
+
const ctx = flyCtx(testnet)
|
|
376
|
+
const chainId = Number(ctx.chainId)
|
|
377
|
+
const write = (tx, extra) => step(ctx, tx, { chainId, ...extra }, rawOnly, summarize)
|
|
378
|
+
if (flag('note')) fail('--note is not matched to 持续打新 trades yet: leave it out')
|
|
379
|
+
|
|
380
|
+
const tokenArg = () => {
|
|
381
|
+
const t = opt('token')
|
|
382
|
+
if (!isAddress(t ?? '')) fail('--token must be the 持续打新 token\'s address (0x…)', { got: t ?? null })
|
|
383
|
+
return t
|
|
384
|
+
}
|
|
385
|
+
const loadSale = async (token) => {
|
|
386
|
+
const sale = await saleOf(ctx, token)
|
|
387
|
+
if (!sale) fail(`not a 持续打新 (continuous-mint) token on this pad${testnet ? ' (BSC testnet)' : ''}`, { token, chainId, pad: ctx.pad })
|
|
388
|
+
return sale
|
|
389
|
+
}
|
|
390
|
+
const handlerOf = () => ctx.read(ctx.pad, FLY_PAD_ABI, 'taxHandler')
|
|
391
|
+
const me = () => walletFor(ctx, opt('from'))
|
|
392
|
+
|
|
393
|
+
if (sub === 'list') {
|
|
394
|
+
// on chain, newest first: the pad keeps every token it created
|
|
395
|
+
const limit = parseIntIn(fail, 'limit', opt('limit', '20'), 1, 200)
|
|
396
|
+
const status = opt('status', 'all')
|
|
397
|
+
if (!['all', 'minting', 'filled', 'launched'].includes(status)) fail('--status must be minting, filled, launched or all')
|
|
398
|
+
const count = Number(await ctx.read(ctx.pad, FLY_PAD_ABI, 'tokenCount'))
|
|
399
|
+
const items = []
|
|
400
|
+
for (let i = count - 1; i >= 0 && items.length < limit; i--) {
|
|
401
|
+
const token = await ctx.read(ctx.pad, FLY_PAD_ABI, 'allTokens', [BigInt(i)])
|
|
402
|
+
const s = await saleOf(ctx, token)
|
|
403
|
+
if (!s) continue
|
|
404
|
+
const st = s.status === 'stalled' || s.status === 'refund' ? 'filled' : s.status
|
|
405
|
+
if (status !== 'all' && st !== status) continue
|
|
406
|
+
items.push({
|
|
407
|
+
token, symbol: await symbolOf(ctx, token), status: s.status, quote: s.quoteSymbol, sharePrice: s.sharePrice, raise: s.raise,
|
|
408
|
+
sold: s.sold, sharesLeft: s.sharesLeft, mintedShares: s.mintedShares, baseQuota: s.rules.baseQuota, postMint: s.rules.postMint,
|
|
409
|
+
pair: s.pair, link: `https://gang.fun/token/${token}`,
|
|
410
|
+
next: s.status === 'minting' ? `gang mint --token ${token} --shares <n>${net}`
|
|
411
|
+
: s.status === 'launched' ? (s.rules.postMint ? `gang mint --token ${token} --shares <n>${net}` : `gang buy --token ${token} --amount <quote>${net}`)
|
|
412
|
+
: `gang info --token ${token}${net}`,
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
return out({ success: true, chainId, pad: ctx.pad, total: count, status, count: items.length, items, ...(!(await padOpen(ctx)) && { note: CLOSED }) })
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (sub === 'info') {
|
|
419
|
+
const token = tokenArg()
|
|
420
|
+
const sale = await loadSale(token)
|
|
421
|
+
const extra = {}
|
|
422
|
+
const owed = await ctx.read(ctx.pad, FLY_PAD_ABI, 'owedDev', [token])
|
|
423
|
+
if (sale.launched) {
|
|
424
|
+
const handler = await handlerOf()
|
|
425
|
+
const side = await poolSide(ctx, token, sale, handler)
|
|
426
|
+
const { raw: _r, ...view } = side
|
|
427
|
+
Object.assign(extra, view)
|
|
428
|
+
if (sale.rules.postMint) {
|
|
429
|
+
const one = await ctx.read(ctx.pad, FLY_PAD_ABI, 'sharePrice', [token, 1n])
|
|
430
|
+
extra.postMint = { sharePriceNow: await units(ctx, sale.quote, one), tierMulNow: Number((one * 100n) / sale.sharePriceRaw) / 100 }
|
|
431
|
+
}
|
|
432
|
+
const [owedTax, swapBack] = await Promise.all([
|
|
433
|
+
ctx.read(handler, FLY_HANDLER_ABI, 'owedOf', [token]),
|
|
434
|
+
swapBackState(ctx, handler, token, (await poolReserves(ctx, token, sale.pair))[0]),
|
|
435
|
+
])
|
|
436
|
+
if (swapBack) extra.swapBack = swapBack
|
|
437
|
+
if (owedTax > 0n) extra.owedCreatorTax = await units(ctx, sale.quote, owedTax)
|
|
438
|
+
}
|
|
439
|
+
if (owed > 0n) extra.owedDevCut = await units(ctx, sale.quote, owed)
|
|
440
|
+
if (extra.owedDevCut || extra.owedCreatorTax) extra.release = `gang release --token ${token}${net} (anyone; pays the creator)`
|
|
441
|
+
return out({ success: true, chainId, kind: 'fly', ...pub(sale), ...extra, next: nextFor(sale, token, net) })
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (sub === 'status') {
|
|
445
|
+
const token = tokenArg()
|
|
446
|
+
const sale = await loadSale(token)
|
|
447
|
+
const slippage = parseNum(fail, 'slippage', opt('slippage', '1'), 0, 50)
|
|
448
|
+
const who = me()
|
|
449
|
+
const [acct, bal, agent] = await Promise.all([
|
|
450
|
+
accountOf(ctx, token, sale, who), ctx.read(token, TOKEN_ABI, 'balanceOf', [who]), hasAgent(ctx, sale.gate, who),
|
|
451
|
+
])
|
|
452
|
+
const a = acct.raw
|
|
453
|
+
const pos = { ...acct.view, isAgent: agent, balance: formatUnits(bal, 18), shares: Number(a.preShares) }
|
|
454
|
+
if (a.minted) pos.inviteLink = inviteLink(token, who)
|
|
455
|
+
if (sale.sellBackOpen && a.preShares) {
|
|
456
|
+
const [payout, fee] = await ctx.read(ctx.pad, FLY_PAD_ABI, 'previewWithdraw', [token, who, BigInt(a.preShares)])
|
|
457
|
+
pos.sellBackAll = await units(ctx, sale.quote, payout)
|
|
458
|
+
pos.sellBackFee = await units(ctx, sale.quote, fee)
|
|
459
|
+
}
|
|
460
|
+
if (sale.launched) {
|
|
461
|
+
const handler = await handlerOf()
|
|
462
|
+
const vault = await ctx.read(ctx.pad, FLY_PAD_ABI, 'dividendVault')
|
|
463
|
+
const [out_, weight, side, bought] = await Promise.all([
|
|
464
|
+
ctx.read(handler, FLY_HANDLER_ABI, 'isOut', [token, who]),
|
|
465
|
+
ctx.read(handler, FLY_HANDLER_ABI, 'eligibleShare', [token, who]),
|
|
466
|
+
poolSide(ctx, token, sale, handler),
|
|
467
|
+
ctx.read(handler, FLY_HANDLER_ABI, 'boughtInWindow', [token, who]),
|
|
468
|
+
])
|
|
469
|
+
const reward = await dividendOf(ctx, vault, token, who, sale.quote, (side.raw.spot * 10n ** 18n) / Q112)
|
|
470
|
+
const q = bal > 0n ? await poolSellQuote(ctx, handler, token, bal) : null
|
|
471
|
+
if (q) {
|
|
472
|
+
pos.poolSellAll = {
|
|
473
|
+
expectOut: await units(ctx, sale.quote, q.out), minOut: await units(ctx, sale.quote, minOf(q.out, slippage)), slippagePct: slippage,
|
|
474
|
+
quotedWith: q.quotedWith, hint: POOL_SELL_HINT,
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (side.protection.active) {
|
|
478
|
+
const left = side.raw.cap > bought ? side.raw.cap - bought : 0n
|
|
479
|
+
pos.protection = { until: side.protection.until, boughtTokens: formatUnits(bought, 18), capLeftTokens: formatUnits(left, 18), agentOk: agent }
|
|
480
|
+
}
|
|
481
|
+
if (a.baseline > 0n) {
|
|
482
|
+
const line = holdLine(a.baseline, sale.rules.holdPct)
|
|
483
|
+
Object.assign(pos, {
|
|
484
|
+
reward: out_ ? 'out' : weight > 0n ? 'earning' : 'below-line',
|
|
485
|
+
holdLineTokens: formatUnits(line, 18),
|
|
486
|
+
sellableBeforeOut: !out_ && bal > line ? formatUnits(bal - line, 18) : '0',
|
|
487
|
+
pendingReward: reward.claimable, creditedUnsoldTokens: reward.creditedUnsoldTokens, creditedUnsoldEstimate: reward.creditedUnsoldEstimate,
|
|
488
|
+
...(out_ && { note: `out: fell below the hold line (${sale.rules.holdPct}% of what it minted). A new mint requalifies it from then on${sale.rules.postMint && acct.view.quotaLeft ? '' : ' (no quota left / no post-launch minting here, so it stays out)'}` }),
|
|
489
|
+
})
|
|
490
|
+
} else {
|
|
491
|
+
Object.assign(pos, { reward: 'none', pendingReward: reward.claimable, note: 'did not mint in this sale: the holder reward is only for minters' })
|
|
492
|
+
}
|
|
493
|
+
if (sale.rules.postMint && acct.view.quotaLeft > 0) {
|
|
494
|
+
const [acc, paid, fee, tokensOut, ok] = await ctx.read(ctx.pad, FLY_PAD_ABI, 'previewMintPost', [token, who, 1n])
|
|
495
|
+
pos.mintOneShareNow = acc ? { paid: await units(ctx, sale.quote, paid), fee: await units(ctx, sale.quote, fee), tokensOut: formatUnits(tokensOut, 18), ok } : null
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return out({ success: true, chainId, kind: 'fly', wallet: who, sale: pub(sale), position: pos, next: nextFor(sale, token, net, acct.view) })
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (sub === 'invite') {
|
|
502
|
+
const token = tokenArg()
|
|
503
|
+
const sale = await loadSale(token)
|
|
504
|
+
const who = flag('who') ? opt('who') : me()
|
|
505
|
+
if (!isAddress(who ?? '')) fail('--who must be a 0x address', { got: who ?? null })
|
|
506
|
+
const [acct, agent] = await Promise.all([accountOf(ctx, token, sale, who), hasAgent(ctx, sale.gate, who)])
|
|
507
|
+
const reason = !acct.view.minted ? 'not_minted' : !agent ? 'not_agent' : !sale.rules.inviteBonus ? 'no_invite_bonus' : null
|
|
508
|
+
const why = {
|
|
509
|
+
not_minted: 'this address has not minted in this token yet: its first mint makes it an inviter',
|
|
510
|
+
not_agent: 'this address holds no Agent ID, so its invites do not count',
|
|
511
|
+
no_invite_bonus: 'this sale gives no invite bonus (inviteBonus 0): invites add no quota',
|
|
512
|
+
}
|
|
513
|
+
// the invitee list is gang.fun's (Referred logs); the count and bonus are read on chain
|
|
514
|
+
const board = await apiGet(`/fly/tokens/${token}/invites/${who}`, undefined, null).catch(() => null)
|
|
515
|
+
return out({
|
|
516
|
+
success: true, chainId, token, referrer: who, link: inviteLink(token, who), canRefer: !reason, ...(reason && { reason, why: why[reason] }),
|
|
517
|
+
inviteBonusPerInvite: sale.rules.inviteBonus, invited: acct.view.invited, bonusShares: acct.view.inviteBonusShares,
|
|
518
|
+
quota: acct.view.quota, quotaLeft: acct.view.quotaLeft,
|
|
519
|
+
...(board?.invitees && { invitees: board.invitees }),
|
|
520
|
+
...(!board && { inviteesNote: `the list of invitees comes from ${API} (/fly/tokens/<token>/invites) once it indexes this pad; the count here is read on chain` }),
|
|
521
|
+
note: 'an invite counts on the invitee\'s first mint in this token (before or after launch), when it passes --ref (gang mint --ref <inviter>) or opens the link; the inviter must have minted here and hold an Agent ID',
|
|
522
|
+
})
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (sub === 'create') {
|
|
526
|
+
const name = opt('name'), symbol = opt('symbol')
|
|
527
|
+
if (!name || !symbol) fail('--name and --symbol are required')
|
|
528
|
+
checkMeta()
|
|
529
|
+
if (!(await padOpen(ctx))) fail(testnet ? 'the 持续打新 pad on BSC testnet has no migrator set: it takes no creates right now' : CLOSED, { pad: ctx.pad })
|
|
530
|
+
const presetName = opt('preset', 'j')
|
|
531
|
+
const preset = FLY_PRESETS[presetName]
|
|
532
|
+
if (!preset) fail(`--preset must be ${Object.keys(FLY_PRESETS).join(' or ')}`, { got: presetName })
|
|
533
|
+
const v = { ...preset }
|
|
534
|
+
for (const [f, [key, min, max, kind]] of Object.entries(CREATE_FLAGS)) {
|
|
535
|
+
if (!flag(f)) continue
|
|
536
|
+
v[key] = kind === 'int' ? parseIntIn(fail, f, opt(f), min, max) : parseNum(fail, f, opt(f), min, max)
|
|
537
|
+
}
|
|
538
|
+
if (flag('tier')) {
|
|
539
|
+
v.tier = opt('tier')
|
|
540
|
+
if (!TIERS.includes(v.tier)) fail('--tier must be flat, standard or linear', { got: v.tier })
|
|
541
|
+
}
|
|
542
|
+
if (flag('post-mint') && flag('no-post-mint')) fail('give --post-mint or --no-post-mint, not both')
|
|
543
|
+
if (flag('post-mint')) v.postMint = true
|
|
544
|
+
if (flag('no-post-mint')) v.postMint = false
|
|
545
|
+
// a pad without the Agent ID gate takes no dev cut (checkConfig refuses one): the preset's goes to 0 unless asked for
|
|
546
|
+
const gated = await ctx.read(ctx.pad, FLY_PAD_ABI, 'agentGateEnabled')
|
|
547
|
+
if (!gated && !flag('dev-cut')) v.devCut = 0
|
|
548
|
+
const linear = v.tier === 'linear'
|
|
549
|
+
if (!linear && ['step-pct', 'step-shares', 'max-mul'].some(flag)) fail('--step-pct / --step-shares / --max-mul only apply with --tier linear')
|
|
550
|
+
if (linear) { v.stepPct ??= 1; v.stepShares ??= 1_000; v.maxMul ??= 10 }
|
|
551
|
+
const devShares = parseIntIn(fail, 'dev-shares', opt('dev-shares', '1'), 1, Math.min(v.quota, v.maxPerTx))
|
|
552
|
+
const bps = (x) => Math.round(x * 100)
|
|
553
|
+
const cfg = {
|
|
554
|
+
raiseBnb: parseEther(String(v.raise)), baseQuota: v.quota, inviteBonus: v.invite, maxPerTx: v.maxPerTx,
|
|
555
|
+
holdBps: bps(v.hold), mintFeeBps: bps(v.mintFee), exitFeeBps: bps(v.exitFee), devCutBps: bps(v.devCut), buyBps: bps(v.buyPct),
|
|
556
|
+
sellTaxBps: bps(v.sellTax), launchDelay: v.launchDelay, window: v.window, windowCapMul: v.capMul, postMint: v.postMint,
|
|
557
|
+
tierMode: TIERS.indexOf(v.tier), stepBps: linear ? bps(v.stepPct) : 0, stepShares: linear ? v.stepShares : 0,
|
|
558
|
+
maxMulX100: linear ? Math.round(v.maxMul * 100) : 0, supplyCapMul: v.supplyCap,
|
|
559
|
+
}
|
|
560
|
+
const [ok, reason] = await ctx.read(ctx.pad, FLY_PAD_ABI, 'checkConfig', [cfg, BigInt(devShares)])
|
|
561
|
+
if (!ok) fail(`setting out of bounds: ${reason}`, { config: cfgView(cfg) })
|
|
562
|
+
const quote = flag('quote') ? opt('quote') : ctx.wbnb
|
|
563
|
+
const refPool = flag('ref-pool') ? opt('ref-pool') : (defaultRefPool(ctx.chainId, quote) ?? zeroAddress)
|
|
564
|
+
if (!isAddress(quote ?? '') || !isAddress(refPool ?? '')) fail('--quote / --ref-pool must be 0x addresses')
|
|
565
|
+
const quoteWbnb = same(quote, ctx.wbnb)
|
|
566
|
+
// the share price: raise / 10,000 in a WBNB sale; another quote is priced by the pad at create (its ref pool's
|
|
567
|
+
// TWAP), so the dev's cost is estimated with GangLaunchpad's preview of the same conversion and approved with 2% room
|
|
568
|
+
let price
|
|
569
|
+
if (quoteWbnb) price = cfg.raiseBnb / BigInt(TOTAL_SHARES)
|
|
570
|
+
else {
|
|
571
|
+
const gangPad = padNets('fair')[testnet ? 'testnet' : 'mainnet'].pad
|
|
572
|
+
try {
|
|
573
|
+
const [, p] = await ctx.read(gangPad, parseAbi(['function previewCreate(address quote, address refPool, uint256 raiseBnb) view returns (uint256 raiseQuote, uint256 sharePrice)']), 'previewCreate', [quote, refPool, cfg.raiseBnb])
|
|
574
|
+
price = (p * 102n) / 100n
|
|
575
|
+
} catch (e) {
|
|
576
|
+
return fail('cannot price the raise in this quote', revertOf(e) || { detail: short(e) })
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
const cost = price * BigInt(devShares)
|
|
580
|
+
const need = cost + (cost * BigInt(cfg.mintFeeBps)) / 10_000n
|
|
581
|
+
const who = me()
|
|
582
|
+
const sym = await symbolOf(ctx, quote)
|
|
583
|
+
const pre = await fund(ctx, { me: who, token: quote, need, spender: ctx.pad, sym }, rawOnly, summarize)
|
|
584
|
+
if (pre) return out(pre)
|
|
585
|
+
const createData = (logoURI, metaURI) => encodeFunctionData({
|
|
586
|
+
abi: FLY_PAD_ABI, functionName: 'create', args: [[name, symbol, logoURI, metaURI], quote, refPool, cfg, BigInt(devShares)],
|
|
587
|
+
})
|
|
588
|
+
const dry = await dryRun(ctx, who, ctx.pad, createData('', ''))
|
|
589
|
+
if (dry) return out({ success: false, step: 'create', ...dry })
|
|
590
|
+
const logo = await resolveLogo()
|
|
591
|
+
const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
|
|
592
|
+
return out(write({ from: who, to: ctx.pad, data: createData(logo.logoURI, meta.metaURI) }, {
|
|
593
|
+
step: 'create', kind: 'fly', name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
|
|
594
|
+
metaURI: meta.metaURI, metadata: meta.metadata, quote: sym || quote, preset: presetName, config: cfgView(cfg),
|
|
595
|
+
sharePrice: await units(ctx, quote, quoteWbnb ? price : (price * 100n) / 102n), devShares, devCost: await units(ctx, quote, need),
|
|
596
|
+
minWallets: Math.ceil(TOTAL_SHARES / cfg.baseQuota),
|
|
597
|
+
note: '10,000 shares at one price; it launches once they are sold (or you open early at ≥ 30%: gang fly open-early), launchDelay later, by anyone (gang fly launch; gang.fun\'s keeper does it too). Minters can sell back before that at the mint price less the exit fee. No GangBond or buy-back on these tokens.',
|
|
598
|
+
}))
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
if (sub === 'mint') {
|
|
602
|
+
const token = tokenArg()
|
|
603
|
+
const want = parseIntIn(fail, 'shares', opt('shares'), 1, 10_000)
|
|
604
|
+
const sale = await loadSale(token)
|
|
605
|
+
const who = me()
|
|
606
|
+
const acct = await accountOf(ctx, token, sale, who)
|
|
607
|
+
if (sale.gate && !(await hasAgent(ctx, sale.gate, who))) fail('this wallet holds no Agent ID; 持续打新 minting is Agent-only', { wallet: who })
|
|
608
|
+
const referrer = await checkReferrer(ctx, token, sale, who, acct.raw, opt('ref'), fail)
|
|
609
|
+
const quota = { quota: acct.view.quota, quotaLeft: acct.view.quotaLeft, maxPerTx: sale.rules.maxPerTx }
|
|
610
|
+
if (!acct.view.quotaLeft) fail('this wallet\'s quota in this sale is used up', { ...quota, hint: `invites add ${sale.rules.inviteBonus} share(s) each: gang fly invite --token ${token}${net}` })
|
|
611
|
+
const refNote = referrer !== zeroAddress
|
|
612
|
+
? { ref: referrer, inviteNote: `first mint here: ${referrer} gets +${sale.rules.inviteBonus} share(s) of quota` }
|
|
613
|
+
: !acct.raw.minted && sale.rules.inviteBonus ? { inviteNote: 'first mint here: pass --ref <inviter> if someone invited this wallet (only the first mint can carry it)' } : {}
|
|
614
|
+
const bnb = same(sale.quote, ctx.wbnb) && !flag('use-wbnb')
|
|
615
|
+
|
|
616
|
+
if (sale.status === 'minting') {
|
|
617
|
+
const [accepted, cost, fee] = await ctx.read(ctx.pad, FLY_PAD_ABI, 'previewMint', [token, who, BigInt(want)])
|
|
618
|
+
if (accepted === 0n) fail('no shares available to this wallet now', quota)
|
|
619
|
+
const minShares = flag('min-shares') ? parseIntIn(fail, 'min-shares', opt('min-shares'), 1, Number(accepted)) : Number(accepted)
|
|
620
|
+
const need = cost + fee
|
|
621
|
+
const fills = sale.sold + Number(accepted) === TOTAL_SHARES
|
|
622
|
+
// launchDelay 0: the mint that fills also launches (about 2.5M gas); near the end other mints landing first can make
|
|
623
|
+
// this one that mint, so it gets a launch-sized gas limit
|
|
624
|
+
const mayLaunch = sale.rules.launchDelaySec === 0 && sale.sharesLeft - Number(accepted) <= 10 * sale.rules.maxPerTx
|
|
625
|
+
const extra = {
|
|
626
|
+
step: 'mint', kind: 'fly', phase: 'pre-launch', token, shares: Number(accepted), ...(Number(accepted) < want && { truncatedFrom: want, ...quota }),
|
|
627
|
+
cost: await units(ctx, sale.quote, cost), fee: await units(ctx, sale.quote, fee), feePct: sale.rules.mintFeePct, quote: sale.quoteSymbol,
|
|
628
|
+
tokens: formatUnits(accepted * TOKENS_PER_SHARE, 18), soldAfter: sale.sold + Number(accepted), quotaLeftAfter: acct.view.quotaLeft - Number(accepted), ...refNote,
|
|
629
|
+
...(fills && { fills: `this mint fills the sale${sale.rules.launchDelaySec ? `; it launches ${sale.rules.launchDelaySec}s later (gang fly launch, anyone)` : ' and launches it (higher gas)'}` }),
|
|
630
|
+
note: `the ${sale.rules.mintFeePct}% mint fee goes to the platform; before launch you can sell back at the mint price less the exit fee (gang withdraw)`,
|
|
631
|
+
}
|
|
632
|
+
if (bnb) {
|
|
633
|
+
const native = await ctx.client.getBalance({ address: who })
|
|
634
|
+
if (native < need + GAS_RESERVE) fail('not enough BNB for this mint (native BNB must also cover gas)', { haveBnb: formatUnits(native, 18), needBnb: formatUnits(need, 18), hint: 'add --use-wbnb to pay from WBNB' })
|
|
635
|
+
const data = encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mintWithBnb', args: [token, accepted, BigInt(minShares), referrer] })
|
|
636
|
+
const dry = await dryRun(ctx, who, ctx.pad, data, need)
|
|
637
|
+
if (dry) return out({ success: false, ...extra, ...dry })
|
|
638
|
+
const tx = { from: who, to: ctx.pad, data, value: need }
|
|
639
|
+
if (mayLaunch) try { tx.gas = await roomyGas(ctx, tx, GAS_FLOOR.launch) } catch (e) { return out({ success: false, ...extra, reverted: true, ...(revertOf(e) || { error: short(e) }) }) }
|
|
640
|
+
return out(write(tx, { ...extra, payBnb: formatUnits(need, 18), ...(tx.gas && { gasLimit: tx.gas.toString() }) }))
|
|
641
|
+
}
|
|
642
|
+
const pre = await fund(ctx, { me: who, token: sale.quote, need, spender: ctx.pad, sym: sale.quoteSymbol }, rawOnly, summarize)
|
|
643
|
+
if (pre) return out(pre)
|
|
644
|
+
const data = encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mint', args: [token, accepted, BigInt(minShares), referrer] })
|
|
645
|
+
const dry = await dryRun(ctx, who, ctx.pad, data)
|
|
646
|
+
if (dry) return out({ success: false, ...extra, ...dry })
|
|
647
|
+
const tx = { from: who, to: ctx.pad, data }
|
|
648
|
+
if (mayLaunch) try { tx.gas = await roomyGas(ctx, tx, GAS_FLOOR.launch) } catch (e) { return out({ success: false, ...extra, reverted: true, ...(revertOf(e) || { error: short(e) }) }) }
|
|
649
|
+
return out(write(tx, { ...extra, ...(tx.gas && { gasLimit: tx.gas.toString() }) }))
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
if (!sale.launched) {
|
|
653
|
+
fail(`the sale is ${sale.status}: no mints until it launches`, {
|
|
654
|
+
token, ...(sale.launchAt && { launchAt: sale.launchAt, launchableNow: sale.launchableNow }),
|
|
655
|
+
hint: sale.launchableNow ? `anyone can launch it now: gang fly launch --token ${token}${net}` : 'wait for the launch (gang info)',
|
|
656
|
+
})
|
|
657
|
+
}
|
|
658
|
+
if (!sale.rules.postMint) fail('this sale has no post-launch minting: buy in the pool', { hint: `gang buy --token ${token} --amount <quote>${net}` })
|
|
659
|
+
const slippage = parseNum(fail, 'slippage', opt('slippage', '2'), 0, 50)
|
|
660
|
+
const [accepted, paid, fee, tokensOut, ok] = await ctx.read(ctx.pad, FLY_PAD_ABI, 'previewMintPost', [token, who, BigInt(want)])
|
|
661
|
+
const handler = await handlerOf()
|
|
662
|
+
const side = await poolSide(ctx, token, sale, handler)
|
|
663
|
+
const priceView = {
|
|
664
|
+
poolPrice: side.prices.pool,
|
|
665
|
+
...(tokensOut > 0n && { mintPricePerToken: formatUnits((paid * 10n ** 18n) / tokensOut, 18) }),
|
|
666
|
+
...(tokensOut > 0n && side.raw.spot > 0n && { premiumOverPoolPct: Number(((paid * Q112 * 10_000n) / tokensOut / side.raw.spot) - 10_000n) / 100 }),
|
|
667
|
+
unit: side.prices.unit,
|
|
668
|
+
}
|
|
669
|
+
if (accepted === 0n) fail('no shares available to this wallet now', quota)
|
|
670
|
+
const minTokensOut = minOf(tokensOut, slippage)
|
|
671
|
+
const maxSpent = paid + fee
|
|
672
|
+
const data = bnb
|
|
673
|
+
? encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mintPostWithBnb', args: [token, accepted, minTokensOut, referrer] })
|
|
674
|
+
: encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'mintPost', args: [token, accepted, minTokensOut, maxSpent, referrer] })
|
|
675
|
+
const extra = {
|
|
676
|
+
step: 'mint', kind: 'fly', phase: 'post-launch', function: bnb ? 'mintPostWithBnb' : 'mintPost', token, shares: Number(accepted),
|
|
677
|
+
...(Number(accepted) < want && { truncatedFrom: want, ...quota }),
|
|
678
|
+
paid: await units(ctx, sale.quote, paid), fee: await units(ctx, sale.quote, fee), maxSpent: await units(ctx, sale.quote, maxSpent), quote: sale.quoteSymbol,
|
|
679
|
+
expectTokens: formatUnits(tokensOut, 18), minTokensOut: formatUnits(minTokensOut, 18), slippagePct: slippage, ...priceView,
|
|
680
|
+
quotaLeftAfter: acct.view.quotaLeft - Number(accepted), ...refNote,
|
|
681
|
+
note: `the money goes into the pool (${sale.rules.buyPct}% of it buys from it${sale.rules.devCutPct ? `, ${sale.rules.devCutPct}% to the creator` : ''}), the tokens are minted to you; the ${sale.rules.mintFeePct}% fee is the platform's. Minted tokens earn the holder reward while you keep ${sale.rules.holdPct}% of them`,
|
|
682
|
+
}
|
|
683
|
+
if (!ok) {
|
|
684
|
+
// the preview says no: the same call, simulated, names the rule (a BNB sale: BNB lent for the simulation only). Only
|
|
685
|
+
// a rule of the pad / handler / token counts: a quote-token revert (no allowance yet) says nothing about the rule
|
|
686
|
+
const dry = await dryRun(ctx, who, ctx.pad, data, bnb ? maxSpent : 0n, bnb)
|
|
687
|
+
const r = dry?.reverted && HINTS[dry.error] ? dry : null
|
|
688
|
+
const cap = side.raw.room < tokensOut * 2n
|
|
689
|
+
return out({
|
|
690
|
+
success: false, ...extra, error: `a post-launch mint is refused right now${r ? `: ${r.error}` : ''}`,
|
|
691
|
+
...(r ? { reason: r.error, hint: r.hint } : {
|
|
692
|
+
reason: cap ? 'supply cap' : 'price or pace rule',
|
|
693
|
+
hint: cap ? HINTS.CapExceeded : 'the pool price is more than 10% below its average / recent high, the mint price is more than 10% above the pool, or this wallet hit its 30-minute pace (2% of the pool): wait, or mint fewer shares',
|
|
694
|
+
}),
|
|
695
|
+
prices: side.prices, supply: side.supply,
|
|
696
|
+
})
|
|
697
|
+
}
|
|
698
|
+
if (bnb) {
|
|
699
|
+
const native = await ctx.client.getBalance({ address: who })
|
|
700
|
+
if (native < maxSpent + GAS_RESERVE) fail('not enough BNB for this mint (native BNB must also cover gas)', { haveBnb: formatUnits(native, 18), needBnb: formatUnits(maxSpent, 18), hint: 'add --use-wbnb to pay from WBNB' })
|
|
701
|
+
const dry = await dryRun(ctx, who, ctx.pad, data, maxSpent)
|
|
702
|
+
if (dry) return out({ success: false, ...extra, ...dry })
|
|
703
|
+
const tx = { from: who, to: ctx.pad, data, value: maxSpent }
|
|
704
|
+
try { tx.gas = await roomyGas(ctx, tx, GAS_FLOOR.mintPost) } catch (e) { return out({ success: false, ...extra, reverted: true, ...(revertOf(e) || { error: short(e) }) }) }
|
|
705
|
+
return out(write(tx, { ...extra, payBnb: formatUnits(maxSpent, 18), refundNote: 'what the mint does not spend comes back in the same tx', gasLimit: tx.gas.toString(), gasNote: GAS_NOTE }))
|
|
706
|
+
}
|
|
707
|
+
const pre = await fund(ctx, { me: who, token: sale.quote, need: maxSpent, spender: ctx.pad, sym: sale.quoteSymbol }, rawOnly, summarize)
|
|
708
|
+
if (pre) return out(pre)
|
|
709
|
+
const dry = await dryRun(ctx, who, ctx.pad, data)
|
|
710
|
+
if (dry) return out({ success: false, ...extra, ...dry })
|
|
711
|
+
const tx = { from: who, to: ctx.pad, data }
|
|
712
|
+
try { tx.gas = await roomyGas(ctx, tx, GAS_FLOOR.mintPost) } catch (e) { return out({ success: false, ...extra, reverted: true, ...(revertOf(e) || { error: short(e) }) }) }
|
|
713
|
+
return out(write(tx, { ...extra, gasLimit: tx.gas.toString(), gasNote: GAS_NOTE }))
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
if (sub === 'withdraw') {
|
|
717
|
+
const token = tokenArg()
|
|
718
|
+
const sale = await loadSale(token)
|
|
719
|
+
if (!sale.sellBackOpen) {
|
|
720
|
+
fail(`the sale is ${sale.status}: sell-back is closed`, sale.launched
|
|
721
|
+
? { pair: sale.pair, hint: `it launched: sell in the pool with gang sell --token ${token} (--amount <tokens> | --all)${net}` }
|
|
722
|
+
: { sellBackReopensAt: sale.sellBackReopensAt, hint: 'a filled sale launches soon (gang fly launch); sell-backs reopen only if it is still not launched 7 days later' })
|
|
723
|
+
}
|
|
724
|
+
const who = me()
|
|
725
|
+
const acct = await accountOf(ctx, token, sale, who)
|
|
726
|
+
const held = Number(acct.raw.preShares)
|
|
727
|
+
if (!held) fail('this wallet has no pre-launch shares in this sale')
|
|
728
|
+
if (flag('all') && flag('shares')) fail('give --shares <n> or --all, not both')
|
|
729
|
+
const shares = flag('all') ? held : parseIntIn(fail, 'shares', opt('shares'), 1, held)
|
|
730
|
+
const [payout, fee] = await ctx.read(ctx.pad, FLY_PAD_ABI, 'previewWithdraw', [token, who, BigInt(shares)])
|
|
731
|
+
const minPayout = (payout * (10_000n - WITHDRAW_TOLERANCE_BPS)) / 10_000n
|
|
732
|
+
const data = encodeFunctionData({ abi: FLY_PAD_ABI, functionName: 'withdraw', args: [token, BigInt(shares), minPayout] })
|
|
733
|
+
const dry = await dryRun(ctx, who, ctx.pad, data)
|
|
734
|
+
if (dry) return out({ success: false, step: 'withdraw', ...dry })
|
|
735
|
+
return out(write({ from: who, to: ctx.pad, data }, {
|
|
736
|
+
step: 'withdraw', kind: 'fly', token, shares, receive: await units(ctx, sale.quote, payout), minReceive: await units(ctx, sale.quote, minPayout),
|
|
737
|
+
exitFee: await units(ctx, sale.quote, fee), exitFeePct: sale.rules.exitFeeNowPct, quote: sale.quoteSymbol,
|
|
738
|
+
note: `mint price less the ${sale.rules.exitFeeNowPct}% exit fee (none after 7 days without progress); the mint fee is not returned; the shares go back to this wallet\'s quota`,
|
|
739
|
+
}))
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
if (sub === 'open-early' || sub === 'launch') {
|
|
743
|
+
const token = tokenArg()
|
|
744
|
+
const sale = await loadSale(token)
|
|
745
|
+
const who = me()
|
|
746
|
+
if (sale.launched) fail('already launched', { pair: sale.pair })
|
|
747
|
+
if (sub === 'open-early') {
|
|
748
|
+
if (sale.status !== 'minting') fail(`the sale is ${sale.status}: open-early is for a sale still minting`, { launchAt: sale.launchAt })
|
|
749
|
+
if (!same(who, sale.creator)) fail('only the creator can open the sale early', { creator: sale.creator, wallet: who })
|
|
750
|
+
if (sale.sold < EARLY_OPEN_SHARES) fail(`open-early needs at least ${EARLY_OPEN_SHARES} shares (30%) sold`, { sold: sale.sold })
|
|
751
|
+
} else {
|
|
752
|
+
if (sale.status === 'minting') fail('the sale has not filled yet: nothing to launch', { sold: sale.sold, hint: sale.canOpenEarly ? `the creator can open early: gang fly open-early --token ${token}${net}` : undefined })
|
|
753
|
+
if (sale.status === 'refund') fail('fewer than 3,000 shares are held 7 days after the fill: this sale can no longer launch, only refund (gang withdraw)', { sold: sale.sold })
|
|
754
|
+
if (!sale.launchableNow) fail(`too early: launch opens at ${sale.launchAt}`, { launchIn: sale.launchIn })
|
|
755
|
+
}
|
|
756
|
+
const data = encodeFunctionData({ abi: FLY_PAD_ABI, functionName: sub === 'launch' ? 'launch' : 'openEarly', args: [token] })
|
|
757
|
+
const dry = await dryRun(ctx, who, ctx.pad, data)
|
|
758
|
+
if (dry) return out({ success: false, step: sub, ...dry })
|
|
759
|
+
const tx = { from: who, to: ctx.pad, data }
|
|
760
|
+
if (sub === 'launch' || !sale.rules.launchDelaySec) {
|
|
761
|
+
try { tx.gas = await roomyGas(ctx, tx, GAS_FLOOR.launch) } catch (e) { return out({ success: false, step: sub, reverted: true, ...(revertOf(e) || { error: short(e) }) }) }
|
|
762
|
+
}
|
|
763
|
+
return out(write(tx, {
|
|
764
|
+
step: sub, kind: 'fly', token, sold: sale.sold, ...(tx.gas && { gasLimit: tx.gas.toString() }),
|
|
765
|
+
note: sub === 'launch'
|
|
766
|
+
? `creates the PancakeSwap pool at the mint price (about 2.5M gas); protection runs ${sale.rules.protectionSec}s after it`
|
|
767
|
+
: sale.rules.launchDelaySec ? `stops the sale at ${sale.sold} shares; anyone can launch it ${sale.rules.launchDelaySec}s later (gang fly launch)` : `stops the sale at ${sale.sold} shares and launches in the same tx (about 2.5M gas)`,
|
|
768
|
+
}))
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
if (sub === 'buy' || sub === 'sell') {
|
|
772
|
+
const token = tokenArg()
|
|
773
|
+
const sale = await loadSale(token)
|
|
774
|
+
if (!sale.launched || !sale.pair) {
|
|
775
|
+
fail(`the sale is ${sale.status}: gang ${sub} trades the token in its pool after launch`, {
|
|
776
|
+
hint: sub === 'buy' ? `before launch, mint shares: gang mint --token ${token} --shares <n>${net}` : `before launch, sell shares back: gang withdraw --token ${token} (--shares <n> | --all)${net}`,
|
|
777
|
+
})
|
|
778
|
+
}
|
|
779
|
+
for (const f of ['bond', 'break-bond', 'settle-first']) if (flag(f)) fail(`--${f}: 持续打新 tokens take no GangBond`)
|
|
780
|
+
const slippage = parseNum(fail, 'slippage', opt('slippage', '1'), 0, 50)
|
|
781
|
+
if (sub === 'sell' && flag('all') === !!opt('amount')) fail('pass exactly one of --amount <tokens> or --all')
|
|
782
|
+
if (sub === 'buy' && !flag('amount')) fail('--amount <quote (or BNB) to spend> required')
|
|
783
|
+
const handler = await handlerOf()
|
|
784
|
+
const side = await poolSide(ctx, token, sale, handler)
|
|
785
|
+
const who = me()
|
|
786
|
+
const payBnb = sub === 'buy' && poolPayBnb(ctx, sale.quote, flag)
|
|
787
|
+
let extra = {}
|
|
788
|
+
if (sub === 'buy' && side.protection.active) {
|
|
789
|
+
// launch protection: the handler refuses a buy without an Agent ID or past the wallet's cap, so say it here
|
|
790
|
+
if (side.raw.gate !== zeroAddress && !(await hasAgent(ctx, side.raw.gate, who))) {
|
|
791
|
+
fail('launch protection: only Agent ID holders can buy from the pool until it ends', { until: side.protection.until, endsIn: side.protection.endsIn })
|
|
792
|
+
}
|
|
793
|
+
const bought = await ctx.read(handler, FLY_HANDLER_ABI, 'boughtInWindow', [token, who])
|
|
794
|
+
const left = side.raw.cap > bought ? side.raw.cap - bought : 0n
|
|
795
|
+
const amountIn = parseUnits(parseAmount(fail, 'amount', opt('amount')), 18)
|
|
796
|
+
let gross = null
|
|
797
|
+
try { gross = await grossBuy(ctx, token, sale.quote, payBnb, amountIn) } catch { /* the pool trade reports a missing pool */ }
|
|
798
|
+
if (gross != null && gross > left) {
|
|
799
|
+
fail('launch protection: this buy takes more tokens from the pool than this wallet\'s protected cap allows', {
|
|
800
|
+
expectTokensBeforeTax: formatUnits(gross, 18), capLeftTokens: formatUnits(left, 18), until: side.protection.until,
|
|
801
|
+
hint: sale.rules.postMint ? `buy less, or mint instead: gang mint --token ${token} --shares <n>${net}` : 'buy less, or wait for the protection to end',
|
|
802
|
+
})
|
|
803
|
+
}
|
|
804
|
+
extra = { protection: { until: side.protection.until, capLeftTokens: formatUnits(left, 18) } }
|
|
805
|
+
}
|
|
806
|
+
let outWarning = null
|
|
807
|
+
if (sub === 'sell') {
|
|
808
|
+
const a = await ctx.read(ctx.pad, FLY_PAD_ABI, 'accounts', [token, who])
|
|
809
|
+
const baseline = a[6]
|
|
810
|
+
if (baseline > 0n && !(await ctx.read(handler, FLY_HANDLER_ABI, 'isOut', [token, who]))) {
|
|
811
|
+
const bal = await ctx.read(token, TOKEN_ABI, 'balanceOf', [who])
|
|
812
|
+
const line = holdLine(baseline, sale.rules.holdPct)
|
|
813
|
+
const sellable = bal > line ? bal - line : 0n
|
|
814
|
+
const amount = flag('all') ? bal : parseUnits(parseAmount(fail, 'amount', opt('amount')), 18)
|
|
815
|
+
if (amount <= bal && amount > sellable) {
|
|
816
|
+
outWarning = {
|
|
817
|
+
warning: `selling ${formatUnits(amount, 18)} tokens goes past sellableBeforeOut (${formatUnits(sellable, 18)}): this wallet drops below its hold line (${formatUnits(line, 18)} tokens) and stops earning the holder reward until it mints again`,
|
|
818
|
+
sellableBeforeOut: formatUnits(sellable, 18), holdLineTokens: formatUnits(line, 18), balance: formatUnits(bal, 18),
|
|
819
|
+
}
|
|
820
|
+
if (!flag('confirm-out')) fail(outWarning.warning, { ...outWarning, token, wallet: who, hint: 'sell at most sellableBeforeOut to keep the reward, or re-run with --confirm-out once the user accepts' })
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
// GangRouter's pool functions trade any token on its Pancake pair (they never ask the pad): the fly token too
|
|
825
|
+
const poolCtx = { ...ctx, pad: null }
|
|
826
|
+
return out(await poolTrade(poolCtx, {
|
|
827
|
+
side: sub, token, quote: sale.quote, me: who, slippage, buyTaxBps: BUY_TAX_PCT * 100, sellTaxBps: side.raw.sellTaxBps, handler,
|
|
828
|
+
amount: sub === 'sell' && flag('all') ? null : parseAmount(fail, 'amount', opt('amount')), all: sub === 'sell' && flag('all'),
|
|
829
|
+
swapBackGas: true, payBnb, toBnb: flag('to-bnb'), gasFloor: GAS_FLOOR[sub],
|
|
830
|
+
base: {
|
|
831
|
+
kind: 'fly', pair: sale.pair, ...extra, ...(outWarning && { ...outWarning, confirmedOut: true }),
|
|
832
|
+
...(sub === 'buy' && {
|
|
833
|
+
rewardNote: 'pool-bought tokens earn no holder reward (only minted ones do)',
|
|
834
|
+
gasNote: GAS_NOTE,
|
|
835
|
+
}),
|
|
836
|
+
// a large pool buy seen in the public mempool can be front-run (issue #75 asks for private sends): the CLI does
|
|
837
|
+
// not broadcast, so it can only say where to send it
|
|
838
|
+
...(sub === 'buy' && (rawOnly || side.protection.active) && { mempoolNote: rawOnly
|
|
839
|
+
? 'send this buy through a private submission endpoint (not a public RPC): a large pool buy in the public mempool can be front-run'
|
|
840
|
+
: 'the Agentic Wallet broadcasts through its own RPC; for a large buy, consider gang buy … --calldata and sending the tx through a private submission endpoint' }),
|
|
841
|
+
},
|
|
842
|
+
}, { rawOnly, summarize, revertOf }))
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
if (sub === 'claim') {
|
|
846
|
+
const token = tokenArg()
|
|
847
|
+
const sale = await loadSale(token)
|
|
848
|
+
const who = me()
|
|
849
|
+
const vault = await ctx.read(ctx.pad, FLY_PAD_ABI, 'dividendVault')
|
|
850
|
+
let spot = 0n, standing = {}
|
|
851
|
+
if (sale.launched) {
|
|
852
|
+
const handler = await handlerOf()
|
|
853
|
+
const [[s], isOut, a, bal] = await Promise.all([
|
|
854
|
+
ctx.read(ctx.pad, FLY_PAD_ABI, 'prices', [token]), ctx.read(handler, FLY_HANDLER_ABI, 'isOut', [token, who]),
|
|
855
|
+
ctx.read(ctx.pad, FLY_PAD_ABI, 'accounts', [token, who]), ctx.read(token, TOKEN_ABI, 'balanceOf', [who]),
|
|
856
|
+
])
|
|
857
|
+
spot = (s * 10n ** 18n) / Q112
|
|
858
|
+
const line = holdLine(a[6], sale.rules.holdPct)
|
|
859
|
+
standing = { reward: a[6] === 0n ? 'none' : isOut ? 'out' : 'earning', holdLineTokens: formatUnits(line, 18), balance: formatUnits(bal, 18) }
|
|
860
|
+
}
|
|
861
|
+
const r = await dividendOf(ctx, vault, token, who, sale.quote, spot)
|
|
862
|
+
const unsold = r.creditedUnsoldTokens && Number(r.creditedUnsoldTokens) > 0
|
|
863
|
+
if (r.claimableRaw === 0n) {
|
|
864
|
+
fail('nothing to claim yet', { ...standing, ...(unsold && { creditedUnsoldEstimate: r.creditedUnsoldEstimate, note: r.note }), hint: `gang status --token ${token}${net}` })
|
|
865
|
+
}
|
|
866
|
+
const data = encodeFunctionData({ abi: VAULT_ABI, functionName: 'claim', args: [token] })
|
|
867
|
+
return out(write({ from: who, to: vault, data }, {
|
|
868
|
+
step: 'claim', kind: 'fly', token, amount: r.claimable, quote: sale.quoteSymbol, ...standing,
|
|
869
|
+
...(unsold && { stillCreditedUnsold: r.creditedUnsoldEstimate }),
|
|
870
|
+
}))
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (sub === 'release') {
|
|
874
|
+
// the creator's money that a transfer could not deliver: the pad's dev cut first, then the handler's tax share
|
|
875
|
+
const token = tokenArg()
|
|
876
|
+
const sale = await loadSale(token)
|
|
877
|
+
const who = me()
|
|
878
|
+
const handler = await handlerOf()
|
|
879
|
+
const [dev, tax] = await Promise.all([ctx.read(ctx.pad, FLY_PAD_ABI, 'owedDev', [token]), ctx.read(handler, FLY_HANDLER_ABI, 'owedOf', [token])])
|
|
880
|
+
if (dev === 0n && tax === 0n) fail('nothing is owed to the creator of this token', { token, creator: sale.creator })
|
|
881
|
+
const [to, abi, functionName, amount, what] = dev > 0n
|
|
882
|
+
? [ctx.pad, FLY_PAD_ABI, 'claimDev', dev, 'dev cut']
|
|
883
|
+
: [handler, FLY_HANDLER_ABI, 'release', tax, 'tax share']
|
|
884
|
+
const data = encodeFunctionData({ abi, functionName, args: [token] })
|
|
885
|
+
const dry = await dryRun(ctx, who, to, data)
|
|
886
|
+
if (dry) return out({ success: false, step: 'release', what, ...dry, hint: dry.error === 'execution reverted' ? 'the creator still cannot receive the quote: try again later' : dry.hint })
|
|
887
|
+
return out(write({ from: who, to, data }, {
|
|
888
|
+
step: 'release', kind: 'fly', token, what, function: functionName, amount: await units(ctx, sale.quote, amount), quote: sale.quoteSymbol, to: sale.creator,
|
|
889
|
+
...(dev > 0n && tax > 0n && { alsoOwed: { taxShare: await units(ctx, sale.quote, tax), next: `run gang release --token ${token}${net} again after this one` } }),
|
|
890
|
+
note: 'anyone may send it; the creator receives it',
|
|
891
|
+
}))
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
if (sub === 'tx') {
|
|
895
|
+
const hash = opt('hash')
|
|
896
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(hash ?? '')) fail('--hash must be a tx hash')
|
|
897
|
+
const r = await ctx.client.waitForTransactionReceipt({ hash, timeout: 120_000 })
|
|
898
|
+
return out({ success: true, chainId, hash, status: r.status, block: Number(r.blockNumber), events: decodeFly(r.logs), explorer: `${ctx.explorer}/tx/${hash}` })
|
|
899
|
+
}
|
|
900
|
+
return fail(USAGE, { got: sub })
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** The logs of a tx, decoded with the fly ABIs (raw units). */
|
|
904
|
+
export function decodeFly(logs) {
|
|
905
|
+
const events = []
|
|
906
|
+
for (const log of logs) {
|
|
907
|
+
for (const abi of FLY_EVENT_ABIS) {
|
|
908
|
+
try {
|
|
909
|
+
const ev = decodeEventLog({ abi, data: log.data, topics: log.topics })
|
|
910
|
+
events.push({ event: ev.eventName, address: log.address, ...JSON.parse(JSON.stringify(ev.args, (_, v) => (typeof v === 'bigint' ? v.toString() : v))) })
|
|
911
|
+
break
|
|
912
|
+
} catch { /* other contract / event */ }
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
return events
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
const cfgView = (c) => ({
|
|
919
|
+
raiseBnb: formatUnits(c.raiseBnb, 18), baseQuota: c.baseQuota, inviteBonus: c.inviteBonus, maxPerTx: c.maxPerTx, holdPct: pct(c.holdBps),
|
|
920
|
+
mintFeePct: pct(c.mintFeeBps), exitFeePct: pct(c.exitFeeBps), devCutPct: pct(c.devCutBps), buyPct: pct(c.buyBps), sellTaxPct: pct(c.sellTaxBps),
|
|
921
|
+
launchDelaySec: c.launchDelay, protectionSec: c.window, protectionCapMul: c.windowCapMul, postMint: c.postMint, tier: TIERS[c.tierMode],
|
|
922
|
+
...(c.tierMode === 2 && { stepPct: pct(c.stepBps), stepShares: c.stepShares, maxMul: c.maxMulX100 / 100 }), supplyCapMul: c.supplyCapMul,
|
|
923
|
+
})
|
|
924
|
+
|
|
925
|
+
/** The command that acts on the sale next. */
|
|
926
|
+
function nextFor(sale, token, net, acct) {
|
|
927
|
+
if (sale.status === 'minting') return `gang mint --token ${token} --shares <n>${net}${acct && !acct.minted ? ' [--ref <inviter>]' : ''}`
|
|
928
|
+
if (sale.status === 'filled') return sale.launchableNow ? `gang fly launch --token ${token}${net}` : `wait until ${sale.launchAt}, then gang fly launch --token ${token}${net}`
|
|
929
|
+
if (sale.status === 'stalled') return `gang fly launch --token ${token}${net} (or gang withdraw to sell back)`
|
|
930
|
+
if (sale.status === 'refund') return `gang withdraw --token ${token} --all${net}`
|
|
931
|
+
return sale.rules.postMint ? `gang mint --token ${token} --shares <n>${net} (or gang buy in the pool)` : `gang buy --token ${token} --amount <quote>${net}`
|
|
932
|
+
}
|