@gangfun/cli 0.22.0 → 0.23.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 +22 -16
- package/README.zh-CN.md +21 -16
- package/package.json +1 -1
- package/src/bond.js +17 -15
- package/src/buyback.js +118 -19
- package/src/chain.js +2 -2
- package/src/combo.js +9 -9
- package/src/creatorfee.js +261 -0
- package/src/discover.js +2 -0
- package/src/fair.js +7 -4
- package/src/fly.js +4 -1
- package/src/gangpad.js +249 -24
- package/src/index.js +53 -14
- package/src/launch.js +33 -1
- package/src/lp.js +52 -15
- package/src/mcp.js +2 -2
- package/src/portfolio.js +25 -5
- package/src/split.js +7 -8
- package/src/v3.js +90 -29
package/src/lp.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, hexToString, isAddress, maxUint128, zeroAddress } from 'viem'
|
|
2
|
-
import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
2
|
+
import { atPad, atTokenPad, GANG_GENS, KIND_UNREAD, gangGens, listedBy, padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
3
|
+
import { notListed, splitPlan, sweepAsset, sweepPlan, sweepReads } from './buyback.js'
|
|
3
4
|
import { walletFor } from './fair.js'
|
|
4
5
|
import { parseNum, revertOf as revertIn, step } from './steps.js'
|
|
5
6
|
|
|
@@ -18,13 +19,12 @@ import { parseNum, revertOf as revertIn, step } from './steps.js'
|
|
|
18
19
|
* for the next chunk.
|
|
19
20
|
* Gas: a chunk takes ~0.53–0.75M (the deposit lets the tax handler sell a chunk of its tax first). The CLI never sets a
|
|
20
21
|
* gas limit: the wallet / node estimates it; a fixed or trimmed limit can revert.
|
|
21
|
-
* Env: GANG_LP_FACTORY / GANG_TESTNET_LP_FACTORY override the
|
|
22
|
+
* Env: GANG_LP_FACTORY / GANG_TESTNET_LP_FACTORY override the create target's factory (gangpad.js).
|
|
22
23
|
*/
|
|
23
24
|
|
|
24
|
-
//
|
|
25
|
-
export const MAINNET_LP_FACTORY =
|
|
26
|
-
|
|
27
|
-
export const TESTNET_LP_FACTORY = '0xA729C60FCa0Bd0D28a55E22126D3fE412AA41591'
|
|
25
|
+
// one factory per GangLaunchpad generation (it is bound to one pad): the create target's (GANG_GENS in gangpad.js)
|
|
26
|
+
export const MAINNET_LP_FACTORY = GANG_GENS.mainnet[0].lpFactory
|
|
27
|
+
export const TESTNET_LP_FACTORY = GANG_GENS.testnet[0].lpFactory
|
|
28
28
|
export const LP_TYPE = 'lp-burn-v1'
|
|
29
29
|
const BPS = 10_000n
|
|
30
30
|
const CHUNK_GAP_S = 4 * 60
|
|
@@ -65,6 +65,7 @@ export const LP_ABI = parseAbi([
|
|
|
65
65
|
'function applyLpBps()',
|
|
66
66
|
'function setPayee(address newPayee)',
|
|
67
67
|
'function split()',
|
|
68
|
+
'function pad() view returns (address)',
|
|
68
69
|
'function releaseDev() returns (uint256)',
|
|
69
70
|
'function addChunk(uint256 minTokensOut) returns (uint256 quoteIn, uint256 tokensIn, uint256 liquidity)',
|
|
70
71
|
'function work(uint256 minOut)',
|
|
@@ -128,8 +129,7 @@ export async function simulateLp(client, from, address, abi, functionName, args
|
|
|
128
129
|
}
|
|
129
130
|
|
|
130
131
|
export function lpFactoryAddress(testnet) {
|
|
131
|
-
return (testnet
|
|
132
|
-
: process.env.GANG_LP_FACTORY || MAINNET_LP_FACTORY) || null
|
|
132
|
+
return gangGens(testnet)[0].lpFactory || null
|
|
133
133
|
}
|
|
134
134
|
|
|
135
135
|
export const lpNotDeployed = (testnet) =>
|
|
@@ -207,8 +207,8 @@ function lpCtx(testnet) {
|
|
|
207
207
|
return { ...net, client, read: (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args }) }
|
|
208
208
|
}
|
|
209
209
|
|
|
210
|
-
const SUBS = ['status', 'set', 'set-payee', 'apply', 'bind', 'release', 'add']
|
|
211
|
-
const USAGE = 'usage: gang lp <status|set|set-payee|apply|bind|release|add> --token <addr> [--pct <0-100>] [--to <addr>] [--slippage 1] [--testnet] — see gang help'
|
|
210
|
+
const SUBS = ['status', 'set', 'set-payee', 'apply', 'bind', 'release', 'split', 'sweep', 'add']
|
|
211
|
+
const USAGE = 'usage: gang lp <status|set|set-payee|apply|bind|release|split|sweep|add> --token <addr> (split / sweep: or --module <addr>) [--pct <0-100>] [--to <addr>] [--asset <addr>|wbnb] [--slippage 1] [--testnet] — see gang help'
|
|
212
212
|
|
|
213
213
|
/** `gang lp <sub>`: the LP splitter of a V3 token (its tax recipient), found from --token. */
|
|
214
214
|
export async function runLp(sub, { opt, flag, out, fail, summarize }) {
|
|
@@ -217,15 +217,30 @@ export async function runLp(sub, { opt, flag, out, fail, summarize }) {
|
|
|
217
217
|
const rawOnly = flag('calldata')
|
|
218
218
|
let ctx
|
|
219
219
|
try { ctx = lpCtx(testnet) } catch (e) { return fail(e.message) }
|
|
220
|
-
|
|
221
|
-
|
|
220
|
+
// split / sweep may name the splitter itself (--module), e.g. the --to of a creator-fee claim
|
|
221
|
+
const named = (sub === 'split' || sub === 'sweep') && flag('module')
|
|
222
|
+
if (named && flag('token')) fail('give --token (its tax recipient is the splitter) or --module, not both')
|
|
223
|
+
let token = opt('token')
|
|
222
224
|
const chainId = Number(ctx.chainId)
|
|
223
225
|
let recipient
|
|
224
|
-
|
|
225
|
-
|
|
226
|
+
if (named) {
|
|
227
|
+
recipient = opt('module')
|
|
228
|
+
if (!isAddress(recipient ?? '')) fail('--module must be an LP splitter address (0x…)', { got: recipient ?? null })
|
|
229
|
+
const pad = await ctx.read(recipient, LP_ABI, 'pad').catch(() => null)
|
|
230
|
+
if (!pad || !atPad(ctx, pad, testnet)) return fail(notListed('LP splitter', testnet), { module: recipient })
|
|
231
|
+
} else {
|
|
232
|
+
if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…)', { got: token ?? null })
|
|
233
|
+
if ((await atTokenPad(ctx, token)) === null) return fail(KIND_UNREAD.error, { token: token, retry: KIND_UNREAD.retry }) // else on the pad of the token's generation
|
|
234
|
+
try { recipient = (await ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]))[3] } catch {
|
|
235
|
+
return fail(`not a V3 token on this pad (${testnet ? 'BSC testnet' : 'BSC mainnet; add --testnet for a testnet token'})`, { token, chainId })
|
|
236
|
+
}
|
|
226
237
|
}
|
|
227
238
|
const s = await lpOf(ctx.read, recipient, { pad: ctx.pad })
|
|
228
|
-
if (!s)
|
|
239
|
+
if (!s) {
|
|
240
|
+
return fail(named ? 'not an LP splitter (lp-burn-v1)' : 'this token\'s tax recipient is not an LP splitter (lp-burn-v1)',
|
|
241
|
+
named ? { module: recipient } : { token, recipient: recipient === zeroAddress ? null : recipient })
|
|
242
|
+
}
|
|
243
|
+
if (named) token = s.token
|
|
229
244
|
const tn = testnet ? ' --testnet' : ''
|
|
230
245
|
// the token pays this splitter, which is bound to another token: it adds liquidity only to that one's pair
|
|
231
246
|
const warning = s.token && s.token.toLowerCase() !== token.toLowerCase()
|
|
@@ -276,6 +291,28 @@ export async function runLp(sub, { opt, flag, out, fail, summarize }) {
|
|
|
276
291
|
return send('applyLpBps', [], { step: 'apply-cut', fromPct: s.lpPct, toPct: s.pendingCut.toPct, note: 'anyone may apply a cut once its notice ran' })
|
|
277
292
|
}
|
|
278
293
|
|
|
294
|
+
if (sub === 'split') {
|
|
295
|
+
if (!(await listedBy(ctx, s.splitter))) return fail(notListed('LP splitter', testnet), { module: s.splitter })
|
|
296
|
+
const [waiting, left] = await Promise.all(['unsplit', 'lpLeft'].map((f) => ctx.read(s.splitter, LP_ABI, f)))
|
|
297
|
+
const plan = splitPlan({ unsplit: waiting, bps: s.lpBps, left, payee: s.payee, part: 'liquidity', leftField: 'lpLeft', symbol: s.quoteSymbol ?? null, unbound: !s.token })
|
|
298
|
+
if (plan.error) return fail(plan.error, { splitter: s.splitter, lpLeft: s.lpLeft, devOwed: s.devOwed })
|
|
299
|
+
return send('split', [], {
|
|
300
|
+
step: 'split', ...plan,
|
|
301
|
+
note: `anyone may: splits what arrived since the last split. ${plan.toPayee} goes to the payee now (should that push fail, it is owed: gang lp release --token ${s.token}${tn}); ${plan.setAside} (${s.lpPct}%) is set aside for the pool, which the keeper adds in chunks once the token trades in its pair (each chunk splits first too, so after graduation this runs by itself)`,
|
|
302
|
+
})
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (sub === 'sweep') {
|
|
306
|
+
if (!(await listedBy(ctx, s.splitter))) return fail(notListed('LP splitter', testnet), { module: s.splitter })
|
|
307
|
+
const asset = sweepAsset(opt, fail, ctx.wbnb)
|
|
308
|
+
const plan = sweepPlan({ asset, ...(await sweepReads(ctx.read, s.splitter, LP_ABI, asset)), payee: s.payee, cmd: 'gang lp' })
|
|
309
|
+
if (plan.error) return fail(plan.error, { splitter: s.splitter, asset })
|
|
310
|
+
return send('sweep', [asset], {
|
|
311
|
+
step: 'sweep', ...plan,
|
|
312
|
+
note: 'anyone may: sends the splitter\'s whole balance of this asset (not its own quote; e.g. a creator fee or another token\'s tax in another quote) to the payee; none of it goes into the pool',
|
|
313
|
+
})
|
|
314
|
+
}
|
|
315
|
+
|
|
279
316
|
if (sub === 'release') {
|
|
280
317
|
if (!(Number(s.devOwed) > 0)) return fail(HINTS.NothingOwed)
|
|
281
318
|
return send('releaseDev', [], { step: 'release', amount: s.devOwed, payee: s.payee, note: 'anyone may; the payee gets what a failed push left owed' })
|
package/src/mcp.js
CHANGED
|
@@ -46,7 +46,7 @@ export const RULES = [
|
|
|
46
46
|
'A gang_execute that timed out or was cancelled on your side keeps running here (the wallet may have sent it): never execute it again or build a new preview for the same trade before checking gang_status or gang_tx with pending: true; then gang_tx (hash, or pending: true) for the result and the note.',
|
|
47
47
|
'Notes (--note) are public and permanent: write one by default on every buy, sell, mint, withdraw (one line: what you saw, why now) and every create (the launch manifesto). Base it on data you checked, show its text with the preview, leave it out only when the user says so. No links. --conf is an honest 0-100.',
|
|
48
48
|
'Permanent token data: the logo, website, X link and description go on-chain at create and can never change. Use only links the user gave; ask once if they have not said. Never host a logo on a temporary file host. Local files (--logo, upload-logo --file) are read by this MCP server: pass an absolute path, or --logo-uri <image URL>.',
|
|
49
|
-
'New tokens go on GangLaunchpad only: create (V3, untaxed unless --buy-tax / --sell-tax) or create --fair (fair mint), or GangFlywheelPad: create --fly (Mint Flywheel). Never an older pad.',
|
|
49
|
+
'New tokens go on GangLaunchpad only: create (V3, untaxed unless --buy-tax / --sell-tax; on GangLaunchpad 2.0 --grad 6|9|12|15 picks the graduation target in BNB, default 9) or create --fair (fair mint), or GangFlywheelPad: create --fly (Mint Flywheel). Never an older pad.',
|
|
50
50
|
'Bonds: before a bond post, tell the user there is no early withdrawal and any sell below the promised holding before settle, anywhere, loses the whole bond. Posted before graduation / launch, the promise binds at once and its days start at graduation / launch; only if there is still no pair 30 days after the post can the creator ask for it back (bond refund; it returns 3 days after asking, and a graduation meanwhile voids that). Relay warning. breakBond (--break-bond) only when the user, told that, still says sell. bond report only when the user asks.',
|
|
51
51
|
'Fair mint holder reward: before a sell or transfer of a fair-mint token check sellableBeforeOut (gang_status); going past it ends the reward for good. confirmOut (--confirm-out) only with the user\'s yes.',
|
|
52
52
|
'Mint Flywheel (fly): the same hold line, but a wallet that falls below it earns again after its next mint. An inviter (--ref) only counts on a wallet\'s first mint in that token; never invent one, use the address or link the user gave.',
|
|
@@ -175,7 +175,7 @@ export const TOOLS = [
|
|
|
175
175
|
{ hash: HASH, pending: { type: 'boolean', description: 'Find the txs of trades approved in the Binance App (no hash needed)' }, testnet: TESTNET },
|
|
176
176
|
(a) => (a.pending ? ['tx', '--pending'] : ['tx', '--hash', a.hash, ...bool('testnet', a.testnet)]), PREVIEW),
|
|
177
177
|
tool('gang_cli', 'Other gang commands',
|
|
178
|
-
'Every other gang command, its flags as separate items (gang_help lists them all): create (V3; create --fair = fair mint; create --fly = Mint Flywheel; launch in one command with --dev-buy / --bond / --buyback / --split / --lp, several of the last three = one combined recipient), mint (--ref <inviter> on a Mint Flywheel token), withdraw, claim, release, fly open-early|launch|invite, quote, list, upload-logo, bond post|topup|raise-hold|extend|status|start|report|settle|refund|burn|tx, buyback status|set|set-payee|apply|bind|release, split status|distribute|release|set-payee|bind, lp status|set|set-payee|apply|bind|release|add, combo status|distribute|release|set-payee|bind|chunk, v3 income, version; the flags no other tool takes (--calldata, --from, …) too. E.g. ["create","--name","My Token","--symbol","MYT","--logo","/Users/me/avatar.png"], ["bond","status","--token","0x…"]. Local files are read by this server: absolute paths, or --logo-uri <image URL>. Writes only preview, as above. execute / watch / help have their own tools.',
|
|
178
|
+
'Every other gang command, its flags as separate items (gang_help lists them all): create (V3; create --fair = fair mint; create --fly = Mint Flywheel; launch in one command with --dev-buy / --bond / --buyback / --split / --lp, several of the last three = one combined recipient), mint (--ref <inviter> on a Mint Flywheel token), withdraw, claim, release, fly open-early|launch|invite, quote, list, upload-logo, bond post|topup|raise-hold|extend|status|start|report|settle|refund|burn|tx, buyback status|set|set-payee|apply|bind|release|split|sweep, split status|distribute|release|set-payee|bind, lp status|set|set-payee|apply|bind|release|split|sweep|add, combo status|distribute|release|set-payee|bind|chunk, creator-fee [--token] [--claim [--to]] (GangLaunchpad 2.0: 70% of the curve fee, kept for the creator), v3 income, version; the flags no other tool takes (--calldata, --from, …) too. E.g. ["create","--name","My Token","--symbol","MYT","--logo","/Users/me/avatar.png"], ["bond","status","--token","0x…"]. Local files are read by this server: absolute paths, or --logo-uri <image URL>. Writes only preview, as above. execute / watch / help have their own tools.',
|
|
179
179
|
{ args: { type: 'array', items: { type: 'string' }, minItems: 1 } }, (a) => a.args, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, ['args']),
|
|
180
180
|
]
|
|
181
181
|
const BY_NAME = new Map(TOOLS.map((t) => [t.name, t]))
|
package/src/portfolio.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `gang portfolio`: one wallet's holdings on every gang.fun track (V3, 打新, 铸币飞轮, V2 / Soft / U / S) in one answer, plus its
|
|
3
|
-
* trading record
|
|
3
|
+
* trading record, the bonds on the tokens it launched and the creator fee they keep for it (GangLaunchpad 2.0).
|
|
4
4
|
*
|
|
5
5
|
* Which tokens: gang.fun's index of the wallet's curve and sale trades (/agents/<addr>/positions), which also gives the
|
|
6
6
|
* cost basis, the average price, the realized PnL and the USD price of each quote. Balance, value and what is claimable
|
|
@@ -168,18 +168,21 @@ function bondRow(l, b) {
|
|
|
168
168
|
/**
|
|
169
169
|
* wallet: 0x address. get(path) → JSON or null (discover.js get). statusOf(kind, token, wallet, position) → the
|
|
170
170
|
* `gang status` result of that kind, or throws (legacy: tokenInfo, or { graduated, myBalanceRaw } for a token no known
|
|
171
|
-
* pad has). bondOf(token) → the `gang bond status` view, or throws.
|
|
171
|
+
* pad has). bondOf(token) → the `gang bond status` view, or throws. creatorFeesOf(wallet) → creatorfee.js creatorFeeList
|
|
172
|
+
* (the wallet's 2.0 tokens and their creator fee, read on chain), or throws; optional.
|
|
172
173
|
*/
|
|
173
|
-
export async function portfolio({ wallet, get, statusOf, bondOf, concurrency = 6 }) {
|
|
174
|
+
export async function portfolio({ wallet, get, statusOf, bondOf, creatorFeesOf, concurrency = 6 }) {
|
|
174
175
|
const w = wallet.toLowerCase()
|
|
175
|
-
const [profile, positions, launches] = await Promise.all([
|
|
176
|
+
const [profile, positions, launches, fees] = await Promise.all([
|
|
176
177
|
get(`/agents/${w}`),
|
|
177
178
|
get(`/agents/${w}/positions`),
|
|
178
179
|
get(`/agents/${w}/launches?limit=${MAX_LAUNCHES}`),
|
|
180
|
+
creatorFeesOf ? creatorFeesOf(wallet).catch((e) => ({ error: e.message })) : null,
|
|
179
181
|
])
|
|
180
182
|
if (!Array.isArray(positions?.items)) throw new Error('gang API has no positions at /agents/<addr>/positions')
|
|
181
183
|
|
|
182
184
|
const errors = []
|
|
185
|
+
if (fees?.error) errors.push({ creatorFee: fees.error })
|
|
183
186
|
const rows = await mapLimit(positions.items, concurrency, async (p) => {
|
|
184
187
|
const kind = KIND[p.track]
|
|
185
188
|
if (!kind) return null
|
|
@@ -228,6 +231,7 @@ export async function portfolio({ wallet, get, statusOf, bondOf, concurrency = 6
|
|
|
228
231
|
launches: l.count ?? null, launchesGraduated: l.graduated ?? null,
|
|
229
232
|
},
|
|
230
233
|
bonds,
|
|
234
|
+
...creatorFeeRows(fees),
|
|
231
235
|
...(launches?.hasMore && { bondsNote: `bonds were looked up on the newest ${MAX_LAUNCHES} launches only` }),
|
|
232
236
|
...(errors.length && { errors }),
|
|
233
237
|
note: 'Holdings are the tokens gang.fun saw this wallet trade on a curve or sale; balance and value are read on chain now. '
|
|
@@ -235,4 +239,20 @@ export async function portfolio({ wallet, get, statusOf, bondOf, concurrency = 6
|
|
|
235
239
|
}
|
|
236
240
|
}
|
|
237
241
|
|
|
238
|
-
|
|
242
|
+
/**
|
|
243
|
+
* The 2.0 creator fee waiting for this wallet on the tokens it created: { creatorFees: { tokens, totals } } with the
|
|
244
|
+
* tokens that have some, or nothing when the network has no 2.0 pad (or the read failed: then it is in errors).
|
|
245
|
+
*/
|
|
246
|
+
function creatorFeeRows(fees) {
|
|
247
|
+
if (!fees?.scanned?.length) return {}
|
|
248
|
+
const due = fees.tokens.filter((x) => x.claimableRaw !== '0')
|
|
249
|
+
return {
|
|
250
|
+
creatorFees: {
|
|
251
|
+
tokens: due.map((x) => ({ token: x.token, symbol: x.symbol, quote: x.quoteSymbol, claimable: num(x.claimable), padGen: x.padGen, next: `gang creator-fee --token ${x.token} --claim` })),
|
|
252
|
+
totals: fees.totals.filter((x) => num(x.claimable) > 0),
|
|
253
|
+
note: 'GangLaunchpad 2.0 keeps 70% of the 1% curve fee of your V3 tokens for you; gang creator-fee lists every one of them',
|
|
254
|
+
},
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export const _test = { holdingOf, bondRow, withBond, mapLimit, creatorFeeRows }
|
package/src/split.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createPublicClient, parseAbi, encodeFunctionData, formatUnits, getAddress, hexToString, isAddress, maxUint256, parseUnits, zeroAddress } from 'viem'
|
|
2
|
-
import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
2
|
+
import { atTokenPad, GANG_GENS, KIND_UNREAD, gangGens, padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
3
3
|
import { walletFor } from './fair.js'
|
|
4
4
|
import { parseAmount, revertOf as revertIn, step } from './steps.js'
|
|
5
5
|
|
|
@@ -15,13 +15,12 @@ import { parseAmount, revertOf as revertIn, step } from './steps.js'
|
|
|
15
15
|
* Gas: each payee's push needs about 365k gas left before it (PUSH_GAS 300k × 64/63 + a 60k reserve), so a split needs a
|
|
16
16
|
* gas limit far above the gas it uses. The CLI never sets or lowers one: the wallet / node estimates it (eth_estimateGas
|
|
17
17
|
* searches for a limit that passes); a lower limit reverts PushStarved, and nothing moves.
|
|
18
|
-
* Env: GANG_SPLIT_FACTORY / GANG_TESTNET_SPLIT_FACTORY override the
|
|
18
|
+
* Env: GANG_SPLIT_FACTORY / GANG_TESTNET_SPLIT_FACTORY override the create target's factory (gangpad.js).
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
|
-
//
|
|
22
|
-
export const MAINNET_SPLIT_FACTORY =
|
|
23
|
-
|
|
24
|
-
export const TESTNET_SPLIT_FACTORY = '0x5F7dC7502E945A860Cf49cca72dA8bD60Fb1567E'
|
|
21
|
+
// one factory per GangLaunchpad generation (it is bound to one pad): the create target's (GANG_GENS in gangpad.js)
|
|
22
|
+
export const MAINNET_SPLIT_FACTORY = GANG_GENS.mainnet[0].splitFactory
|
|
23
|
+
export const TESTNET_SPLIT_FACTORY = GANG_GENS.testnet[0].splitFactory
|
|
25
24
|
export const SPLIT_TYPE = 'split-v1'
|
|
26
25
|
export const MAX_PAYEES = 10
|
|
27
26
|
const BPS = 10_000
|
|
@@ -110,8 +109,7 @@ export async function simulateSplit(client, from, address, abi, functionName, ar
|
|
|
110
109
|
}
|
|
111
110
|
|
|
112
111
|
export function splitFactoryAddress(testnet) {
|
|
113
|
-
return (testnet
|
|
114
|
-
: process.env.GANG_SPLIT_FACTORY || MAINNET_SPLIT_FACTORY) || null
|
|
112
|
+
return gangGens(testnet)[0].splitFactory || null
|
|
115
113
|
}
|
|
116
114
|
|
|
117
115
|
export const splitNotDeployed = (testnet) =>
|
|
@@ -295,6 +293,7 @@ export async function runSplit(sub, { opt, flag, out, fail, summarize }) {
|
|
|
295
293
|
} else {
|
|
296
294
|
token = opt('token')
|
|
297
295
|
if (!isAddress(token ?? '')) fail('--token must be a V3 token address (0x…), or name the module with --module <addr>', { got: token ?? null })
|
|
296
|
+
if ((await atTokenPad(ctx, token)) === null) return fail(KIND_UNREAD.error, { token: token, retry: KIND_UNREAD.retry }) // else on the pad of the token's generation
|
|
298
297
|
try {
|
|
299
298
|
const [creator, quote] = await ctx.read(ctx.pad, PAD_ABI, 'curves', [token])
|
|
300
299
|
if (creator === zeroAddress) throw new Error('not a curve')
|
package/src/v3.js
CHANGED
|
@@ -3,7 +3,8 @@ import { decimalsOf, defaultRefPool, dividendOf, VAULT_ABI, fundingStep as fund,
|
|
|
3
3
|
import { API } from './discover.js'
|
|
4
4
|
import { UA } from './version.js'
|
|
5
5
|
import { walletFor } from './fair.js'
|
|
6
|
-
import { MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
|
|
6
|
+
import { atTokenPad, CREATOR_FEE_ABI, GRAD_TARGET_ABI, gradTargetBnbOf, gradTiersOf, KIND_UNREAD, MERGED_ERRORS_ABI, MERGED_HINTS, NOT_ON_MAINNET, notThisKind, padNets, rpcTransport } from './gangpad.js'
|
|
7
|
+
import { createNote, curveCreatorFee } from './creatorfee.js'
|
|
7
8
|
import { poolPayBnb, poolTrade } from './pool.js'
|
|
8
9
|
import { bondGuard } from './bond.js'
|
|
9
10
|
import { splitterOf } from './buyback.js'
|
|
@@ -23,6 +24,7 @@ export const V3_NETS = padNets('v3')
|
|
|
23
24
|
const TAX = '(uint16 buyTaxBps, uint16 sellTaxBps, uint16 dividendBps, address recipient)'
|
|
24
25
|
const PAD_ABI = parseAbi([
|
|
25
26
|
`function create(string name, string symbol, string logoURI, string metaURI, address quote, address refPool, ${TAX} tax) returns (address)`,
|
|
27
|
+
`function createWithGradTarget(string name, string symbol, string logoURI, string metaURI, address quote, address refPool, ${TAX} tax, uint256 gradBnb) returns (address)`,
|
|
26
28
|
'function buy(address token, uint256 quoteIn, uint256 minTokensOut) returns (uint256)',
|
|
27
29
|
'function sell(address token, uint256 tokensIn, uint256 minQuoteOut) returns (uint256)',
|
|
28
30
|
`function checkTaxConfig(${TAX} tax) view returns (bool ok, string reason)`,
|
|
@@ -74,6 +76,7 @@ const HINTS = {
|
|
|
74
76
|
BadTaxConfig: 'a tax setting is out of bounds, or the recipient is neither you nor on the whitelist: see reason',
|
|
75
77
|
NotAgent: 'this wallet holds no Agent ID; V3 create and curve trades are Agent-only',
|
|
76
78
|
WalletCapReached: 'this wallet already holds the per-wallet cap (1% of supply)',
|
|
79
|
+
BadGradTarget: 'the graduation target (--grad) must be one of the pad\'s GRAD_BNB_TIERS: 6 / 9 / 12 / 15 BNB raised',
|
|
77
80
|
AlreadyGraduated: 'the token graduated: re-run gang buy / gang sell, which now trade it in the PancakeSwap pool',
|
|
78
81
|
Slippage: 'the price moved past --slippage; re-run to re-quote',
|
|
79
82
|
RefPoolRequired: 'a non-WBNB --quote needs --ref-pool: a Pancake V2 pair or V3 pool that holds the quote token',
|
|
@@ -95,8 +98,8 @@ const HINTS = {
|
|
|
95
98
|
VaultFloorTooHigh: 'the platform\'s dividend vault requires a larger holding than V3 dividends allow (10,000 tokens), so a dividend token can\'t be created right now; --dividend 0 still works, or ask gang to fix the vault setting',
|
|
96
99
|
}
|
|
97
100
|
|
|
98
|
-
/** What `gang tx` decodes a V3 trade's logs with (the pad, the tax router, the dividend vault). */
|
|
99
|
-
export const V3_EVENT_ABIS = [PAD_ABI, TAX_ROUTER_ABI, VAULT_ABI]
|
|
101
|
+
/** What `gang tx` decodes a V3 trade's logs with (the pad and its 2.0 creator fee, the tax router, the dividend vault). */
|
|
102
|
+
export const V3_EVENT_ABIS = [PAD_ABI, CREATOR_FEE_ABI, GRAD_TARGET_ABI, TAX_ROUTER_ABI, VAULT_ABI]
|
|
100
103
|
|
|
101
104
|
export function v3Ctx(testnet) {
|
|
102
105
|
const net = V3_NETS[testnet ? 'testnet' : 'mainnet']
|
|
@@ -107,11 +110,19 @@ export function v3Ctx(testnet) {
|
|
|
107
110
|
|
|
108
111
|
const symbolOf = async (ctx, token) => { try { return await ctx.read(token, ERC20_ABI, 'symbol') } catch { return null } }
|
|
109
112
|
const pct = (bps) => Number(bps) / 100
|
|
113
|
+
const bnbOf = (wei) => Number(wei / 10n ** 15n) / 1000
|
|
114
|
+
/**
|
|
115
|
+
* The graduation target in words. A non-WBNB quote fixes the amount in the quote at create (`inQuote`, e.g. "1234.5
|
|
116
|
+
* USDT"): the BNB figure is what that was worth then, a nominal target whose BNB worth moves with the quote's price.
|
|
117
|
+
*/
|
|
118
|
+
const gradLine = (bnb, inQuote) => (inQuote
|
|
119
|
+
? `the curve graduates into PancakeSwap once ${inQuote} is raised: ${bnb} BNB priced in the quote at create, fixed in the quote, so what it is worth in BNB moves with the quote's price (market cap at graduation ≈ 5× the target)`
|
|
120
|
+
: `the curve graduates into PancakeSwap once ${bnb} BNB is raised (market cap then ≈ ${bnb * 5} BNB)`)
|
|
110
121
|
const VIRTUAL_TOKEN = 1_066_666_666_666_666_666_666_666_667n
|
|
111
122
|
const ceilDiv = (a, b) => (a + b - 1n) / b
|
|
112
123
|
|
|
113
124
|
/** Revert name (+ BadTaxConfig reason) of a failed call, or null when it was the RPC. */
|
|
114
|
-
const revertOf = (e) => revertIn(e, [PAD_ABI, TAX_ROUTER_ABI, GANG_ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
|
|
125
|
+
const revertOf = (e) => revertIn(e, [PAD_ABI, CREATOR_FEE_ABI, GRAD_TARGET_ABI, TAX_ROUTER_ABI, GANG_ROUTER_ABI, MERGED_ERRORS_ABI], { ...MERGED_HINTS, ...ROUTER_HINTS, ...HINTS })
|
|
115
126
|
|
|
116
127
|
/** eth_call `data` from `from`: { result } when it passes, { failed } with the revert (or RPC error) otherwise. */
|
|
117
128
|
async function simulate(ctx, from, to, abi, functionName, args, value = 0n) {
|
|
@@ -159,9 +170,11 @@ export async function curveOf(ctx, token) {
|
|
|
159
170
|
const [creator, quote, realQuote, sold, gradAmt, virtualQuote, graduated, buyTaxBps, sellTaxBps, dividendBps, pair] = c
|
|
160
171
|
if (creator === zeroAddress) return null
|
|
161
172
|
// the recipient is not in curves(): it lives on the tax handler's route, read back through taxConfigOf
|
|
162
|
-
const [{ handler, router, registry }, remaining, tax] = await Promise.all([
|
|
173
|
+
const [{ handler, router, registry }, remaining, tax, targetBnb] = await Promise.all([
|
|
163
174
|
taxContracts(ctx),
|
|
164
175
|
ctx.read(ctx.pad, PAD_ABI, 'graduationRemaining', [token]), ctx.read(ctx.pad, PAD_ABI, 'taxConfigOf', [token]),
|
|
176
|
+
// the target in BNB raised (2.0: the creator's pick); graduationAt below is the same target in the quote
|
|
177
|
+
gradTargetBnbOf(ctx, token).catch(() => null),
|
|
165
178
|
])
|
|
166
179
|
const recipient = tax[3] === zeroAddress ? null : tax[3]
|
|
167
180
|
// §22: the creator may be its own recipient without a listing; say so, the platform did not review it
|
|
@@ -184,23 +197,28 @@ export async function curveOf(ctx, token) {
|
|
|
184
197
|
buyTaxPct: pct(buyTaxBps), sellTaxPct: pct(sellTaxBps), dividendPct: pct(dividendBps), recipient, recipientLabel: label,
|
|
185
198
|
...(recipientIsCreator && { recipientIsCreator: true, recipientNote: 'the recipient is the creator itself, not reviewed by the platform' }),
|
|
186
199
|
raised: await units(ctx, quote, graduated ? gradAmt : realQuote), graduationAt: await units(ctx, quote, gradAmt),
|
|
187
|
-
toGraduation: await units(ctx, quote, remaining),
|
|
200
|
+
graduationTargetBnb: targetBnb, toGraduation: await units(ctx, quote, remaining),
|
|
188
201
|
progressPct: graduated ? 100 : gradAmt > 0n ? Number((realQuote * 10_000n) / gradAmt) / 100 : 0,
|
|
189
202
|
priceQuote: await units(ctx, quote, price), priceFrom: graduated ? 'pool' : 'curve', priceRaw: price,
|
|
190
|
-
owedToRecipient: await units(ctx, quote, owed), owedRaw: owed, reserveTokenRaw, curveRaw: { realQuote, sold, virtualQuote },
|
|
203
|
+
owedToRecipient: await units(ctx, quote, owed), owedRaw: owed, reserveTokenRaw, curveRaw: { realQuote, sold, virtualQuote, remaining },
|
|
191
204
|
}
|
|
192
205
|
}
|
|
193
206
|
|
|
194
207
|
/**
|
|
195
|
-
* What a curve buy of `quoteIn` that gets `tokensOut` spends, the fee included
|
|
196
|
-
*
|
|
208
|
+
* What a curve buy of `quoteIn` that gets `tokensOut` spends, the fee included, as CurveLogic trims it: first to the
|
|
209
|
+
* token's own graduation amount (what is still to raise), then to the wallet cap (`room`, _quoteInFor), each followed by
|
|
210
|
+
* _recomputeFee. { spent, cut: null | 'graduation' | 'wallet cap' }: the rest of quoteIn is refunded.
|
|
197
211
|
*/
|
|
198
|
-
async function spentFor(ctx, c, quoteIn, tokensOut) {
|
|
199
|
-
const { realQuote, sold, virtualQuote } = c.curveRaw
|
|
200
|
-
const net = ceilDiv(virtualQuote * VIRTUAL_TOKEN, VIRTUAL_TOKEN - sold - tokensOut) - (virtualQuote + realQuote)
|
|
212
|
+
async function spentFor(ctx, c, quoteIn, tokensOut, room) {
|
|
213
|
+
const { realQuote, sold, virtualQuote, remaining } = c.curveRaw
|
|
201
214
|
const feeBps = BigInt(Math.round((await feesOf(ctx)).curveFeePct * 100))
|
|
202
|
-
const gross = ceilDiv(net * 10_000n, 10_000n - feeBps)
|
|
203
|
-
|
|
215
|
+
const gross = (net) => { const g = ceilDiv(net * 10_000n, 10_000n - feeBps); return g < quoteIn ? g : quoteIn }
|
|
216
|
+
if (room !== undefined && tokensOut === room) {
|
|
217
|
+
const net = ceilDiv(virtualQuote * VIRTUAL_TOKEN, VIRTUAL_TOKEN - sold - tokensOut) - (virtualQuote + realQuote)
|
|
218
|
+
return { spent: gross(net), cut: 'wallet cap' }
|
|
219
|
+
}
|
|
220
|
+
if (quoteIn - (quoteIn * feeBps) / 10_000n > remaining) return { spent: gross(remaining), cut: 'graduation' }
|
|
221
|
+
return { spent: quoteIn, cut: null }
|
|
204
222
|
}
|
|
205
223
|
|
|
206
224
|
/** `token` funding for `need` toward the pad (wrap BNB, then approve): a step object, or null when ready. */
|
|
@@ -256,12 +274,17 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
256
274
|
return out({ success: true, status, items: (r.items || []).map((x) => ({
|
|
257
275
|
token: x.address, symbol: x.symbol, buyTaxPct: pct(x.buyTaxBps), sellTaxPct: pct(x.sellTaxBps), dividendPct: pct(x.dividendBps),
|
|
258
276
|
recipient: x.recipient, recipientLabel: x.recipientLabel, quote: x.quoteSymbol, progressPct: x.progressPct, graduated: x.graduated,
|
|
277
|
+
// the target per token (2.0: the creator's pick), never a fixed 15 BNB: in the quote from gradAmt, in BNB when gang.fun sends it
|
|
278
|
+
...(x.gradAmt != null && { graduationAt: f(x.gradAmt, x.quoteDecimals) }),
|
|
279
|
+
...(x.gradTargetBnb != null && { graduationTargetBnb: Number(x.gradTargetBnb) }),
|
|
259
280
|
chainId: x.chainId, link: `https://gang.fun/token/${x.address}`,
|
|
260
281
|
})) })
|
|
261
282
|
}
|
|
262
283
|
|
|
263
284
|
let ctx
|
|
264
285
|
try { ctx = v3Ctx(testnet) } catch (e) { return fail(e.message) }
|
|
286
|
+
// a token is served by the GangLaunchpad generation that has it (its pad, router, GangBond); a create goes to the newest
|
|
287
|
+
if (sub !== 'create' && sub !== 'tx' && (await atTokenPad(ctx, opt('token'))) === null) return fail(KIND_UNREAD.error, { token: opt('token'), retry: KIND_UNREAD.retry })
|
|
265
288
|
// not a curve on this pad: on the merged pad it may be a 打新 token (kindOf), so point at `gang fair`
|
|
266
289
|
const notV3 = async (token) => {
|
|
267
290
|
const { error, kind } = await notThisKind(ctx, token, 'v3', net)
|
|
@@ -295,8 +318,13 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
295
318
|
? { warning: `this token pays its tax to the LP splitter, but it is bound to another token (${lp.token}): the liquidity goes to that token's pair` } : null
|
|
296
319
|
const splitWarn = split && split.token && split.token.toLowerCase() !== token.toLowerCase()
|
|
297
320
|
? { warning: `this token pays its tax to the split module, but the module is bound to another token (${split.token}): the keeper never splits this token's tax (${c.quote}); it is split only by hand (gang split distribute --token ${token}${net} --asset ${c.quote})` } : null
|
|
321
|
+
// 2.0: the creator's part of the curve fee, waiting on the pad
|
|
322
|
+
const gen = await curveCreatorFee(ctx, token, c, net)
|
|
323
|
+
const nonWbnb = c.quote.toLowerCase() !== String(ctx.wbnb).toLowerCase()
|
|
324
|
+
const graduationNote = c.graduationTargetBnb != null && !c.graduated
|
|
325
|
+
? gradLine(c.graduationTargetBnb, nonWbnb ? `${c.graduationAt} ${c.quoteSymbol || 'of the quote'}` : null) : null
|
|
298
326
|
return out({
|
|
299
|
-
success: true, chainId: Number(ctx.chainId), ...fees, ...pub, taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
|
|
327
|
+
success: true, chainId: Number(ctx.chainId), ...fees, ...pub, ...gen, ...(graduationNote && { graduationNote }), taxNote, ...(swapBack && { swapBack }), ...(buyback && { buyback }),
|
|
300
328
|
...(split && { split: { ...split, ...splitWarn } }), ...(lp && { lp: { ...lp, ...lpWarn } }),
|
|
301
329
|
...(combo && { combo: { ...combo, ...(comboWarning && { warning: comboWarning }) } }),
|
|
302
330
|
})
|
|
@@ -312,9 +340,12 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
312
340
|
const { claimableRaw: _r, ...dividend } = c.dividendPct > 0 ? await dividendOf(ctx, vault, token, me, c.quote, c.priceRaw) : {}
|
|
313
341
|
// graduated: what selling the whole balance into the pool pays now (sell tax and the chunk sold first included)
|
|
314
342
|
const q = c.graduated && c.pair && bal > 0n ? await poolSellQuote(ctx, c.taxHandler, token, bal) : null
|
|
343
|
+
// the creator's own view also shows its creator fee (2.0)
|
|
344
|
+
const { creatorFee } = me.toLowerCase() === c.creator.toLowerCase() ? await curveCreatorFee(ctx, token, c, net) : {}
|
|
315
345
|
return out({
|
|
316
346
|
success: true, chainId: Number(ctx.chainId), wallet: me, token, quote: c.quoteSymbol, graduated: c.graduated,
|
|
317
|
-
balance: formatUnits(bal, 18), dividendPct: c.dividendPct,
|
|
347
|
+
balance: formatUnits(bal, 18), dividendPct: c.dividendPct, ...(creatorFee && { creatorFee }),
|
|
348
|
+
graduationTargetBnb: c.graduationTargetBnb, graduationAt: c.graduationAt, progressPct: c.progressPct,
|
|
318
349
|
...(q && {
|
|
319
350
|
poolSellAll: {
|
|
320
351
|
expectOut: await units(ctx, c.quote, q.out), minOut: await units(ctx, c.quote, minOf(q.out, slippage)), slippagePct: slippage,
|
|
@@ -367,6 +398,9 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
367
398
|
if (!(n >= 1 && n <= 5)) fail(`--${f} must be a number between 1 and 5 (in %); for an untaxed token leave out both tax flags (or give both as 0)`, { got: opt(f) ?? null })
|
|
368
399
|
return n
|
|
369
400
|
}
|
|
401
|
+
// --grad: the graduation target in BNB raised, one of the pad's GRAD_BNB_TIERS (2.0); left out: the pad's default
|
|
402
|
+
const grad = flag('grad') ? Number(opt('grad')) : null
|
|
403
|
+
if (grad !== null && !(grad > 0)) fail('--grad must be the graduation target in BNB raised: 6, 9, 12 or 15', { got: opt('grad') ?? null })
|
|
370
404
|
const buyTax = taxed ? taxOf('buy-tax') : 0
|
|
371
405
|
const sellTax = taxed ? taxOf('sell-tax') : 0
|
|
372
406
|
const dividend = taxed ? parseNum(fail, 'dividend', opt('dividend', '0'), 0, 100) : 0
|
|
@@ -379,6 +413,12 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
379
413
|
const refPool = flag('ref-pool') ? opt('ref-pool') : (defaultRefPool(ctx.chainId, quote) ?? zeroAddress)
|
|
380
414
|
if (!isAddress(quote ?? '') || !isAddress(refPool ?? '')) fail('--quote / --ref-pool must be 0x addresses')
|
|
381
415
|
const tax = { buyTaxBps: Math.round(buyTax * 100), sellTaxBps: Math.round(sellTax * 100), dividendBps: Math.round(dividend * 100), recipient }
|
|
416
|
+
// --grad first: a pad without the pick (1.0) refuses it whatever else the create would say
|
|
417
|
+
const tiers = await gradTiersOf(ctx)
|
|
418
|
+
if (grad !== null && !tiers) {
|
|
419
|
+
fail(`--grad: this GangLaunchpad${ctx.gen ? ` (${ctx.gen})` : ''} has no graduation target to pick; every curve graduates at ${bnbOf(await ctx.read(ctx.pad, GRAD_TARGET_ABI, 'TARGET_GRAD_BNB'))} BNB raised: leave --grad out`)
|
|
420
|
+
}
|
|
421
|
+
if (grad !== null && !tiers.includes(grad)) fail(`--grad must be one of ${tiers.join(' / ')} (BNB raised)`, { got: opt('grad') })
|
|
382
422
|
// the recipient may be the creator itself: checkTaxConfigFor knows who creates (a pad without it: checkTaxConfig)
|
|
383
423
|
const [ok, reason] = await ctx.read(ctx.pad, PAD_ABI, 'checkTaxConfigFor', [me, tax]).catch((e) => {
|
|
384
424
|
if (!noSuchFunction(e)) throw e
|
|
@@ -386,15 +426,22 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
386
426
|
})
|
|
387
427
|
if (!ok) fail(`tax setting refused: ${reason}`, { hint: HINTS.BadTaxConfig, tax: { buyTax, sellTax, dividend, recipient } })
|
|
388
428
|
if (!(await ctx.read(ctx.pad, PAD_ABI, 'isAgent', [me]))) fail('this wallet holds no Agent ID; V3 create is Agent-only', { wallet: me })
|
|
389
|
-
//
|
|
429
|
+
// the target: --grad (2.0, createWithGradTarget) or the pad's default (create: 9 BNB on 2.0, 15 on 1.0)
|
|
430
|
+
const targetBnb = grad ?? bnbOf(await ctx.read(ctx.pad, GRAD_TARGET_ABI, 'TARGET_GRAD_BNB'))
|
|
431
|
+
// the target in the quote: WBNB as is; a fixed rate in QuoteRegistry; else --ref-pool prices it. On 2.0 it is read
|
|
432
|
+
// with graduationAmountFor for the very target the create takes, so GradAmtTooSmall / QuoteAmountTooLarge show here
|
|
390
433
|
let gradAmt
|
|
391
|
-
try {
|
|
434
|
+
try {
|
|
435
|
+
gradAmt = tiers ? await ctx.read(ctx.pad, GRAD_TARGET_ABI, 'graduationAmountFor', [quote, refPool, parseUnits(String(targetBnb), 18)])
|
|
436
|
+
: await ctx.read(ctx.pad, PAD_ABI, 'graduationAmountOf', [quote, refPool])
|
|
437
|
+
} catch (e) {
|
|
392
438
|
return fail('cannot price the graduation target in this quote', revertOf(e) || { detail: e.shortMessage || e.message })
|
|
393
439
|
}
|
|
394
|
-
const
|
|
395
|
-
|
|
440
|
+
const fn = grad !== null ? 'createWithGradTarget' : 'create'
|
|
441
|
+
const argsOf = (logoURI, metaURI) => [name, symbol, logoURI, metaURI, quote, refPool, tax, ...(grad !== null ? [parseUnits(String(grad), 18)] : [])]
|
|
442
|
+
const createData = (logoURI, metaURI) => encodeFunctionData({ abi: PAD_ABI, functionName: fn, args: argsOf(logoURI, metaURI) })
|
|
396
443
|
// the logo / metadata strings never decide a revert: dry-run without them, so a create that would fail uploads nothing
|
|
397
|
-
const dry = await simulate(ctx, me, ctx.pad, PAD_ABI,
|
|
444
|
+
const dry = await simulate(ctx, me, ctx.pad, PAD_ABI, fn, argsOf('', ''))
|
|
398
445
|
if (dry.failed) return out({ success: false, step: 'create', ...dry.failed })
|
|
399
446
|
const logo = await resolveLogo()
|
|
400
447
|
const meta = await resolveMeta({ name, symbol, logoURI: logo.logoURI })
|
|
@@ -405,10 +452,12 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
405
452
|
}
|
|
406
453
|
const rest = 100 - dividend
|
|
407
454
|
const fees = await feesOf(ctx)
|
|
455
|
+
const creatorFee = await createNote(ctx, net)
|
|
408
456
|
return out(notes.step(ctx, { from: me, to: ctx.pad, data: createData(logo.logoURI, meta.metaURI) }, {
|
|
409
457
|
step: 'create', chainId: Number(ctx.chainId), name, symbol, logoURI: logo.logoURI, ...(logo.uploaded && { uploaded: true }),
|
|
410
458
|
metaURI: meta.metaURI, metadata: meta.metadata,
|
|
411
|
-
quote: (await symbolOf(ctx, quote)) || quote, graduationAt: await units(ctx, quote, gradAmt),
|
|
459
|
+
quote: (await symbolOf(ctx, quote)) || quote, graduationTargetBnb: targetBnb, graduationAt: await units(ctx, quote, gradAmt),
|
|
460
|
+
graduation: `${gradLine(targetBnb, quote.toLowerCase() === String(ctx.wbnb).toLowerCase() ? null : `${await units(ctx, quote, gradAmt)} ${(await symbolOf(ctx, quote)) || 'of the quote'}`)}${tiers ? `; ${grad !== null ? 'picked with --grad' : 'the default'}, --grad picks ${tiers.join(' / ')}` : ''}`,
|
|
412
461
|
...(refPool !== zeroAddress && quote.toLowerCase() !== String(ctx.wbnb).toLowerCase() && { refPool }),
|
|
413
462
|
buyTaxPct: buyTax, sellTaxPct: sellTax, dividendPct: dividend,
|
|
414
463
|
recipient: recipient === zeroAddress ? null : recipient, recipientLabel: selfRecipient ? 'you (the creator)' : label, tokenIfNext: dry.result,
|
|
@@ -416,6 +465,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
416
465
|
? `of each ${buyTax}% buy / ${sellTax}% sell tax in the PancakeSwap pool (after graduation; the curve charges no tax): ${fees.platformTaxPct}% of volume to the platform, then ${dividend}% of the rest to holders, ${rest}% to the recipient in the quote`
|
|
417
466
|
+ (dividend > 0 ? '; if no holder has 10,000+ tokens when a tax is paid, the holders\' part goes to the recipient too' : '')
|
|
418
467
|
: 'untaxed: no tax in the PancakeSwap pool after graduation, no dividend, no recipient',
|
|
468
|
+
...(creatorFee && { creatorFee }),
|
|
419
469
|
note: `${taxed ? 'tax rates and recipient are' : 'untaxed is'} fixed at create. Curve trades pay only the ${fees.curveFeePct}% fee, no tax${taxed ? ': the tax starts in the pool after graduation' : ''}. tokenIfNext changes if another create lands first: the real address is the Created event from \`gang tx --hash …\`.`,
|
|
420
470
|
}, 'create'))
|
|
421
471
|
}
|
|
@@ -439,17 +489,28 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
439
489
|
}
|
|
440
490
|
const me = walletFor(ctx, opt('from'))
|
|
441
491
|
if (!(await ctx.read(ctx.pad, PAD_ABI, 'isAgent', [me]))) fail('this wallet holds no Agent ID; curve trades are Agent-only', { wallet: me })
|
|
442
|
-
|
|
492
|
+
const room = await ctx.read(ctx.pad, PAD_ABI, 'walletRoom', [token, me])
|
|
493
|
+
if (room === 0n) fail(HINTS.WalletCapReached)
|
|
443
494
|
if (!flag('amount') && !flag('bnb')) fail('--amount <quote to spend> required (the 1% curve fee included; no tax on the curve)')
|
|
444
495
|
const raw = parseAmount(fail, flag('amount') ? 'amount' : 'bnb', opt('amount') ?? opt('bnb'))
|
|
445
496
|
const quoteIn = parseUnits(raw, await decimalsOf(ctx, c.quote))
|
|
446
497
|
const slippage = parseSlippage(fail, opt('slippage', '1'))
|
|
447
498
|
// asked from gang.fun before any wrap / approve round, so a follow that can't count fails first
|
|
448
499
|
const follow = await notes.follow(token, me)
|
|
449
|
-
const priced = async (tokensOut) => follow && notes.priced(follow, token, await spentFor(ctx, c, quoteIn, tokensOut), await decimalsOf(ctx, c.quote))
|
|
450
|
-
|
|
500
|
+
const priced = async (tokensOut) => follow && notes.priced(follow, token, (await spentFor(ctx, c, quoteIn, tokensOut, room)).spent, await decimalsOf(ctx, c.quote))
|
|
501
|
+
// the pad trims a buy past the token's own graduation amount or the wallet cap and refunds the rest: say what it spends
|
|
502
|
+
const cutOf = async (tokensOut, refundAs) => {
|
|
503
|
+
const { spent, cut } = await spentFor(ctx, c, quoteIn, tokensOut, room)
|
|
504
|
+
if (!cut) return {}
|
|
505
|
+
const [s, r] = await Promise.all([units(ctx, c.quote, spent), units(ctx, c.quote, quoteIn - spent)])
|
|
506
|
+
const why = cut === 'graduation'
|
|
507
|
+
? `only ${c.toGraduation} ${c.quoteSymbol} is left to raise before this token graduates at ${c.graduationAt} ${c.quoteSymbol}`
|
|
508
|
+
: `the 1% wallet cap leaves this wallet room for ${formatUnits(tokensOut, 18)} more tokens only`
|
|
509
|
+
return { spent: s, refund: r, cutBy: cut, cutNote: `${why}: the buy spends ${s} ${c.quoteSymbol} (fee included) and refunds ${r} ${refundAs}` }
|
|
510
|
+
}
|
|
511
|
+
const extra = async (tokensOut, minOut, refundAs = c.quoteSymbol) => ({
|
|
451
512
|
step: 'buy', chainId: Number(ctx.chainId), token, spend: raw, quote: c.quoteSymbol, expectTokens: formatUnits(tokensOut, 18),
|
|
452
|
-
minTokensOut: formatUnits(minOut, 18), curveTaxPct: 0, ...(c.buyTaxPct > 0 && { poolBuyTaxPct: c.buyTaxPct }),
|
|
513
|
+
minTokensOut: formatUnits(minOut, 18), ...(await cutOf(tokensOut, refundAs)), curveTaxPct: 0, ...(c.buyTaxPct > 0 && { poolBuyTaxPct: c.buyTaxPct }),
|
|
453
514
|
})
|
|
454
515
|
// WBNB-quoted: pay native BNB through the router in one tx (it wraps; tokens land in this wallet; a cap / graduation
|
|
455
516
|
// refund comes back from the pad to this wallet as WBNB, not BNB)
|
|
@@ -465,7 +526,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
465
526
|
const minOut = minOf(sim.result, slippage)
|
|
466
527
|
const data = encodeFunctionData({ abi: GANG_ROUTER_ABI, functionName: 'v3BuyBNB', args: [token, minOut, routerDeadline()] })
|
|
467
528
|
return out(notes.step(ctx, { from: me, to: ctx.router, data, value: quoteIn }, {
|
|
468
|
-
...extra(sim.result, minOut), via: 'router', curveFeePct: (await feesOf(ctx)).curveFeePct,
|
|
529
|
+
...(await extra(sim.result, minOut, 'WBNB (not BNB)')), via: 'router', curveFeePct: (await feesOf(ctx)).curveFeePct,
|
|
469
530
|
note: 'paid in BNB through GangRouter; spend includes the 1% curve fee (no tax on the curve; the buy tax applies only in the pool after graduation); at the 1% wallet cap or the graduation cut the excess comes back to this wallet as WBNB (not BNB)',
|
|
470
531
|
}, 'buy', await priced(sim.result)))
|
|
471
532
|
}
|
|
@@ -475,7 +536,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
475
536
|
if (sim.failed) return out({ success: false, step: 'buy', ...sim.failed })
|
|
476
537
|
const minOut = minOf(sim.result, slippage)
|
|
477
538
|
return out(notes.step(ctx, { from: me, to: ctx.pad, data: encodeFunctionData({ abi: PAD_ABI, functionName: 'buy', args: [token, quoteIn, minOut] }) }, {
|
|
478
|
-
...extra(sim.result, minOut), curveFeePct: (await feesOf(ctx)).curveFeePct,
|
|
539
|
+
...(await extra(sim.result, minOut)), curveFeePct: (await feesOf(ctx)).curveFeePct,
|
|
479
540
|
note: 'spend includes the 1% curve fee (no tax on the curve; the buy tax applies only in the pool after graduation); at the 1% wallet cap the excess is refunded',
|
|
480
541
|
}, 'buy', await priced(sim.result)))
|
|
481
542
|
}
|
|
@@ -556,7 +617,7 @@ export async function runV3(sub, { opt, flag, out, fail, summarize, resolveLogo,
|
|
|
556
617
|
const r = await ctx.client.waitForTransactionReceipt({ hash, timeout: 120_000 })
|
|
557
618
|
const events = []
|
|
558
619
|
for (const log of r.logs) {
|
|
559
|
-
for (const abi of
|
|
620
|
+
for (const abi of V3_EVENT_ABIS) {
|
|
560
621
|
try {
|
|
561
622
|
const ev = decodeEventLog({ abi, data: log.data, topics: log.topics })
|
|
562
623
|
events.push({ event: ev.eventName, ...Object.fromEntries(Object.entries(ev.args).map(([k, v]) => [k, typeof v === 'bigint' ? v.toString() : v])) })
|