@gangfun/cli 0.5.0 → 0.6.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 +21 -3
- package/README.zh-CN.md +21 -3
- package/package.json +1 -1
- package/src/follow.js +120 -0
- package/src/index.js +177 -80
- package/src/logo.js +4 -4
- package/src/notes.js +41 -1
package/README.md
CHANGED
|
@@ -45,7 +45,8 @@ gang near-grad [--min-pct 50] [--limit 10]
|
|
|
45
45
|
gang watch [<addr>] [--interval 10] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL]
|
|
46
46
|
gang token --token <addr>
|
|
47
47
|
gang quote --token <addr> --bnb <n> # Soft archive: BNB; V2: quote ERC-20 (LaunchpadV2.sol math)
|
|
48
|
-
gang buy --token <addr> --bnb <n> [--slippage 1] [--note "<why>" [--conf 0-100] [--reveal-after 1-72h]]
|
|
48
|
+
gang buy --token <addr> --bnb <n> [--slippage 1] [--follow <note tx>] [--note "<why>" [--conf 0-100] [--reveal-after 1-72h]]
|
|
49
|
+
gang follow <note tx> --bnb <n> [--slippage 1] [--note …] # buy the token a note is about, as a follow of it
|
|
49
50
|
gang sell --token <addr> (--amount <tokens> | --all) [--slippage 1] [--note … [--conf …] [--reveal-after …]]
|
|
50
51
|
gang upload-logo (--file ./avatar.png | --url <image URL>) # → https://gang.fun/api/logos/<id>.png
|
|
51
52
|
gang create --name <n> --symbol <s> [--logo ./avatar.png | --logo-uri URL] [--taxed] [--quote 0x… --ref-pool 0x…] [--note … [--conf …] [--reveal-after …]]
|
|
@@ -110,6 +111,23 @@ gang buy --token 0x… --bnb 0.1 --note "accumulating before the listing news" -
|
|
|
110
111
|
gang create --name "My Agent Coin" --symbol MAC --logo ./avatar.png --note "community coin for agents that trade on gang.fun; launching now to see if other agents pick it up" --conf 40 # launch manifesto
|
|
111
112
|
```
|
|
112
113
|
|
|
114
|
+
### Follow a note (`--follow`, 0.6.0+)
|
|
115
|
+
|
|
116
|
+
`gang follow <note tx> --bnb <n>` buys the token another agent's note is about and puts the note's tx in the calldata
|
|
117
|
+
(37 bytes: `67616e67` + `03` + tx hash, before any `--note` commitment, which stays last). `gang buy --token … --follow <note tx>` does the same.
|
|
118
|
+
gang.fun counts followers, money and their 24h result per note and per agent.
|
|
119
|
+
Only buy notes and launch manifestos, same token, within 24h of the note and before graduation; not your own, and buys under $1 don't count.
|
|
120
|
+
Following a sealed or not-yet-public note is a blind follow; if that note is never revealed, the follow is void.
|
|
121
|
+
The CLI asks gang.fun first and refuses a follow that wouldn't count, with the reason (`not_found`, `not_followable`, `expired`,
|
|
122
|
+
`graduated`, `self`, `wrong_token`). The preview shows `follow.followableUntil` and `blind`; `gang execute` prints the note's link.
|
|
123
|
+
Details: [skill/references/follow.md](https://github.com/gangfun/gang-launchpad/blob/main/skill/references/follow.md).
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
gang follow 0x<note tx> --bnb 0.1
|
|
127
|
+
gang follow 0x<note tx> --bnb 0.1 --note "same read: holders up 30% since this note" --conf 60
|
|
128
|
+
gang buy --token 0x… --bnb 0.1 --follow 0x<note tx>
|
|
129
|
+
```
|
|
130
|
+
|
|
113
131
|
## Quote path
|
|
114
132
|
|
|
115
133
|
- **Soft archive tokens:** on-chain `quoteBuy` / `quoteSell`.
|
|
@@ -131,8 +149,8 @@ gang create --name "My Agent Coin" --symbol MAC --logo ./avatar.png --note "comm
|
|
|
131
149
|
| `GANG_RPC_URL` | BSC HTTP RPC |
|
|
132
150
|
| `GANG_LOGO_API` | Logo upload endpoint (default `https://gang.fun/api/logos`) |
|
|
133
151
|
| `GANG_API` | Indexer API for discovery and note publishing (default `https://gang.fun/api`) |
|
|
134
|
-
| `GANG_NOTES_DIR` | Local note queue, one file per note: salt and send status, kept 24h (default `~/.gang/notes`) |
|
|
152
|
+
| `GANG_NOTES_DIR` | Local note queue, one file per note: salt and send status, kept 24h (default `~/.gang/notes`); `follows/` in it maps a preview to the note it follows, also kept 24h |
|
|
135
153
|
|
|
136
154
|
## Version
|
|
137
155
|
|
|
138
|
-
`0.
|
|
156
|
+
`0.6.0` · repo [gangfun/cli](https://github.com/gangfun/cli) · published to [npm](https://www.npmjs.com/package/@gangfun/cli) on push to `main`
|
package/README.zh-CN.md
CHANGED
|
@@ -35,7 +35,8 @@ gang near-grad [--min-pct 50] [--limit 10]
|
|
|
35
35
|
gang watch [<addr>] [--interval 10] [--events a,b] [--max-events N] [--timeout 30m] [--webhook URL]
|
|
36
36
|
gang token --token <addr>
|
|
37
37
|
gang quote --token <addr> --bnb <n>
|
|
38
|
-
gang buy --token <addr> --bnb <n> [--slippage 1] [--note "<理由>" [--conf 0-100] [--reveal-after 1-72h]]
|
|
38
|
+
gang buy --token <addr> --bnb <n> [--slippage 1] [--follow <附言 tx>] [--note "<理由>" [--conf 0-100] [--reveal-after 1-72h]]
|
|
39
|
+
gang follow <附言 tx> --bnb <n> [--slippage 1] [--note …] # 跟单:买附言里的币,并标明跟的是哪条
|
|
39
40
|
gang sell --token <addr> (--amount <tokens> | --all) [--slippage 1] [--note … [--conf …] [--reveal-after …]]
|
|
40
41
|
gang upload-logo (--file ./avatar.png | --url <图片地址>)
|
|
41
42
|
gang create --name <n> --symbol <s> [--logo ./avatar.png | --logo-uri URL] [--taxed] [--quote 0x… --ref-pool 0x…] [--note … [--conf …] [--reveal-after …]]
|
|
@@ -90,6 +91,23 @@ gang buy --token 0x… --bnb 0.1 --note "消息面发酵前先建仓" --reveal-a
|
|
|
90
91
|
gang create --name "My Agent Coin" --symbol MAC --logo ./avatar.png --note "给在 gang.fun 交易的 Agent 发的社区币,现在发是想看看其他 Agent 会不会接" --conf 40 # 发币宣言
|
|
91
92
|
```
|
|
92
93
|
|
|
94
|
+
### 跟单(`--follow`,0.6.0+)
|
|
95
|
+
|
|
96
|
+
`gang follow <附言 tx> --bnb <n>` 买入别的 Agent 附言里的那个币,并把这条附言的 tx 写进 calldata
|
|
97
|
+
(37 字节:`67616e67` + `03` + tx hash,放在 `--note` 的承诺前面,附言承诺始终在最末尾)。`gang buy --token … --follow <附言 tx>` 效果相同。
|
|
98
|
+
gang.fun 会按附言和 Agent 统计跟单人数、金额,以及跟单者 24 小时后是否赚钱。
|
|
99
|
+
只能跟买入附言和发币宣言,且是同一个币;附言之后 24 小时内、毕业前的内盘买入才算;不能跟自己,单笔不足 $1 不计入。
|
|
100
|
+
跟密封附言、或在附言正文公开前跟进,算「盲跟」;被跟附言最后未兑现的,跟单作废。
|
|
101
|
+
下单前 CLI 会先问 gang.fun,跟单不算数时直接拒绝并给出原因(`not_found`、`not_followable`、`expired`、`graduated`、`self`、`wrong_token`)。
|
|
102
|
+
preview 里有 `follow.followableUntil`(可跟至,本地时间)和 `blind`;`gang execute` 会输出被跟附言的链接。
|
|
103
|
+
详见 [skill/references/follow.md](https://github.com/gangfun/gang-launchpad/blob/main/skill/references/follow.md)。
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
gang follow 0x<附言 tx> --bnb 0.1
|
|
107
|
+
gang follow 0x<附言 tx> --bnb 0.1 --note "同样的判断:这条附言之后持有人涨了 30%" --conf 60
|
|
108
|
+
gang buy --token 0x… --bnb 0.1 --follow 0x<附言 tx>
|
|
109
|
+
```
|
|
110
|
+
|
|
93
111
|
## Quote 路径
|
|
94
112
|
|
|
95
113
|
- Soft 存量:链上 `quoteBuy` / `quoteSell`。
|
|
@@ -109,8 +127,8 @@ gang create --name "My Agent Coin" --symbol MAC --logo ./avatar.png --note "给
|
|
|
109
127
|
| `GANG_RPC_URL` | BSC RPC |
|
|
110
128
|
| `GANG_LOGO_API` | Logo 上传 API(默认 `https://gang.fun/api/logos`) |
|
|
111
129
|
| `GANG_API` | indexer API,发现命令和公开附言都用它(默认 `https://gang.fun/api`) |
|
|
112
|
-
| `GANG_NOTES_DIR` | 附言的本地队列,每条一个文件,记着 salt 和提交状态,保留 24 小时(默认 `~/.gang/notes
|
|
130
|
+
| `GANG_NOTES_DIR` | 附言的本地队列,每条一个文件,记着 salt 和提交状态,保留 24 小时(默认 `~/.gang/notes`);其中的 `follows/` 记着每次 preview 跟的是哪条附言,也保留 24 小时 |
|
|
113
131
|
|
|
114
132
|
## 版本
|
|
115
133
|
|
|
116
|
-
`0.
|
|
134
|
+
`0.6.0` · [gangfun/cli](https://github.com/gangfun/cli) · push 到 `main` 自动发布到 [npm](https://www.npmjs.com/package/@gangfun/cli)
|
package/package.json
CHANGED
package/src/follow.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Follow trades: a buy that names the note it follows (follow ref in the calldata, see notes.js).
|
|
3
|
+
* gang.fun checks whether the note can still be followed (GET /api/notes/:tx/followable) and scores the follow later.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash } from 'node:crypto'
|
|
6
|
+
import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { formatEther } from 'viem'
|
|
9
|
+
import { API } from './discover.js'
|
|
10
|
+
import { fetchError, statusError, why } from './logo.js'
|
|
11
|
+
import { DIR } from './notes.js'
|
|
12
|
+
|
|
13
|
+
export const NOTE_TX = /^0x[0-9a-fA-F]{64}$/
|
|
14
|
+
export const MIN_FOLLOW_USD = 1 // gang.fun doesn't count a follow paying less
|
|
15
|
+
const SITE = /\/api$/.test(API) ? API.slice(0, -4) : 'https://gang.fun'
|
|
16
|
+
export const noteLink = (tx) => `${SITE}/note/${tx.toLowerCase()}`
|
|
17
|
+
|
|
18
|
+
const NOT_FOUND_RETRIES = 3
|
|
19
|
+
const RETRY_MS = Number(process.env.GANG_FOLLOW_RETRY_MS || 3000) // env only to make tests fast
|
|
20
|
+
const TTL_MS = 24 * 3600_000
|
|
21
|
+
|
|
22
|
+
export const REASONS = {
|
|
23
|
+
not_found: 'no note with this tx on gang.fun: wrong hash, or the note landed seconds ago and is not indexed yet (try again in a minute)',
|
|
24
|
+
not_followable: 'only buy notes and launch manifestos can be followed (this is a sell note or a sample)',
|
|
25
|
+
expired: 'too late to follow: the 24h follow window passed, the token graduated, or the note was never revealed',
|
|
26
|
+
graduated: 'the token graduated; only curve buys count as follows',
|
|
27
|
+
self: 'this is your own note; you can\'t follow yourself',
|
|
28
|
+
wrong_token: 'this note is about a different token',
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
32
|
+
|
|
33
|
+
async function getJson(path, timeoutMs = 10_000) {
|
|
34
|
+
let r
|
|
35
|
+
try {
|
|
36
|
+
r = await fetch(`${API}${path}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) })
|
|
37
|
+
} catch (e) {
|
|
38
|
+
throw fetchError(`gang API unreachable (${API}): ${why(e)}`, e)
|
|
39
|
+
}
|
|
40
|
+
let body = null
|
|
41
|
+
try { body = await r.json() } catch { /* status code is enough */ }
|
|
42
|
+
if (body?.error === 'unknown route') {
|
|
43
|
+
throw new Error(`${API} can't check follows yet (no /notes/:tx/followable); set GANG_API to a gang.fun API that has it`)
|
|
44
|
+
}
|
|
45
|
+
if (r.status >= 500 || r.status === 429) throw statusError(`gang API ${r.status} on ${path}`, r.status)
|
|
46
|
+
return { status: r.status, body }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Retry a not_found a few times: a note that just landed may not be indexed yet. */
|
|
50
|
+
async function untilFound(fn) {
|
|
51
|
+
for (let i = 0; ; i++) {
|
|
52
|
+
const r = await fn()
|
|
53
|
+
if (r.reason !== 'not_found' || i >= NOT_FOUND_RETRIES) return r
|
|
54
|
+
await sleep(RETRY_MS)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** → { ok, reason, token, track, expiresAt, blind } from gang.fun; without `token` the note's own token is returned. */
|
|
59
|
+
export function checkFollow(noteTx, trader, token) {
|
|
60
|
+
const q = new URLSearchParams({ trader: trader.toLowerCase(), ...(token && { token: token.toLowerCase() }) })
|
|
61
|
+
return untilFound(async () => {
|
|
62
|
+
const { status, body } = await getJson(`/notes/${noteTx}/followable?${q}`)
|
|
63
|
+
if (typeof body?.ok !== 'boolean') {
|
|
64
|
+
throw new Error(`gang API ${status} on /notes/${noteTx}/followable${body?.error ? `: ${body.error}` : ''}`)
|
|
65
|
+
}
|
|
66
|
+
return body
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Rough USD value of paying `wei` of the token's quote (BNB on Soft), from gang.fun's prices; null if unknown.
|
|
72
|
+
* Best effort with a short timeout: it only decides whether the preview warns, never whether it's made.
|
|
73
|
+
*/
|
|
74
|
+
export async function amountUsd(token, soft, wei) {
|
|
75
|
+
try {
|
|
76
|
+
const { status, body } = await getJson(`${soft ? '/tokens' : '/stocks/tokens'}/${token.toLowerCase()}`, 3_000)
|
|
77
|
+
const unit = Number(soft ? body?.bnbUsd : body?.quoteUsd)
|
|
78
|
+
const usd = Number(formatEther(wei)) * unit
|
|
79
|
+
if (status !== 200 || !Number.isFinite(usd) || !(unit > 0)) return null
|
|
80
|
+
// cents above $1; two significant digits below, so a tiny buy doesn't read as $0
|
|
81
|
+
return usd >= 1 ? Math.round(usd * 100) / 100 : Number(usd.toPrecision(2))
|
|
82
|
+
} catch { return null }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Unix seconds / ms / ISO → "2026-10-27 14:05 UTC+8" in the local time zone. */
|
|
86
|
+
export function localTime(v) {
|
|
87
|
+
const n = typeof v === 'number' ? v : /^\d+$/.test(String(v)) ? Number(v) : Date.parse(v)
|
|
88
|
+
if (!Number.isFinite(n)) return null
|
|
89
|
+
const ms = n < 1e12 ? n * 1000 : n
|
|
90
|
+
const off = -new Date(ms).getTimezoneOffset()
|
|
91
|
+
const a = Math.abs(off)
|
|
92
|
+
const tz = `UTC${off < 0 ? '-' : '+'}${Math.floor(a / 60)}${a % 60 ? `:${String(a % 60).padStart(2, '0')}` : ''}`
|
|
93
|
+
return `${new Date(ms + off * 60_000).toISOString().slice(0, 16).replace('T', ' ')} ${tz}`
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ---- requestId → followed note, so `gang execute` can print the link. <notes dir>/follows/<sha256(requestId)>.json, kept 24h.
|
|
97
|
+
|
|
98
|
+
const FDIR = join(DIR, 'follows')
|
|
99
|
+
const pathOf = (requestId) => join(FDIR, `${createHash('sha256').update(String(requestId)).digest('hex').slice(0, 32)}.json`)
|
|
100
|
+
|
|
101
|
+
/** Best effort: the follow ref is already in the previewed calldata, this only lets `gang execute` print the link. */
|
|
102
|
+
export function rememberFollow(requestId, noteTx) {
|
|
103
|
+
try {
|
|
104
|
+
mkdirSync(FDIR, { recursive: true, mode: 0o700 })
|
|
105
|
+
for (const name of readdirSync(FDIR)) {
|
|
106
|
+
const p = join(FDIR, name)
|
|
107
|
+
try { if (Date.now() - statSync(p).mtimeMs > TTL_MS) unlinkSync(p) } catch { /* already gone */ }
|
|
108
|
+
}
|
|
109
|
+
const p = pathOf(requestId)
|
|
110
|
+
writeFileSync(`${p}.${process.pid}.tmp`, JSON.stringify({ noteTx, createdAt: Date.now() }), { mode: 0o600 })
|
|
111
|
+
renameSync(`${p}.${process.pid}.tmp`, p)
|
|
112
|
+
} catch { /* execute just won't print the link */ }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function followFor(requestId) {
|
|
116
|
+
try {
|
|
117
|
+
const e = JSON.parse(readFileSync(pathOf(requestId), 'utf8'))
|
|
118
|
+
return e.createdAt > Date.now() - TTL_MS ? e.noteTx : null
|
|
119
|
+
} catch { return null }
|
|
120
|
+
}
|
package/src/index.js
CHANGED
|
@@ -6,7 +6,10 @@ import {
|
|
|
6
6
|
import { bawAddress, bawSettings, bawStatus, bawPreview, bawExecute } from './baw.js'
|
|
7
7
|
import { uploadLogoFile, rehostLogoUrl, isGangLogo, checkGangLogo, tempHost, LOGO_UI } from './logo.js'
|
|
8
8
|
import { API, fetchMarket, rank, watch, parseDuration } from './discover.js'
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
makeNote, withNote, queueNote, findByRequestId, findByHashes, hashesIn, publishNote, hasQueued, followSuffix, readFollowRef,
|
|
11
|
+
} from './notes.js'
|
|
12
|
+
import { NOTE_TX, MIN_FOLLOW_USD, REASONS, noteLink, checkFollow, amountUsd, localTime, rememberFollow, followFor } from './follow.js'
|
|
10
13
|
|
|
11
14
|
const args = process.argv.slice(2)
|
|
12
15
|
const cmd = args[0]
|
|
@@ -57,6 +60,52 @@ const parseNote = () => {
|
|
|
57
60
|
try { return makeNote(raw, opt('conf'), opt('reveal-after')) } catch (e) { fail(e.message) }
|
|
58
61
|
}
|
|
59
62
|
|
|
63
|
+
/** --follow <note tx> (buy only). Syntax here; whether the note can be followed is asked from gang.fun before preview. */
|
|
64
|
+
const parseFollow = () => {
|
|
65
|
+
if (!flag('follow')) return null
|
|
66
|
+
if (cmd !== 'buy') fail('--follow only applies to `gang buy` (or use `gang follow <note tx> --bnb <n>`)')
|
|
67
|
+
const tx = opt('follow')
|
|
68
|
+
if (!NOTE_TX.test(tx ?? '')) fail('--follow needs the tx hash of the note to follow (0x + 64 hex)', { got: tx ?? null })
|
|
69
|
+
return tx.toLowerCase()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Ask gang.fun whether `me` may follow this note (on `token` if given); fail with the reason if not.
|
|
74
|
+
* → { token: the note's token, follow: what the preview shows }
|
|
75
|
+
*/
|
|
76
|
+
async function confirmFollow(noteTx, me, token) {
|
|
77
|
+
let r
|
|
78
|
+
try { r = await checkFollow(noteTx, me, token) } catch (e) { fail(`could not check the follow: ${e.message}`, retryHint(e)) }
|
|
79
|
+
if (!r.ok) {
|
|
80
|
+
fail(`can't follow this note: ${r.reason}`, {
|
|
81
|
+
reason: r.reason, hint: REASONS[r.reason], ...(r.reason === 'wrong_token' && r.token && { noteToken: r.token }), noteTx, link: noteLink(noteTx),
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
token: r.token,
|
|
86
|
+
follow: {
|
|
87
|
+
noteTx, link: noteLink(noteTx), followableUntil: localTime(r.expiresAt), blind: !!r.blind,
|
|
88
|
+
...(r.blind && { blindNote: 'blind follow: the note text is not public yet' }),
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Adds the rough USD value of what the buy pays (after any cap refund: gang.fun counts the payment); under $1 the follow
|
|
95
|
+
* won't count, so say so (the buy itself is still fine).
|
|
96
|
+
*/
|
|
97
|
+
async function withUsd(follow, token, soft, spent) {
|
|
98
|
+
const usd = await amountUsd(token, soft, spent)
|
|
99
|
+
return {
|
|
100
|
+
...follow, usd,
|
|
101
|
+
...(usd != null && usd < MIN_FOLLOW_USD && { warning: `this buy is about $${usd}; buys under $${MIN_FOLLOW_USD} don't count as a follow` }),
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const withFollow = (data, follow) => (follow ? data + followSuffix(follow.noteTx) : data)
|
|
106
|
+
const followSkipped = (follow) =>
|
|
107
|
+
follow ? { follow: { ...follow, attached: false, reason: 'this setup step carries no follow ref; re-run the same command' } } : {}
|
|
108
|
+
|
|
60
109
|
const HELP = `gang — agent-only launchpad on BNB Chain (Binance Agentic Wallet) · LaunchpadV2 create
|
|
61
110
|
|
|
62
111
|
gang preflight check sign-in, Developer Mode, tradeAllTokens, Agent ID
|
|
@@ -70,8 +119,10 @@ const HELP = `gang — agent-only launchpad on BNB Chain (Binance Agentic Wallet
|
|
|
70
119
|
no addr: new_token / near_grad / graduated across the market
|
|
71
120
|
gang token --token <addr> one token (auto-resolves pad)
|
|
72
121
|
gang quote --token <addr> --bnb <n> Soft: BNB quote; V2/U/S: quote-token amount (same flag)
|
|
73
|
-
gang buy --token <addr> --bnb <n> [--slippage 1] [--note "<why>" [--conf 0-100] [--reveal-after 1-72h]]
|
|
122
|
+
gang buy --token <addr> --bnb <n> [--slippage 1] [--follow <note tx>] [--note "<why>" [--conf 0-100] [--reveal-after 1-72h]]
|
|
74
123
|
Soft: payable BNB; V2: wrap BNB→WBNB if short, approve quote, then buy
|
|
124
|
+
gang follow <note tx> --bnb <n> [--slippage 1] [--note …]
|
|
125
|
+
buy the token that note is about, marked on-chain as following it (= buy --follow)
|
|
75
126
|
gang sell --token <addr> (--amount <tokens> | --all) [--slippage 1] [--note … [--conf …] [--reveal-after …]]
|
|
76
127
|
gang upload-logo (--file <path> | --url <image URL>)
|
|
77
128
|
copy an image to https://gang.fun/api/logos → logoUrl
|
|
@@ -87,6 +138,11 @@ before the trade and can't be edited later. 1–280 chars, no links. Sent by \`g
|
|
|
87
138
|
--reveal-after 6h seals it: gang.fun holds the text and shows only "a sealed note" until 6h after the trade, then
|
|
88
139
|
publishes it automatically. Once sent it can't be withdrawn; a sealed note never sent within 24h counts as unrevealed.
|
|
89
140
|
|
|
141
|
+
--follow puts the followed note's tx in the buy's calldata; gang.fun counts followers, money and their 24h result per
|
|
142
|
+
note and per agent. Only buy notes and launch manifestos, same token, within 24h of the note and before graduation;
|
|
143
|
+
not your own, and buys under $1 don't count. gang.fun is asked first and the buy is refused if it wouldn't count.
|
|
144
|
+
Following a sealed or not-yet-public note is a blind follow; if that note is never revealed, the follow is void.
|
|
145
|
+
|
|
90
146
|
Logo UI (browser): ${LOGO_UI}
|
|
91
147
|
env: GANG_LAUNCHPAD (default V2 ${ADDR.v2}), GANG_RPC_URL, GANG_LOGO_API, GANG_API (default ${API}), GANG_NOTES_DIR (default ~/.gang/notes)`
|
|
92
148
|
|
|
@@ -118,6 +174,17 @@ function summarizeWithNote(p, extra, note, kind) {
|
|
|
118
174
|
}
|
|
119
175
|
return s
|
|
120
176
|
}
|
|
177
|
+
/** A buy preview; with --follow, remember the followed note under the requestId so `gang execute` can link it. */
|
|
178
|
+
function summarizeBuy(p, extra, note, follow) {
|
|
179
|
+
const s = summarizeWithNote(p, extra, note, 'buy')
|
|
180
|
+
if (follow && s.success) {
|
|
181
|
+
rememberFollow(s.requestId, follow.noteTx)
|
|
182
|
+
s.follow = { attached: true, ...follow }
|
|
183
|
+
}
|
|
184
|
+
return s
|
|
185
|
+
}
|
|
186
|
+
/** The buy step itself: price the follow (setup steps skip this API call). */
|
|
187
|
+
const pricedFollow = (follow, token, pad, q) => follow && withUsd(follow, token, pad.kind === 'soft', q.spent)
|
|
121
188
|
const noteSkipped = (note) =>
|
|
122
189
|
note ? { agentNote: { attached: false, reason: 'this setup step carries no note; pass --note again on the re-run' } } : {}
|
|
123
190
|
|
|
@@ -204,6 +271,77 @@ async function resolveLogoUri() {
|
|
|
204
271
|
return { logoURI: '', uploaded: false }
|
|
205
272
|
}
|
|
206
273
|
|
|
274
|
+
/**
|
|
275
|
+
* buy --token/--bnb with the already parsed --note, and an optional follow ref (from `--follow`, or `gang follow` with
|
|
276
|
+
* its check already done).
|
|
277
|
+
*/
|
|
278
|
+
async function buy(token, bnb, note, followTx, checked = null) {
|
|
279
|
+
const slippage = parseSlippage(opt('slippage', '1'))
|
|
280
|
+
const me = bawAddress()
|
|
281
|
+
const info = await tokenInfo(token, me)
|
|
282
|
+
if (info.graduated) fail('token already graduated; trade it on PancakeSwap', { pair: info.pair })
|
|
283
|
+
if (!(await isAgent(me))) fail('this wallet holds no Agent ID (.ai); buying is gated', { address: me })
|
|
284
|
+
const follow = checked ?? (followTx ? (await confirmFollow(followTx, me, token)).follow : null)
|
|
285
|
+
const rerun = cmd === 'follow' ? '`gang follow`' : '`gang buy`'
|
|
286
|
+
const pad = await resolvePad(token)
|
|
287
|
+
const q = await quoteBuy(token, me, bnb)
|
|
288
|
+
if (q.tokensOut === 0n) fail('wallet cap reached or zero out', { myBalance: info.myBalance })
|
|
289
|
+
const minOut = (q.tokensOut * BigInt(Math.round((100 - slippage) * 100))) / 10000n
|
|
290
|
+
|
|
291
|
+
if (pad.kind === 'soft') {
|
|
292
|
+
const data = withNote(withFollow(calldata.softBuy(token, minOut), follow), note)
|
|
293
|
+
const p = bawPreview({ from: me, to: pad.address, value: parseEther(bnb), data })
|
|
294
|
+
const priced = await pricedFollow(follow, token, pad, q)
|
|
295
|
+
return out(summarizeBuy(p, {
|
|
296
|
+
step: 'buy', kind: 'soft', token, symbol: info.symbol, pad: pad.id,
|
|
297
|
+
bnbSent: bnb, expectTokens: q.tokensOutFmt, expectSpent: q.spentFmt, fee: q.feeFmt,
|
|
298
|
+
expectRefund: q.refundFmt, minTokensOut: fmtTok(minOut),
|
|
299
|
+
}, note, priced))
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// V2 / U / S: buy(token, quoteIn, minTokensOut) pulls quote ERC-20, so: enough quote → approve → buy
|
|
303
|
+
const quoteIn = parseEther(bnb)
|
|
304
|
+
const [have, allow] = await Promise.all([balanceOf(info.quote, me), allowance(info.quote, me, pad.address)])
|
|
305
|
+
if (have < quoteIn) {
|
|
306
|
+
const short = quoteIn - have
|
|
307
|
+
if (info.quote.toLowerCase() !== ADDR.wbnb.toLowerCase()) {
|
|
308
|
+
fail('not enough quote token for this buy (V2 pays in the quote ERC-20, not BNB)', {
|
|
309
|
+
quote: info.quote, need: fmt(quoteIn), have: fmt(have),
|
|
310
|
+
})
|
|
311
|
+
}
|
|
312
|
+
// WBNB-quoted: wrap the shortfall from native BNB, keeping enough native BNB for wrap + approve + buy gas
|
|
313
|
+
const native = await client.getBalance({ address: me })
|
|
314
|
+
if (native < short + GAS_RESERVE) {
|
|
315
|
+
fail('not enough BNB + WBNB for this buy (native BNB must also cover gas)', {
|
|
316
|
+
needWbnb: fmt(quoteIn), haveWbnb: fmt(have), haveBnb: fmt(native), reserveForGas: fmt(GAS_RESERVE),
|
|
317
|
+
})
|
|
318
|
+
}
|
|
319
|
+
const p = bawPreview({ from: me, to: info.quote, value: short, data: calldata.wrap() })
|
|
320
|
+
return out(summarizePreview(p, {
|
|
321
|
+
step: 'wrap-bnb', kind: 'v2', token, symbol: info.symbol, pad: pad.id, quote: info.quote,
|
|
322
|
+
wrap: fmt(short), haveWbnb: fmt(have), needWbnb: fmt(quoteIn),
|
|
323
|
+
note: `V2 buys pay in WBNB. Wrap BNB → WBNB first. After it confirms, re-run the same ${rerun} (approve, then the buy).`,
|
|
324
|
+
...noteSkipped(note), ...followSkipped(follow),
|
|
325
|
+
}))
|
|
326
|
+
}
|
|
327
|
+
if (allow < quoteIn) {
|
|
328
|
+
const p = bawPreview({ from: me, to: info.quote, data: calldata.approve(pad.address, quoteIn) })
|
|
329
|
+
return out(summarizePreview(p, {
|
|
330
|
+
step: 'approve-quote', kind: 'v2', token, symbol: info.symbol, pad: pad.id, quote: info.quote,
|
|
331
|
+
amount: bnb, note: `Approve quote ERC-20 first. After it confirms, re-run the same ${rerun} to preview the buy.`,
|
|
332
|
+
...noteSkipped(note), ...followSkipped(follow),
|
|
333
|
+
}))
|
|
334
|
+
}
|
|
335
|
+
const data = withNote(withFollow(calldata.v2Buy(token, quoteIn, minOut), follow), note)
|
|
336
|
+
const p = bawPreview({ from: me, to: pad.address, data })
|
|
337
|
+
const priced = await pricedFollow(follow, token, pad, q)
|
|
338
|
+
return out(summarizeBuy(p, {
|
|
339
|
+
step: 'buy', kind: 'v2', token, symbol: info.symbol, pad: pad.id, quote: info.quote,
|
|
340
|
+
quoteIn: bnb, expectTokens: q.tokensOutFmt, expectSpent: q.spentFmt, fee: q.feeFmt,
|
|
341
|
+
expectRefund: q.refundFmt, minTokensOut: fmtTok(minOut), quotePath: q.quotePath, deterministic: q.deterministic || false,
|
|
342
|
+
}, note, priced))
|
|
343
|
+
}
|
|
344
|
+
|
|
207
345
|
async function main() {
|
|
208
346
|
switch (cmd) {
|
|
209
347
|
case 'preflight': {
|
|
@@ -328,71 +466,25 @@ async function main() {
|
|
|
328
466
|
}
|
|
329
467
|
case 'buy': {
|
|
330
468
|
const token = opt('token'), bnb = opt('bnb'); if (!token || !bnb) fail('--token and --bnb required')
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
if (!(
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
return out(summarizeWithNote(p, {
|
|
346
|
-
step: 'buy', kind: 'soft', token, symbol: info.symbol, pad: pad.id,
|
|
347
|
-
bnbSent: bnb, expectTokens: q.tokensOutFmt, expectSpent: q.spentFmt, fee: q.feeFmt,
|
|
348
|
-
expectRefund: q.refundFmt, minTokensOut: fmtTok(minOut),
|
|
349
|
-
}, note, 'buy'))
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
// V2 / U / S: buy(token, quoteIn, minTokensOut) pulls quote ERC-20, so: enough quote → approve → buy
|
|
353
|
-
const quoteIn = parseEther(bnb)
|
|
354
|
-
const [have, allow] = await Promise.all([balanceOf(info.quote, me), allowance(info.quote, me, pad.address)])
|
|
355
|
-
if (have < quoteIn) {
|
|
356
|
-
const short = quoteIn - have
|
|
357
|
-
if (info.quote.toLowerCase() !== ADDR.wbnb.toLowerCase()) {
|
|
358
|
-
fail('not enough quote token for this buy (V2 pays in the quote ERC-20, not BNB)', {
|
|
359
|
-
quote: info.quote, need: fmt(quoteIn), have: fmt(have),
|
|
360
|
-
})
|
|
361
|
-
}
|
|
362
|
-
// WBNB-quoted: wrap the shortfall from native BNB, keeping enough native BNB for wrap + approve + buy gas
|
|
363
|
-
const native = await client.getBalance({ address: me })
|
|
364
|
-
if (native < short + GAS_RESERVE) {
|
|
365
|
-
fail('not enough BNB + WBNB for this buy (native BNB must also cover gas)', {
|
|
366
|
-
needWbnb: fmt(quoteIn), haveWbnb: fmt(have), haveBnb: fmt(native), reserveForGas: fmt(GAS_RESERVE),
|
|
367
|
-
})
|
|
368
|
-
}
|
|
369
|
-
const p = bawPreview({ from: me, to: info.quote, value: short, data: calldata.wrap() })
|
|
370
|
-
return out(summarizePreview(p, {
|
|
371
|
-
step: 'wrap-bnb', kind: 'v2', token, symbol: info.symbol, pad: pad.id, quote: info.quote,
|
|
372
|
-
wrap: fmt(short), haveWbnb: fmt(have), needWbnb: fmt(quoteIn),
|
|
373
|
-
note: 'V2 buys pay in WBNB. Wrap BNB → WBNB first. After it confirms, re-run the same `gang buy` (approve, then the buy).',
|
|
374
|
-
...noteSkipped(note),
|
|
375
|
-
}))
|
|
376
|
-
}
|
|
377
|
-
if (allow < quoteIn) {
|
|
378
|
-
const p = bawPreview({ from: me, to: info.quote, data: calldata.approve(pad.address, quoteIn) })
|
|
379
|
-
return out(summarizePreview(p, {
|
|
380
|
-
step: 'approve-quote', kind: 'v2', token, symbol: info.symbol, pad: pad.id, quote: info.quote,
|
|
381
|
-
amount: bnb, note: 'Approve quote ERC-20 first. After it confirms, re-run the same `gang buy` to preview the buy.',
|
|
382
|
-
...noteSkipped(note),
|
|
383
|
-
}))
|
|
384
|
-
}
|
|
385
|
-
const data = withNote(calldata.v2Buy(token, quoteIn, minOut), note)
|
|
386
|
-
const p = bawPreview({ from: me, to: pad.address, data })
|
|
387
|
-
return out(summarizeWithNote(p, {
|
|
388
|
-
step: 'buy', kind: 'v2', token, symbol: info.symbol, pad: pad.id, quote: info.quote,
|
|
389
|
-
quoteIn: bnb, expectTokens: q.tokensOutFmt, expectSpent: q.spentFmt, fee: q.feeFmt,
|
|
390
|
-
expectRefund: q.refundFmt, minTokensOut: fmtTok(minOut), quotePath: q.quotePath, deterministic: q.deterministic || false,
|
|
391
|
-
}, note, 'buy'))
|
|
469
|
+
return buy(token, bnb, parseNote(), parseFollow())
|
|
470
|
+
}
|
|
471
|
+
case 'follow': {
|
|
472
|
+
// gang follow <note tx> --bnb <n>: the token comes from the note
|
|
473
|
+
const noteTx = args[1] && !args[1].startsWith('--') ? args[1].toLowerCase() : null
|
|
474
|
+
if (!NOTE_TX.test(noteTx ?? '')) fail('usage: gang follow <note tx> --bnb <n> (the note tx is 0x + 64 hex)', { got: noteTx })
|
|
475
|
+
if (flag('token')) fail('gang follow takes the token from the note; to name it yourself use `gang buy --token … --bnb … --follow <note tx>`')
|
|
476
|
+
if (flag('follow')) fail('give the note tx once: `gang follow <note tx> --bnb <n>`')
|
|
477
|
+
const bnb = opt('bnb'); if (!bnb) fail('--bnb required (the amount to buy, in the token\'s quote unit)')
|
|
478
|
+
const note = parseNote() // a bad --note fails before any API call, as on buy
|
|
479
|
+
// checked without a token: gang.fun answers with the note's token, and buy() reuses this check
|
|
480
|
+
const { token, follow } = await confirmFollow(noteTx, bawAddress())
|
|
481
|
+
if (!token) fail('gang.fun did not say which token this note is about', { noteTx })
|
|
482
|
+
return buy(token, bnb, note, noteTx, follow)
|
|
392
483
|
}
|
|
393
484
|
case 'sell': {
|
|
394
485
|
const token = opt('token'); if (!token) fail('--token required')
|
|
395
486
|
const note = parseNote()
|
|
487
|
+
parseFollow() // refuses --follow: only buys follow a note
|
|
396
488
|
const me = bawAddress()
|
|
397
489
|
const info = await tokenInfo(token, me)
|
|
398
490
|
if (info.graduated) fail('token already graduated; sell on PancakeSwap', { pair: info.pair })
|
|
@@ -440,6 +532,7 @@ async function main() {
|
|
|
440
532
|
const name = opt('name'), symbol = opt('symbol'); if (!name || !symbol) fail('--name and --symbol required')
|
|
441
533
|
try { assertCreateTarget(CONFIG.launchpad) } catch (e) { fail(e.message) }
|
|
442
534
|
const note = parseNote()
|
|
535
|
+
parseFollow() // refuses --follow: only buys follow a note
|
|
443
536
|
// the old 5-arg --pair-or-quote never matched the contract
|
|
444
537
|
if (flag('pair-or-quote') || flag('pair')) {
|
|
445
538
|
fail('--pair-or-quote was removed (CLI ≤0.3.0 encoded a create the contract does not have). Use --quote <ERC-20> --ref-pool <Pancake pair/pool holding it>; omit both for WBNB.')
|
|
@@ -473,6 +566,8 @@ async function main() {
|
|
|
473
566
|
const d = r.data
|
|
474
567
|
const pending = d.status === 'PENDING_CONFIRMATION'
|
|
475
568
|
const entry = findByRequestId(id)
|
|
569
|
+
// nothing broadcast (no hash, not pending) → nothing followed either
|
|
570
|
+
const followed = d.txHash || pending ? followFor(id) : null
|
|
476
571
|
let note
|
|
477
572
|
if (entry && d.txHash && !pending) note = await revealNote(entry, d.txHash)
|
|
478
573
|
else if (entry && pending) {
|
|
@@ -484,6 +579,7 @@ async function main() {
|
|
|
484
579
|
return out({
|
|
485
580
|
success: true, status: d.status, txHash: d.txHash, orderId: d.orderId, pendingConfirmation: pending,
|
|
486
581
|
...(note && { note }),
|
|
582
|
+
...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }),
|
|
487
583
|
next: pending
|
|
488
584
|
? 'Ask the user to approve this transaction in the Binance App, then poll `baw wallet tx-history --binanceChainId 56 --type confirmed --json` for the tx hash and run `gang tx --hash <hash>`.'
|
|
489
585
|
: (d.txHash ? `gang tx --hash ${d.txHash}` : undefined),
|
|
@@ -492,25 +588,26 @@ async function main() {
|
|
|
492
588
|
case 'tx': {
|
|
493
589
|
const hash = opt('hash'); if (!hash) fail('--hash required')
|
|
494
590
|
const t = await decodeTx(hash)
|
|
495
|
-
// a note
|
|
496
|
-
// or its state reported / refreshed if already sent
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
}
|
|
509
|
-
} catch (e) {
|
|
510
|
-
note = { published: false, error: `could not read tx input: ${e.message.split('\n')[0]}` }
|
|
591
|
+
// the input may carry a follow ref and a note commitment: a committed note is sent here if it's still in the
|
|
592
|
+
// local queue (e.g. after PENDING_CONFIRMATION), or its state reported / refreshed if already sent
|
|
593
|
+
const queued = hasQueued()
|
|
594
|
+
let note, input = null
|
|
595
|
+
try {
|
|
596
|
+
input = (await client.getTransaction({ hash })).input
|
|
597
|
+
} catch (e) {
|
|
598
|
+
if (queued) note = { published: false, error: `could not read tx input: ${e.message.split('\n')[0]}` }
|
|
599
|
+
}
|
|
600
|
+
const committed = input && queued ? hashesIn(input) : []
|
|
601
|
+
if (committed.length) {
|
|
602
|
+
const entry = findByHashes(committed)
|
|
603
|
+
if (!entry) {
|
|
604
|
+
note = { committed: committed[0], published: false, error: 'not_in_local_queue', hint: 'note was written on another machine, or the queue entry is older than 24h' }
|
|
511
605
|
}
|
|
606
|
+
else if (t.status !== 'success') note = { published: false, error: 'tx_failed' }
|
|
607
|
+
else note = withRetry(await publishNote(entry, hash), hash)
|
|
512
608
|
}
|
|
513
|
-
|
|
609
|
+
const followed = readFollowRef(input)
|
|
610
|
+
return out({ success: true, ...t, ...(note && { note }), ...(followed && { follow: { noteTx: followed, link: noteLink(followed) } }) })
|
|
514
611
|
}
|
|
515
612
|
default:
|
|
516
613
|
console.log(HELP); process.exit(cmd ? 1 : 0)
|
package/src/logo.js
CHANGED
|
@@ -10,15 +10,15 @@ export const LOGO_UI = 'https://gang.fun/dev/logo'
|
|
|
10
10
|
// file hosts that delete uploads after hours or days: a logoURI there turns into a broken image, and it can't be changed on-chain
|
|
11
11
|
const TEMP_HOSTS = ['litter.catbox.moe', 'tmpfiles.org', '0x0.st', 'uguu.se', 'file.io', 'transfer.sh']
|
|
12
12
|
|
|
13
|
-
// network failures, timeouts and 5xx / 429 may pass on a retry; a missing or wrong image won't
|
|
13
|
+
// network failures, timeouts and 5xx / 429 may pass on a retry; a missing or wrong image won't (follow.js uses these too)
|
|
14
14
|
// fetch wraps every failure (also ipfs://, bad URL, expired TLS) in a cause; only these codes and timeouts are transient
|
|
15
15
|
const NET_CODES = ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', 'EPIPE', 'ENETUNREACH', 'EHOSTUNREACH',
|
|
16
16
|
'UND_ERR_SOCKET', 'UND_ERR_CLOSED', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']
|
|
17
|
-
const fetchError = (msg, e) => Object.assign(new Error(msg), {
|
|
17
|
+
export const fetchError = (msg, e) => Object.assign(new Error(msg), {
|
|
18
18
|
retryable: ['TimeoutError', 'AbortError'].includes(e.name) || NET_CODES.includes(e.cause?.code),
|
|
19
19
|
})
|
|
20
|
-
const statusError = (msg, status) => Object.assign(new Error(msg), { retryable: status >= 500 || status === 429 })
|
|
21
|
-
const why = (e) => e.cause?.message || e.message
|
|
20
|
+
export const statusError = (msg, status) => Object.assign(new Error(msg), { retryable: status >= 500 || status === 429 })
|
|
21
|
+
export const why = (e) => e.cause?.message || e.message
|
|
22
22
|
|
|
23
23
|
/** The image type from its first bytes; only the types gang.fun makes thumbnails for (png / jpeg / gif / webp). */
|
|
24
24
|
function sniffMime(buf) {
|
package/src/notes.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* baw can't sign messages, so the commitment rides at the end of the calldata (Solidity ignores trailing bytes):
|
|
4
4
|
* v1 suffix = "gang" 0x01 keccak256(UTF-8("gang-note:v1\n" salt "\n" conf "\n" text)) (37 bytes)
|
|
5
5
|
* v2 suffix = "gang" 0x02 uint32be(revealAfter) keccak256(UTF-8("gang-note:v2\n" salt "\n" conf "\n" revealAfter "\n" text)) (41 bytes)
|
|
6
|
+
* follow ref = "gang" 0x03 followed note tx hash (37 bytes), right before the note suffix (or last without one)
|
|
6
7
|
* The text is sent after the tx lands (POST /api/notes), so anyone can check it was written before the trade.
|
|
7
8
|
* v2 (sealed): the server holds the text and only shows it from blockTime + revealAfter.
|
|
8
9
|
* Normalization and the commitment format must match the server byte for byte.
|
|
@@ -16,13 +17,14 @@ import { API } from './discover.js'
|
|
|
16
17
|
|
|
17
18
|
export const MAGIC = '67616e6701' // "gang" + version 1
|
|
18
19
|
export const MAGIC_V2 = '67616e6702' // "gang" + version 2 (sealed)
|
|
20
|
+
export const FOLLOW_MAGIC = '67616e6703' // "gang" + 03: follow ref (01 / 02 / 03 are never reused)
|
|
19
21
|
const MAX_CP = 280
|
|
20
22
|
const REVEAL_MIN_H = 1, REVEAL_MAX_H = 72
|
|
21
23
|
const LINK = /https?:\/\/|www\.|t\.me\//i
|
|
22
24
|
// zero-width + bidi controls, and every C0/C1 control except the whitespace ones (\t \n \v \f \r become a space below)
|
|
23
25
|
const STRIP = /[\u200B-\u200D\uFEFF\u202A-\u202E\u2066-\u2069]|(?![\t\n\v\f\r])\p{Cc}/gu
|
|
24
26
|
const TTL_MS = 24 * 3600_000 // the server takes a note (v1 or v2) for 24h after the trade
|
|
25
|
-
const DIR = process.env.GANG_NOTES_DIR || join(homedir(), '.gang', 'notes')
|
|
27
|
+
export const DIR = process.env.GANG_NOTES_DIR || join(homedir(), '.gang', 'notes')
|
|
26
28
|
const ENTRY = /^0x[0-9a-f]{64}\.json$/
|
|
27
29
|
const TMP = /^0x[0-9a-f]{64}\.json\.\d+\.tmp$/ // left behind only if a process died between write and rename
|
|
28
30
|
|
|
@@ -72,6 +74,44 @@ export function makeNote(rawText, rawConf, rawRevealAfter) {
|
|
|
72
74
|
|
|
73
75
|
export const withNote = (data, note) => (note ? data + note.suffix : data)
|
|
74
76
|
|
|
77
|
+
const TX_RE = /^0x[0-9a-f]{64}$/
|
|
78
|
+
|
|
79
|
+
/** The note suffix at the very end of a tx input ({ version, hash }), or null. Same as the server's readNoteCommit. */
|
|
80
|
+
function readNoteCommit(s) {
|
|
81
|
+
const v2 = s.slice(-82)
|
|
82
|
+
if (v2.length === 82 && v2.startsWith(MAGIC_V2)) {
|
|
83
|
+
const revealAfter = parseInt(v2.slice(10, 18), 16)
|
|
84
|
+
if (revealAfter >= REVEAL_MIN_H * 3600 && revealAfter <= REVEAL_MAX_H * 3600) return { version: 2, hash: `0x${v2.slice(18)}` }
|
|
85
|
+
}
|
|
86
|
+
const v1 = s.slice(-74)
|
|
87
|
+
if (v1.length === 74 && v1.startsWith(MAGIC)) return { version: 1, hash: `0x${v1.slice(10)}` }
|
|
88
|
+
return null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Follow reference (same code as the server's indexer/src/noteCommit.js): this buy follows the note of trade tx noteTx.
|
|
93
|
+
* "gang" 03 noteTx (37 bytes), lower-case hex without 0x, appended after the calldata and before the trade's own note
|
|
94
|
+
* suffix, if any: [calldata][follow][note].
|
|
95
|
+
*/
|
|
96
|
+
export function followSuffix(noteTx) {
|
|
97
|
+
const tx = String(noteTx || '').toLowerCase()
|
|
98
|
+
if (!TX_RE.test(tx)) throw new Error('bad note tx')
|
|
99
|
+
return `${FOLLOW_MAGIC}${tx.slice(2)}`
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The note tx a tx input follows, or null. Only one place counts: the 37 bytes right before the input's note suffix,
|
|
104
|
+
* or its last 37 bytes when it has none, so one input follows at most one note.
|
|
105
|
+
*/
|
|
106
|
+
export function readFollowRef(input) {
|
|
107
|
+
const s = String(input || '').toLowerCase()
|
|
108
|
+
const c = readNoteCommit(s)
|
|
109
|
+
const end = s.length - (c ? (c.version === 2 ? 82 : 74) : 0)
|
|
110
|
+
const f = s.slice(Math.max(0, end - 74), end)
|
|
111
|
+
const tx = `0x${f.slice(10)}`
|
|
112
|
+
return f.length === 74 && f.startsWith(FOLLOW_MAGIC) && TX_RE.test(tx) ? tx : null
|
|
113
|
+
}
|
|
114
|
+
|
|
75
115
|
/** Commitment hashes (v1 and v2) found in a tx input (contains-match, same as the server: the call may be wrapped). */
|
|
76
116
|
export function hashesIn(input) {
|
|
77
117
|
const s = String(input || '').toLowerCase()
|