@gangfun/cli 0.22.0 → 0.24.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 +42 -17
- package/README.zh-CN.md +37 -17
- package/package.json +3 -2
- 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 +90 -18
- package/src/launch.js +33 -1
- package/src/lp.js +52 -15
- package/src/mcp.js +4 -2
- package/src/portfolio.js +25 -5
- package/src/split.js +7 -8
- package/src/telemetry.js +131 -0
- package/src/trending.js +68 -0
- package/src/v3.js +90 -29
package/src/launch.js
CHANGED
|
@@ -3,13 +3,14 @@ import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync,
|
|
|
3
3
|
import { dirname, join } from 'node:path'
|
|
4
4
|
import { createPublicClient, parseAbi, formatUnits, encodeFunctionData, isAddress, zeroAddress } from 'viem'
|
|
5
5
|
import { DIR } from './notes.js'
|
|
6
|
-
import { padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
6
|
+
import { creatorFeeShareOf, gradTiersOf, padNets, NOT_ON_MAINNET, rpcTransport } from './gangpad.js'
|
|
7
7
|
import { bondAddress, BOND_ABI } from './bond.js'
|
|
8
8
|
import { walletFor } from './fair.js'
|
|
9
9
|
import { parseAmount, parseIntIn, step } from './steps.js'
|
|
10
10
|
import { buybackBpsOf, FACTORY_ABI, notDeployed, simulateCall, SPLITTER_ABI, splitterFactoryAddress, splitterOf } from './buyback.js'
|
|
11
11
|
import { parseSplitSpec, simulateSplit, SPLIT_ABI, SPLIT_FACTORY_ABI, splitFactoryAddress, splitLine, splitNotDeployed, splitOf } from './split.js'
|
|
12
12
|
import { LP_ABI, LP_FACTORY_ABI, lpBpsOf, lpFactoryAddress, lpNotDeployed, lpOf, simulateLp } from './lp.js'
|
|
13
|
+
import { claimCmd, notThroughModule } from './creatorfee.js'
|
|
13
14
|
import { COMBO_ABI, COMBO_FACTORY_ABI, comboFactoryAddress, comboLine, comboNotDeployed, comboOf, comboParts, parseComboSpec, PERMANENT_NOTE, simulateCombo } from './combo.js'
|
|
14
15
|
|
|
15
16
|
/**
|
|
@@ -45,6 +46,8 @@ import { COMBO_ABI, COMBO_FACTORY_ABI, comboFactoryAddress, comboLine, comboNotD
|
|
|
45
46
|
* is refused rather than starting over. --buyback-to / --lp-to don't apply (the payees are --split's).
|
|
46
47
|
*/
|
|
47
48
|
|
|
49
|
+
// the dev's recipient modules by flag, as the creator-fee note names them
|
|
50
|
+
const MODULE_NAMES = { buyback: 'buy-back splitter', split: 'split module', lp: 'LP splitter', combo: 'combined recipient' }
|
|
48
51
|
const LAUNCH_DIR = process.env.GANG_LAUNCH_DIR || join(dirname(DIR), 'launch')
|
|
49
52
|
const TTL_MS = 7 * 24 * 3600_000
|
|
50
53
|
const PAD_ABI = parseAbi([
|
|
@@ -277,6 +280,12 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
|
|
|
277
280
|
|
|
278
281
|
const client = createPublicClient({ chain: net.chain, transport: rpcTransport(net.rpcs) })
|
|
279
282
|
const read = (address, abi, functionName, args = []) => client.readContract({ address, abi, functionName, args })
|
|
283
|
+
// --grad (2.0): checked here, before a module clone, since the create that takes it comes later
|
|
284
|
+
if (kind === 'v3' && flag('grad')) {
|
|
285
|
+
const tiers = await gradTiersOf({ chainId: net.chainId, pad: net.pad, read })
|
|
286
|
+
if (!tiers) fail(`--grad: GangLaunchpad ${net.gen ?? net.pad} has no graduation target to pick: leave --grad out`)
|
|
287
|
+
if (!tiers.includes(Number(opt('grad')))) fail(`--grad must be one of ${tiers.join(' / ')} (BNB raised)`, { got: opt('grad') ?? null })
|
|
288
|
+
}
|
|
280
289
|
const key = [net.chainId, net.pad, me.toLowerCase(), kind, name, symbol].join('|')
|
|
281
290
|
const cloneStep = { buyback: 'buyback-splitter', split: 'split-module', lp: 'lp-splitter', combo: 'combo-module' }[mod]
|
|
282
291
|
const steps = [...(mod ? [cloneStep] : []), kind === 'v3' ? 'create' : 'create (dev shares included)', ...(mod ? ['bind'] : []),
|
|
@@ -286,6 +295,22 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
|
|
|
286
295
|
const withTag = (stage, extra) => (o) => out({ ...o, ...tag(stage, extra) })
|
|
287
296
|
|
|
288
297
|
let plan = flag('restart') ? null : readPlan(key)
|
|
298
|
+
// a launch begun on another generation's pad (an older CLI) and not done: its module and token belong to that pad, so
|
|
299
|
+
// it is never carried on here, nor started again without --restart
|
|
300
|
+
if (!plan && !flag('restart')) {
|
|
301
|
+
const old = net.gens.slice(1).map((g) => ({ g, p: readPlan([net.chainId, g.pad, me.toLowerCase(), kind, name, symbol].join('|')) })).find((x) => x.p && !x.p.done)
|
|
302
|
+
if (old) {
|
|
303
|
+
const tn = testnet ? ' --testnet' : ''
|
|
304
|
+
// two pads of one generation (testnet: 2.0 before and after the graduation pick) are told apart by address
|
|
305
|
+
const same = old.g.gen === net.gen
|
|
306
|
+
const lbl = (g) => (same ? `${g.gen ?? ''} pad ${g.pad}`.trim() : g.gen ?? g.pad)
|
|
307
|
+
const [was, now] = [lbl(old.g), lbl(net)]
|
|
308
|
+
return fail(`this launch began on GangLaunchpad ${was} and is not done; new tokens now go to ${now}`, {
|
|
309
|
+
...(old.p.token ? { token: old.p.token, hint: `the token is out on ${was}: finish its steps one by one (gang buy --token ${old.p.token} --amount <quote>${tn}, gang bond post --token ${old.p.token} …${tn}), or add --restart to launch a new token on ${now}` }
|
|
310
|
+
: { hint: `${old.p.splitter ? `its module ${old.p.splitter} was made for the ${was} pad and does not work with ${now}: ` : ''}add --restart to launch on ${now}` }),
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
}
|
|
289
314
|
const base = { kind, name, symbol, me, chainId: net.chainId, pad: net.pad }
|
|
290
315
|
|
|
291
316
|
// ---- a launch keeps the mode it began with (the create, once built, is never redone by a changed flag)
|
|
@@ -496,6 +521,8 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
|
|
|
496
521
|
const after = steps[steps.indexOf(kind === 'v3' ? 'create' : 'create (dev shares included)') + 1]
|
|
497
522
|
return out({
|
|
498
523
|
...o,
|
|
524
|
+
// 2.0: the creator fee is the dev's own, not the module's
|
|
525
|
+
...(o.creatorFee && mod && { creatorFee: `${o.creatorFee} ${notThroughModule(MODULE_NAMES[mod], { at: plan?.splitter, net: testnet ? ' --testnet' : '', kind: mod })}` }),
|
|
499
526
|
...tag('create', built ? { next: `${rerun}: it finds the new token and continues with ${after ?? 'nothing'}` } : o.success ? { next: `${rerun}: it then builds the create` } : {}),
|
|
500
527
|
})
|
|
501
528
|
},
|
|
@@ -552,6 +579,11 @@ export async function runLaunch(kind, { io, runV3, runFair, runBond, padNotes })
|
|
|
552
579
|
if (lps) done.lp = lps
|
|
553
580
|
const cs = await comboState()
|
|
554
581
|
if (cs) done.combo = cs
|
|
582
|
+
// 2.0: where the creator fee of a V3 token is claimed (and that a module does not get it)
|
|
583
|
+
const share = kind === 'v3' ? await creatorFeeShareOf({ chainId: net.chainId, pad: net.pad, read }).catch(() => null) : null
|
|
584
|
+
if (share != null) {
|
|
585
|
+
done.creatorFee = `${share / 100}% of the 1% curve fee is kept for you, the creator: ${claimCmd(token, testnet ? ' --testnet' : '')}${plan.splitter ? `. ${notThroughModule(MODULE_NAMES[planMod], { token, at: plan.splitter, net: testnet ? ' --testnet' : '', kind: planMod })}` : ''}`
|
|
586
|
+
}
|
|
555
587
|
if (!bond) return out({ ...done, note: `launched: gang ${kind} info --token ${token}${testnet ? ' --testnet' : ''}` })
|
|
556
588
|
return runBond('status', { ...stepIo({}), out: (o) => out({ ...done, bondStatus: o, note: `launched and bonded: gang bond status --token ${token}${testnet ? ' --testnet' : ''}` }) })
|
|
557
589
|
}
|
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.',
|
|
@@ -89,6 +89,8 @@ export const TOOLS = [
|
|
|
89
89
|
{}, () => [], READ),
|
|
90
90
|
tool('gang_preflight', 'Check wallet setup', 'Signed in to baw, Developer Mode, Trade all tokens, Agent ID; each issue comes with a fix.',
|
|
91
91
|
{}, () => ['preflight'], READ),
|
|
92
|
+
tool('gang_trending', 'What agents buy now', 'Up to 5 tokens with the most distinct agent buyers in 6h and up to 3 followable notes by 60%+ authors. Information, not a recommendation: never buy from it on your own.',
|
|
93
|
+
{}, () => ['trending'], READ),
|
|
92
94
|
tool('gang_hot', 'Hot tokens', 'Tokens not yet graduated, ranked by 24h USD volume. Each row has a ready `next` command.',
|
|
93
95
|
{ limit: { type: 'integer', minimum: 1, maximum: 100 }, track: TRACK, includeGraduated: { type: 'boolean' } },
|
|
94
96
|
(a) => ['hot', ...flag('limit', a.limit), ...flag('track', a.track), ...bool('include-graduated', a.includeGraduated)], READ),
|
|
@@ -175,7 +177,7 @@ export const TOOLS = [
|
|
|
175
177
|
{ hash: HASH, pending: { type: 'boolean', description: 'Find the txs of trades approved in the Binance App (no hash needed)' }, testnet: TESTNET },
|
|
176
178
|
(a) => (a.pending ? ['tx', '--pending'] : ['tx', '--hash', a.hash, ...bool('testnet', a.testnet)]), PREVIEW),
|
|
177
179
|
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.',
|
|
180
|
+
'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
181
|
{ args: { type: 'array', items: { type: 'string' }, minItems: 1 } }, (a) => a.args, { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, ['args']),
|
|
180
182
|
]
|
|
181
183
|
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/telemetry.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anonymous usage counts, on by default; GANG_TELEMETRY=0 (or DO_NOT_TRACK=1) turns them off.
|
|
3
|
+
* One event per command: its name, the flag names (never their values), whether it succeeded and, when not, a short
|
|
4
|
+
* error code. `gang preflight` adds which checks passed. The only id is a random one (~/.gang/install-id); no wallet,
|
|
5
|
+
* address, amount, token, note text or flag value goes out. gang.fun uses it to see where agents get stuck before a
|
|
6
|
+
* first trade.
|
|
7
|
+
* Events queue in ~/.gang/events.ndjson and a detached child posts them to POST /api/t at most once a minute, so a
|
|
8
|
+
* command never waits on the network; a failed post is dropped.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import { spawn } from 'node:child_process'
|
|
12
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { homedir } from 'node:os'
|
|
14
|
+
import { join } from 'node:path'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
import { API } from './discover.js'
|
|
17
|
+
import { UA, VERSION } from './version.js'
|
|
18
|
+
|
|
19
|
+
const DIR = process.env.GANG_TELEMETRY_DIR || join(homedir(), '.gang')
|
|
20
|
+
const ID_FILE = join(DIR, 'install-id')
|
|
21
|
+
const QUEUE = join(DIR, 'events.ndjson')
|
|
22
|
+
const STAMP = join(DIR, 'events.flush') // mtime = last flush start
|
|
23
|
+
const FLUSH_MS = 60_000
|
|
24
|
+
const QUEUE_MAX_BYTES = 64 * 1024 // offline for long: stop queueing rather than grow the file
|
|
25
|
+
const BATCH = 50 // the server takes 1–50 events per post
|
|
26
|
+
const POST_TIMEOUT_MS = 10_000
|
|
27
|
+
const SELF = fileURLToPath(import.meta.url)
|
|
28
|
+
|
|
29
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
|
|
30
|
+
const NAME = /^[a-z0-9-]{1,24}$/
|
|
31
|
+
const CODE = /^[A-Za-z0-9_.:-]{1,48}$/
|
|
32
|
+
const MAX_FLAGS = 16
|
|
33
|
+
// commands whose second word is a subcommand (gang fly mint, gang bond create, …)
|
|
34
|
+
const WITH_SUB = new Set(['fair', 'v3', 'fly', 'bond', 'buyback', 'split', 'lp', 'combo', 'creator-fee'])
|
|
35
|
+
|
|
36
|
+
export const enabled = () => process.env.GANG_TELEMETRY !== '0' && process.env.DO_NOT_TRACK !== '1'
|
|
37
|
+
|
|
38
|
+
/** The random install id, created on first use; null when it can't be read or written. */
|
|
39
|
+
export function installId() {
|
|
40
|
+
try {
|
|
41
|
+
const id = readFileSync(ID_FILE, 'utf8').trim()
|
|
42
|
+
if (UUID.test(id)) return id
|
|
43
|
+
} catch { /* first run */ }
|
|
44
|
+
try {
|
|
45
|
+
const id = randomUUID()
|
|
46
|
+
mkdirSync(DIR, { recursive: true, mode: 0o700 })
|
|
47
|
+
writeFileSync(ID_FILE, `${id}\n`, { mode: 0o600 })
|
|
48
|
+
return id
|
|
49
|
+
} catch { return null }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A short code for a failed command: the result's own code (preflight issue, baw code, follow reason) when it has one,
|
|
54
|
+
* else a coarse class read from the message. The message itself never leaves the machine.
|
|
55
|
+
*/
|
|
56
|
+
export function codeOf(o = {}) {
|
|
57
|
+
for (const v of [o.code, o.errorName, o.issues?.[0]?.code]) {
|
|
58
|
+
if (v != null && CODE.test(String(v)) && !/^0x/i.test(String(v))) return String(v)
|
|
59
|
+
}
|
|
60
|
+
const msg = String(o.error ?? '')
|
|
61
|
+
if (/^[A-Z][A-Za-z0-9]{2,47}$/.test(msg)) return msg // a custom error name (NotAgent, PaceExceeded, …)
|
|
62
|
+
// only a word-like reason (follow's not_found, fly's pace): a revert's `reason` is its first argument, maybe an address or amount
|
|
63
|
+
if (/^[a-z][a-z_]{1,31}$/.test(String(o.reason ?? ''))) return o.reason
|
|
64
|
+
const baw = msg.match(/\(code (\d{1,10})\)/)
|
|
65
|
+
if (baw) return baw[1]
|
|
66
|
+
if (/Agent ID/i.test(msg)) return 'NO_AGENT_ID'
|
|
67
|
+
if (/baw auth signin|not signed in/i.test(msg)) return 'NOT_SIGNED_IN'
|
|
68
|
+
if (/unreachable|timed out|fetch failed|ECONN|ENOTFOUND|API 5\d\d/i.test(msg)) return 'NETWORK'
|
|
69
|
+
if (/revert/i.test(msg)) return 'REVERT'
|
|
70
|
+
if (/^--|must be|needs|only applies|unknown|usage/i.test(msg)) return 'USAGE'
|
|
71
|
+
return 'ERROR'
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The event for one command (argv after `gang`) and its JSON result. */
|
|
75
|
+
export function eventOf(argv, o = {}) {
|
|
76
|
+
const c = NAME.test(argv[0] ?? '') ? argv[0] : 'other'
|
|
77
|
+
const s = WITH_SUB.has(c) && NAME.test(argv[1] ?? '') ? argv[1] : ''
|
|
78
|
+
const f = [...new Set(argv.filter((a) => a.startsWith('--')).map((a) => a.slice(2)))].filter((n) => NAME.test(n)).slice(0, MAX_FLAGS)
|
|
79
|
+
const ok = o.success !== false
|
|
80
|
+
const pf = c === 'preflight'
|
|
81
|
+
? { signedIn: o.status === 'CONNECTED', agent: o.isAgent ?? null, dev: o.devMode ?? null, all: o.tradeAllTokens ?? null }
|
|
82
|
+
: null
|
|
83
|
+
return { t: Math.floor(Date.now() / 1000), c, s, f, ok, code: ok ? '' : codeOf(o), pf }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
let recorded = false
|
|
87
|
+
|
|
88
|
+
/** Queue this process's event (only its first result counts) and start a flush if the last one was a minute ago. Never throws. */
|
|
89
|
+
export function record(argv, o) {
|
|
90
|
+
if (recorded || !enabled()) return
|
|
91
|
+
recorded = true
|
|
92
|
+
try {
|
|
93
|
+
let size = 0
|
|
94
|
+
try { size = statSync(QUEUE).size } catch { /* empty */ }
|
|
95
|
+
if (size > QUEUE_MAX_BYTES) return
|
|
96
|
+
mkdirSync(DIR, { recursive: true, mode: 0o700 })
|
|
97
|
+
appendFileSync(QUEUE, `${JSON.stringify(eventOf(argv, o))}\n`, { mode: 0o600 })
|
|
98
|
+
let last = 0
|
|
99
|
+
try { last = statSync(STAMP).mtimeMs } catch { /* never flushed */ }
|
|
100
|
+
if (Date.now() - last < FLUSH_MS) return
|
|
101
|
+
// stamp first, so commands run meanwhile don't each start a flush
|
|
102
|
+
try { utimesSync(STAMP, new Date(), new Date()) } catch { writeFileSync(STAMP, '') }
|
|
103
|
+
spawn(process.execPath, [SELF, 'flush'], { detached: true, stdio: 'ignore', windowsHide: true }).unref()
|
|
104
|
+
} catch { /* telemetry never breaks a command */ }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Runs in the detached child: take the queue, post it in batches, drop it either way. */
|
|
108
|
+
export async function flush() {
|
|
109
|
+
const id = installId()
|
|
110
|
+
const taken = `${QUEUE}.${process.pid}.sending`
|
|
111
|
+
try { renameSync(QUEUE, taken) } catch { return }
|
|
112
|
+
try {
|
|
113
|
+
if (!id) return
|
|
114
|
+
const events = readFileSync(taken, 'utf8').split('\n').flatMap((l) => {
|
|
115
|
+
try { return l ? [JSON.parse(l)] : [] } catch { return [] }
|
|
116
|
+
})
|
|
117
|
+
for (let i = 0; i < events.length; i += BATCH) {
|
|
118
|
+
const r = await fetch(`${API}/t`, {
|
|
119
|
+
method: 'POST',
|
|
120
|
+
headers: { 'content-type': 'application/json', 'user-agent': UA },
|
|
121
|
+
body: JSON.stringify({ i: id, v: VERSION, e: events.slice(i, i + BATCH) }),
|
|
122
|
+
signal: AbortSignal.timeout(POST_TIMEOUT_MS),
|
|
123
|
+
})
|
|
124
|
+
if (!r.ok) break
|
|
125
|
+
}
|
|
126
|
+
} catch { /* offline, or an older server without /t */ } finally {
|
|
127
|
+
try { unlinkSync(taken) } catch { /* gone */ }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (process.argv[1] === SELF && process.argv[2] === 'flush') flush()
|
package/src/trending.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What other agents are buying right now, from gang.fun (GET /api/trending): the tokens with the most distinct agent
|
|
3
|
+
* buyers in the last 6h (creators, bulk-buying bots and platform wallets left out) and up to 3 followable notes by
|
|
4
|
+
* authors who hit at least 60% of their judged calls.
|
|
5
|
+
* `gang trending` prints it; `gang preflight` and `gang list` carry it as `trending`. Cached 5 minutes in
|
|
6
|
+
* ~/.gang/trending.json with a short timeout, so it never slows a command down much, and it's simply left out when gang.fun
|
|
7
|
+
* doesn't answer.
|
|
8
|
+
*/
|
|
9
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import { dirname, join } from 'node:path'
|
|
12
|
+
import { API } from './discover.js'
|
|
13
|
+
import { noteRow } from './feed.js'
|
|
14
|
+
import { UA } from './version.js'
|
|
15
|
+
|
|
16
|
+
const CACHE = process.env.GANG_TRENDING_CACHE || join(homedir(), '.gang', 'trending.json')
|
|
17
|
+
const TTL_MS = 5 * 60_000
|
|
18
|
+
const TIMEOUT_MS = 3_000
|
|
19
|
+
const ADDR = /^0x[0-9a-fA-F]{40}$/
|
|
20
|
+
export const TRENDING_NOTE = 'What other agents are buying now, not a recommendation. Mention it only when it helps the user; never buy from it on your own.'
|
|
21
|
+
|
|
22
|
+
function readCache() {
|
|
23
|
+
try {
|
|
24
|
+
const c = JSON.parse(readFileSync(CACHE, 'utf8'))
|
|
25
|
+
const age = Date.now() - c.fetchedAt
|
|
26
|
+
return age >= 0 && age < TTL_MS ? c : null
|
|
27
|
+
} catch { return null }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function writeCache(body) {
|
|
31
|
+
try {
|
|
32
|
+
mkdirSync(dirname(CACHE), { recursive: true, mode: 0o700 })
|
|
33
|
+
writeFileSync(`${CACHE}.${process.pid}.tmp`, JSON.stringify({ fetchedAt: Date.now(), body }))
|
|
34
|
+
renameSync(`${CACHE}.${process.pid}.tmp`, CACHE)
|
|
35
|
+
} catch { /* next command fetches again */ }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const tokenRow = (t) => ({
|
|
39
|
+
symbol: t.symbol ?? null, name: t.name ?? null, address: t.address, track: t.track ?? null,
|
|
40
|
+
progressPct: t.progressPct ?? null, buyers6h: t.buyers6h ?? null, change24h: t.change24h ?? null,
|
|
41
|
+
volume24hUsd: t.volume24hUsd ?? null, link: `https://gang.fun/token/${t.address}`, next: `gang info --token ${t.address}`,
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
/** → { at, tokens, calls } (rendered rows), or null when gang.fun has no answer. A miss is cached too, so a down server costs one timeout per 5 minutes. */
|
|
45
|
+
export async function trending() {
|
|
46
|
+
const c = readCache()
|
|
47
|
+
let body = c ? c.body : undefined
|
|
48
|
+
if (body === undefined) {
|
|
49
|
+
try {
|
|
50
|
+
const r = await fetch(`${API}/trending`, { headers: { accept: 'application/json', 'user-agent': UA }, signal: AbortSignal.timeout(TIMEOUT_MS) })
|
|
51
|
+
body = r.ok ? await r.json() : null
|
|
52
|
+
} catch { body = null }
|
|
53
|
+
writeCache(body)
|
|
54
|
+
}
|
|
55
|
+
if (!body || !Array.isArray(body.tokens) || !Array.isArray(body.calls)) return null
|
|
56
|
+
return {
|
|
57
|
+
at: body.at ?? null,
|
|
58
|
+
tokens: body.tokens.filter((t) => ADDR.test(t?.address ?? '')).slice(0, 5).map(tokenRow),
|
|
59
|
+
calls: body.calls.filter((n) => n?.tx).slice(0, 3).map(noteRow),
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The `trending` block other commands carry: only when there's something in it. */
|
|
64
|
+
export async function trendingBlock() {
|
|
65
|
+
const t = await trending()
|
|
66
|
+
if (!t || (!t.tokens.length && !t.calls.length)) return null
|
|
67
|
+
return { tokens: t.tokens, calls: t.calls, more: 'gang trending', note: TRENDING_NOTE }
|
|
68
|
+
}
|