forewit 0.0.0-stage → 0.1.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.
@@ -0,0 +1,175 @@
1
+ // Execute mode: runs the Binance Agentic Wallet CLI (baw) for one commit or reveal, behind an explicit typed yes.
2
+ // Syntax and codes from the binance agentic wallet skill, references/external-sign.md, preflight.md, wallet-view.md.
3
+ // baw is always started without a shell, with an argument array. Gas price and gas limit are never passed.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { readFileSync, existsSync } from 'node:fs';
6
+ import { join, delimiter } from 'node:path';
7
+ import { cleanText } from './question.mjs';
8
+ import { isAddress } from './keccak.mjs';
9
+ import { BAW_CHAIN_IDS, RISK_WARNING } from '../config.mjs';
10
+
11
+ const CHAIN = String(BAW_CHAIN_IDS[0]);
12
+ export const RETRY_CHECKS = [
13
+ `baw wallet tx-history --type pending --binanceChainId ${CHAIN} --json`,
14
+ `baw wallet tx-lock --binanceChainId ${CHAIN} --json`,
15
+ ];
16
+ export const DEV_MODE_HELP =
17
+ 'Developer Mode is off, expired or over its limit. In the Binance App open Agentic Wallet, Settings (top right icon), ' +
18
+ 'turn on Developer Mode, read and confirm the risk warning, and approve the signature request. It lasts 7 days (each use ' +
19
+ 'extends it), has its own daily limit, and the wallet balance must be under its cap. Then run this command again.';
20
+
21
+ /**
22
+ * The one place that decides which program is baw. FOREWIT_BAW_BIN is for tests only (a fake baw script).
23
+ * On Windows npm installs baw as a .cmd shim, which cannot run without a shell, so its JS entry is run with node instead.
24
+ */
25
+ export function bawCommand(env = process.env) {
26
+ const bin = env.FOREWIT_BAW_BIN || 'baw';
27
+ if (/\.m?js$/i.test(bin)) return { file: process.execPath, pre: [bin] };
28
+ if (bin !== 'baw' || process.platform !== 'win32') return { file: bin, pre: [] };
29
+ // npm's default global folder too, for shells whose PATH lacks it
30
+ const dirs = [...(env.PATH ?? env.Path ?? '').split(delimiter), env.APPDATA && join(env.APPDATA, 'npm')].filter(Boolean);
31
+ for (const dir of dirs) {
32
+ if (!existsSync(join(dir, 'baw.cmd'))) continue;
33
+ const pkg = join(dir, 'node_modules', '@binance', 'agentic-wallet');
34
+ try {
35
+ const b = JSON.parse(readFileSync(join(pkg, 'package.json'), 'utf8')).bin;
36
+ const rel = typeof b === 'string' ? b : b?.baw;
37
+ if (rel) return { file: process.execPath, pre: [join(pkg, rel)] };
38
+ } catch { /* keep looking */ }
39
+ }
40
+ throw new Error('baw not found. Install the Binance Agentic Wallet CLI (npm package @binance/agentic-wallet).');
41
+ }
42
+
43
+ /** Runs baw with --json output and returns its parsed reply. Errors arrive as JSON on stdout with exit code 1. */
44
+ export function runBaw(args) {
45
+ const { file, pre } = bawCommand();
46
+ const r = spawnSync(file, [...pre, ...args], { encoding: 'utf8', timeout: 90000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 << 20 });
47
+ if (r.error?.code === 'ENOENT') throw new Error('baw not found. Install the Binance Agentic Wallet CLI (npm package @binance/agentic-wallet).');
48
+ try {
49
+ const j = JSON.parse(r.stdout);
50
+ if (j && typeof j === 'object') return j;
51
+ } catch { /* fall through */ }
52
+ return { success: false, unknown: true, error: { code: null, message: r.error ? r.error.message : 'unreadable baw output' } };
53
+ }
54
+
55
+ const codeOf = (reply) => Number(reply?.error?.code);
56
+ const errText = (reply) => cleanText(String(reply?.error?.message ?? reply?.error?.name ?? 'unknown error'));
57
+
58
+ /** Refusals that need no network and no baw: run them before a salt is made or anything is printed. */
59
+ export function assertCanExecute(net, io) {
60
+ if (!io?.isTTY?.()) throw new Error('--execute needs an interactive terminal so the wallet owner can type yes; stdin is not a TTY. Nothing was sent.');
61
+ if (!BAW_CHAIN_IDS.includes(net.chainId) || !isAddress(net.ledger ?? '')) {
62
+ throw new Error(`--execute needs BSC mainnet (chain ${CHAIN}) with a pinned ledger; baw cannot sign on ${net.name} (chain ${net.chainId}). Run without --execute for the dry run.`);
63
+ }
64
+ }
65
+
66
+ /** Read only checks before any preview. Pending transactions or a locked wallet stop the run: never send twice. */
67
+ export function preflight(now = Date.now()) {
68
+ const status = runBaw(['wallet', 'status', '--json']);
69
+ if (status?.data?.status !== 'CONNECTED') throw new Error('the Agentic Wallet is not signed in (baw wallet status is not CONNECTED). Sign in with: baw auth signin');
70
+ const id = runBaw(['wallet', 'agent-id', '--json']);
71
+ if (codeOf(id) === 20003008) throw new Error('the Agent ID service is temporarily unavailable (20003008). This does not mean you have no Agent ID; try again later.');
72
+ if (id?.data?.claimed !== true) throw new Error('this wallet has no claimed Agent ID (baw wallet agent-id). Claim one in the Binance App, Web3 wallet, Agent ID.');
73
+ const dev = runBaw(['wallet', 'settings', '--json'])?.data?.devMode;
74
+ const exp = dev?.expiresAt;
75
+ const expMs = typeof exp === 'number' ? exp * 1000 : typeof exp === 'string' ? Date.parse(exp) : NaN; // docs say seconds, baw 1.12.0 returns ISO text
76
+ if (dev?.enabled !== true || !(expMs > now) || dev?.balanceExceeded === true) throw new Error(DEV_MODE_HELP);
77
+ if (runBaw(['wallet', 'tx-lock', '--binanceChainId', CHAIN, '--json'])?.data?.status !== 'UNLOCKED') {
78
+ throw new Error('the wallet is locked: a transaction is pending onchain or waiting for approval in the Binance App. Resolve it, then check status before trying again.');
79
+ }
80
+ const pending = runBaw(['wallet', 'tx-history', '--type', 'pending', '--binanceChainId', CHAIN, '--json'])?.data?.transactions;
81
+ if (!Array.isArray(pending)) throw new Error('could not read pending transactions (baw wallet tx-history --type pending); refusing to send.');
82
+ if (pending.length) throw new Error(`the wallet has ${pending.length} pending transaction(s). Wait until they confirm, then run status before sending again. Never resend.`);
83
+ }
84
+
85
+ function explainError(reply, stage) {
86
+ const code = codeOf(reply);
87
+ if (code === 351802 || code === 351804) return `${code}: ${DEV_MODE_HELP}`;
88
+ if (code === 351803) return '351803: risk blocked by the Binance Agentic Wallet. Stopped. Forewit never works around a risk block.';
89
+ if (code === 351805) return `351805: the simulation failed (${errText(reply)}). Common reasons: the commit window closed, the wallet holds no Agent ID, the reveal window is not open, or the receipt does not match. Run status; do not retry blindly.`;
90
+ return `${stage} failed${Number.isFinite(code) ? ` (${code})` : ''}: ${errText(reply)}`;
91
+ }
92
+
93
+ // Field names confirmed on a real BSC mainnet preview (baw 1.12.0, 23 Nov 2026, agent/test/fixtures/baw_preview_contract_call.json):
94
+ // parsedTx is { transactionType: 'ContractInteraction', action: <4 byte selector>, contractAddress, contractAddressList,
95
+ // transactionTypeTranslationKey }. It echoes neither the value nor the full calldata, so value 0 is proven by the
96
+ // simulation showing no balance, allowance or authority change, and the calldata by the selector plus our own argv.
97
+ export function parsedCall(parsedTx) {
98
+ const p = parsedTx ?? {};
99
+ return { type: p.transactionType, to: p.contractAddress, selector: p.action };
100
+ }
101
+
102
+ const isEmptyList = (v) => Array.isArray(v) && v.length === 0;
103
+
104
+ /** Refuses unless the preview targets the pinned ledger, has value 0 and carries exactly our calldata. */
105
+ export function checkPreview(d, { ledger, data }) {
106
+ const got = parsedCall(d?.parsedTx);
107
+ const bad = [];
108
+ if (got.type !== 'ContractInteraction') bad.push(`transaction type ${cleanText(String(got.type))} is not ContractInteraction`);
109
+ if (typeof got.to !== 'string' || got.to.toLowerCase() !== ledger.toLowerCase()) bad.push(`target ${cleanText(String(got.to))} is not the pinned ledger ${ledger}`);
110
+ if (typeof got.selector !== 'string' || got.selector.toLowerCase() !== data.slice(0, 10).toLowerCase()) bad.push('function selector is missing or differs from ours');
111
+ const sim = d?.simulationResult ?? {};
112
+ if (!['balanceChanges', 'allowanceChanges', 'authorityChanges'].every((k) => isEmptyList(sim[k]))) bad.push('the simulation shows a balance, allowance or authority change, so value is not 0');
113
+ if (sim.simulationErrorDetail || (sim.simulationCode != null && !/^0+$/.test(String(sim.simulationCode)))) bad.push(`simulation did not pass (${cleanText(String(sim.simulationCode))})`);
114
+ if (typeof d?.requestId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(d.requestId)) bad.push('no usable requestId');
115
+ const keys = Object.keys(d?.parsedTx ?? {}).map((k) => cleanText(k)).join(', ');
116
+ if (bad.length) throw new Error(`refusing this preview: ${bad.join('; ')} (parsedTx fields: ${keys || 'none'}). Nothing was sent.`);
117
+ }
118
+
119
+ function printPreview(d, data, log) {
120
+ const s = (v) => cleanText(typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v));
121
+ log('', 'Preview from the Binance Agentic Wallet:', ' parsedTx:');
122
+ for (const [k, v] of Object.entries(d.parsedTx ?? {})) log(` ${cleanText(k)}: ${s(v)}`);
123
+ log(` calldata sent (baw echoes only its selector, checked above): ${data}`);
124
+ const sim = d.simulationResult ?? {};
125
+ log(' simulationResult:');
126
+ for (const [k, v] of Object.entries(sim)) log(` ${cleanText(k)}: ${s(v)}`);
127
+ const risks = d.risks ?? {};
128
+ const details = Array.isArray(risks.riskDetails) ? risks.riskDetails : [];
129
+ const flagged = Object.entries(risks.addresses ?? {});
130
+ log(' risks:');
131
+ if (!details.length && !flagged.length) log(' none reported');
132
+ for (const r of details) log(` ${s(r.riskType)}: ${s(r.title)}: ${s(r.description)}`);
133
+ for (const [addr, a] of flagged) for (const r of a?.riskDetails ?? []) log(` address ${s(addr)} flagged (level ${s(a.riskLevel)}): ${s(r.title)}: ${s(r.description)}`);
134
+ if (Array.isArray(risks.riskBehaviors) && risks.riskBehaviors.length) log(` riskBehaviors: ${s(risks.riskBehaviors)}`);
135
+ log(` requireConfirmation: ${s(d.requireConfirmation)}${d.requireConfirmation ? ' (you will also approve it in the Binance App)' : ''}`);
136
+ }
137
+
138
+ /**
139
+ * Preview, show, ask for a typed yes, execute. `io` is { isTTY(): boolean, ask(prompt): Promise<string>, log?(...lines) }.
140
+ * Returns 'BROADCASTED' or 'PENDING_CONFIRMATION'; throws on every refusal, abort or error.
141
+ */
142
+ export async function sendWithConfirmation({ net, from, data, what, io }) {
143
+ const log = io.log ?? ((...l) => console.log(l.join('\n')));
144
+ assertCanExecute(net, io);
145
+ if (!isAddress(from) || !/^0x[0-9a-f]+$/.test(data)) throw new Error('refusing to send unvalidated input');
146
+ preflight();
147
+ const previewArgs = ['contract-call', 'preview', '--binanceChainId', CHAIN, '--from', from, '--to', net.ledger, '--value', '0', '--inputData', data, '--json'];
148
+ const preview = runBaw(previewArgs);
149
+ if (preview?.success !== true) throw new Error(`${explainError(preview, 'preview')} Nothing was sent.`);
150
+ const d = preview.data;
151
+ checkPreview(d, { ledger: net.ledger, data });
152
+ printPreview(d, data, log);
153
+ log('', `Risk warning: ${RISK_WARNING}`, `This sends the ${what} from ${from} to ${net.ledger} with value 0 (network gas only). Forewit pays no returns.`);
154
+ const answer = await io.ask('Type yes to send it, anything else aborts: ');
155
+ if (String(answer ?? '').trim() !== 'yes') throw new Error('aborted: you did not type yes. Nothing was sent.');
156
+ const exp = typeof d.expiresAt === 'string' && !/^d+$/.test(d.expiresAt) ? Date.parse(d.expiresAt) : Number(d.expiresAt); // docs: ms number
157
+ if (Number.isFinite(exp) && Date.now() >= exp) {
158
+ throw new Error('the preview expired before you confirmed. Nothing was sent; run the command again for a fresh preview.');
159
+ }
160
+
161
+ const result = runBaw(['contract-call', 'execute', '--requestId', d.requestId, '--json']);
162
+ const r = result?.data;
163
+ if (result?.success === true && r?.status === 'BROADCASTED' && /^0x[0-9a-fA-F]{64}$/.test(r.txHash ?? '')) {
164
+ log('', `BROADCASTED. txHash: ${r.txHash}`, ` ${net.explorer}/tx/${r.txHash}`);
165
+ return 'BROADCASTED';
166
+ }
167
+ if (result?.success === true && r?.status === 'PENDING_CONFIRMATION') {
168
+ log('', 'PENDING_CONFIRMATION: approve this transaction in the Binance App now.',
169
+ 'Do not run this command again for it: never resend. It completes once you approve it in the App.',
170
+ 'Check it with:', ...RETRY_CHECKS.map((c) => ' ' + c));
171
+ return 'PENDING_CONFIRMATION';
172
+ }
173
+ const why = result?.success === false && !result.unknown ? explainError(result, 'execute') : 'execute returned an unknown or unreadable result, so the transaction state is unknown';
174
+ throw new Error(`${why.replace(/\.$/, '')}. Do not resend. Before any retry check: ${RETRY_CHECKS.join(' and ')}`);
175
+ }
@@ -0,0 +1,120 @@
1
+ // Zero dependency Ethereum keccak256 (original Keccak padding 0x01, not NIST SHA3 0x06),
2
+ // hex helpers, and the minimal ABI encoding and decoding the Forewit CLI needs.
3
+
4
+ const MASK = (1n << 64n) - 1n;
5
+ const RATE = 136; // bytes, for a 256 bit output
6
+
7
+ const RC = [
8
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
9
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
10
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
11
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
12
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
13
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n,
14
+ ];
15
+ // Rotation offsets indexed by lane x + 5y.
16
+ const ROT = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14];
17
+
18
+ const rotl = (v, n) => (n === 0 ? v : ((v << BigInt(n)) | (v >> BigInt(64 - n))) & MASK);
19
+
20
+ function keccakF(s) {
21
+ for (let round = 0; round < 24; round++) {
22
+ const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
23
+ for (let x = 0; x < 5; x++) {
24
+ const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
25
+ for (let y = 0; y < 25; y += 5) s[x + y] ^= d;
26
+ }
27
+ const b = new Array(25);
28
+ for (let x = 0; x < 5; x++) {
29
+ for (let y = 0; y < 5; y++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(s[x + 5 * y], ROT[x + 5 * y]);
30
+ }
31
+ for (let y = 0; y < 25; y += 5) {
32
+ for (let x = 0; x < 5; x++) s[x + y] = b[x + y] ^ (~b[((x + 1) % 5) + y] & MASK & b[((x + 2) % 5) + y]);
33
+ }
34
+ s[0] ^= RC[round];
35
+ }
36
+ }
37
+
38
+ /** keccak256 over a Uint8Array, returns a 32 byte Uint8Array. */
39
+ export function keccak256(data) {
40
+ if (!(data instanceof Uint8Array)) throw new TypeError('keccak256 expects a Uint8Array');
41
+ const padLen = RATE - (data.length % RATE);
42
+ const msg = new Uint8Array(data.length + padLen);
43
+ msg.set(data);
44
+ msg[data.length] ^= 0x01;
45
+ msg[msg.length - 1] ^= 0x80;
46
+ const s = new Array(25).fill(0n);
47
+ for (let off = 0; off < msg.length; off += RATE) {
48
+ for (let i = 0; i < RATE / 8; i++) {
49
+ let lane = 0n;
50
+ for (let j = 7; j >= 0; j--) lane = (lane << 8n) | BigInt(msg[off + i * 8 + j]);
51
+ s[i] ^= lane;
52
+ }
53
+ keccakF(s);
54
+ }
55
+ const out = new Uint8Array(32);
56
+ for (let i = 0; i < 4; i++) {
57
+ for (let j = 0; j < 8; j++) out[i * 8 + j] = Number((s[i] >> BigInt(8 * j)) & 0xffn);
58
+ }
59
+ return out;
60
+ }
61
+
62
+ // Hex helpers
63
+
64
+ export const bytesToHex = (b) => '0x' + Buffer.from(b).toString('hex');
65
+
66
+ export function hexToBytes(hex) {
67
+ if (!/^0x([0-9a-fA-F]{2})*$/.test(hex)) throw new Error(`not even length 0x hex: ${String(hex).slice(0, 80)}`);
68
+ return new Uint8Array(Buffer.from(hex.slice(2), 'hex'));
69
+ }
70
+
71
+ export const utf8 = (s) => new TextEncoder().encode(s);
72
+ export const keccakHex = (bytes) => bytesToHex(keccak256(bytes));
73
+ export const keccakText = (s) => keccakHex(utf8(s));
74
+
75
+ export const isAddress = (a) => typeof a === 'string' && /^0x[0-9a-fA-F]{40}$/.test(a);
76
+ export const isBytes32 = (h) => typeof h === 'string' && /^0x[0-9a-fA-F]{64}$/.test(h);
77
+
78
+ // ABI encoding (static types only: each value is one 32 byte word)
79
+
80
+ const WORD_MAX = (1n << 256n) - 1n;
81
+
82
+ export function wordUint(v) {
83
+ const n = BigInt(v);
84
+ if (n < 0n || n > WORD_MAX) throw new Error(`uint256 out of range: ${v}`);
85
+ return n.toString(16).padStart(64, '0');
86
+ }
87
+
88
+ export function wordAddress(a) {
89
+ if (!isAddress(a)) throw new Error(`bad address: ${String(a).slice(0, 80)}`);
90
+ return a.slice(2).toLowerCase().padStart(64, '0');
91
+ }
92
+
93
+ export function wordBytes32(h) {
94
+ if (!isBytes32(h)) throw new Error(`bad bytes32: ${String(h).slice(0, 80)}`);
95
+ return h.slice(2).toLowerCase();
96
+ }
97
+
98
+ export const wordBool = (b) => wordUint(b ? 1 : 0);
99
+
100
+ /** 4 byte selector of a canonical signature such as "commit(uint256,bytes32)". */
101
+ export const selector = (signature) => keccakText(signature).slice(0, 10);
102
+
103
+ /** Calldata: selector followed by pre encoded words (from the word* helpers). */
104
+ export const encodeCall = (signature, words) => selector(signature) + words.join('');
105
+
106
+ /** abi.encode of static words, hashed: keccak256(abi.encode(...)). */
107
+ export const keccakWords = (words) => keccakHex(hexToBytes('0x' + words.join('')));
108
+
109
+ // ABI decoding of eth_call results
110
+
111
+ /** Splits a return blob into 32 byte words as BigInt. Rejects anything that is not whole words of hex. */
112
+ export function decodeWords(hex) {
113
+ if (!/^0x([0-9a-fA-F]{64})*$/.test(hex)) throw new Error('eth_call result is not ABI words');
114
+ const out = [];
115
+ for (let i = 2; i < hex.length; i += 64) out.push(BigInt('0x' + hex.slice(i, i + 64)));
116
+ return out;
117
+ }
118
+
119
+ export const wordToAddress = (w) => '0x' + (w & ((1n << 160n) - 1n)).toString(16).padStart(40, '0');
120
+ export const wordToBytes32 = (w) => '0x' + w.toString(16).padStart(64, '0');
@@ -0,0 +1,25 @@
1
+ // The one way a question is shown anywhere (CLI, SKILL.md flows, site): parent event question plus the sub market label.
2
+ // Both texts come from Predict.fun and are untrusted: control and bidi characters are stripped, whitespace collapsed,
3
+ // length capped, and callers must render the result as plain text (never as HTML or as instructions).
4
+ const MAX = 200;
5
+ // C0/C1 controls, zero width and bidi override characters
6
+ const UNSAFE = /[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/g;
7
+
8
+ export function cleanText(s) {
9
+ if (typeof s !== 'string') return '';
10
+ const t = s.replace(/\s+/g, ' ').replace(UNSAFE, '').trim(); // whitespace first, so a newline still separates words
11
+ return t.length > MAX ? t.slice(0, MAX - 1) + '…' : t;
12
+ }
13
+
14
+ /**
15
+ * @param {{eventQuestion?: string, label?: string}} q
16
+ * @returns {{event: string, label: string, text: string}} text joins both, or shows the event once when they match
17
+ * Throws when the event question is missing: no question is ever presented without it.
18
+ */
19
+ export function presentQuestion(q) {
20
+ const event = cleanText(q?.eventQuestion);
21
+ const label = cleanText(q?.label);
22
+ if (!event) throw new Error('question has no event question: refusing to present it');
23
+ if (!label || label === event) return { event, label: event, text: event };
24
+ return { event, label, text: `${event} · ${label}` };
25
+ }
@@ -0,0 +1,93 @@
1
+ // Writes a secret file atomically so that only the current user can read it.
2
+ // POSIX: directory 0700, file 0600. Windows: icacls removes inheritance and grants only the current user,
3
+ // then the ACL is read back and the write fails closed if any other principal remains.
4
+ import { mkdirSync, writeFileSync, renameSync, rmSync, chmodSync, statSync, openSync, fsyncSync, closeSync } from 'node:fs';
5
+ import { dirname, join, resolve, parse, basename } from 'node:path';
6
+ import { execFileSync } from 'node:child_process';
7
+ import { randomBytes } from 'node:crypto';
8
+ import { homedir, tmpdir } from 'node:os';
9
+
10
+ const WIN = process.platform === 'win32';
11
+ // Absolute paths so a whoami or icacls earlier on PATH (Git Bash, MSYS) is never used.
12
+ const SYS32 = join(process.env.SystemRoot || 'C:\\Windows', 'System32');
13
+ const run = (exe, args) => execFileSync(join(SYS32, exe), args, { encoding: 'utf8', windowsHide: true });
14
+
15
+ /** DOMAIN\user of the current Windows account. */
16
+ export function windowsUser() {
17
+ const user = run('whoami.exe', []).trim();
18
+ if (!/^[^\s:()]+\\[^:()]+$/.test(user)) throw new Error(`unexpected whoami output: ${user.slice(0, 80)}`);
19
+ return user;
20
+ }
21
+
22
+ /** Principals in the ACL of `target`, parsed from icacls output. */
23
+ export function windowsPrincipals(target) {
24
+ const lines = run('icacls.exe', [target]).split(/\r?\n/);
25
+ if (!lines[0].startsWith(target + ' ')) throw new Error('unexpected icacls output');
26
+ const principals = [];
27
+ for (let i = 0; i < lines.length && lines[i].trim() !== ''; i++) {
28
+ const ace = (i === 0 ? lines[i].slice(target.length) : lines[i]).trim();
29
+ const at = ace.lastIndexOf(':(');
30
+ if (at <= 0) throw new Error(`unparsed icacls entry: ${ace.slice(0, 80)}`);
31
+ principals.push(ace.slice(0, at));
32
+ }
33
+ return principals;
34
+ }
35
+
36
+ function lockWindows(target, isDir, user) {
37
+ run('icacls.exe', [target, '/inheritance:r', '/grant:r', `${user}:${isDir ? '(OI)(CI)F' : 'F'}`]);
38
+ // /inheritance:r drops inherited entries only; explicit ones (often SYSTEM, Administrators) must be removed by name.
39
+ for (const p of windowsPrincipals(target)) {
40
+ if (p.toLowerCase() !== user.toLowerCase()) run('icacls.exe', [target, '/remove', /^S-1-[\d-]+$/.test(p) ? `*${p}` : p]);
41
+ }
42
+ const principals = windowsPrincipals(target);
43
+ // Allow list, case insensitive: anything other than exactly the current user fails closed.
44
+ const others = principals.filter((p) => p.toLowerCase() !== user.toLowerCase());
45
+ if (principals.length === 0 || others.length) throw new Error(`ACL of ${target} still grants: ${others.join(', ') || 'nobody'}`);
46
+ }
47
+
48
+ function lockPosix(target, isDir) {
49
+ chmodSync(target, isDir ? 0o700 : 0o600);
50
+ if ((statSync(target).mode & 0o077) !== 0) throw new Error(`${target} is still accessible to group or others`);
51
+ }
52
+
53
+ function lock(target, isDir, user) {
54
+ if (WIN) lockWindows(target, isDir, user);
55
+ else lockPosix(target, isDir);
56
+ }
57
+
58
+ /** Throws unless `dir` is a dedicated subdirectory: locking home, temp or a drive root would lock out the system. */
59
+ export function assertDedicatedDir(dir) {
60
+ for (const forbidden of [homedir(), tmpdir(), parse(resolve(dir)).root]) {
61
+ if (resolve(dir).toLowerCase() === resolve(forbidden).toLowerCase()) throw new Error(`refusing to lock ${dir}; use a dedicated subdirectory`);
62
+ }
63
+ }
64
+
65
+ /** Atomically writes `text` to `path`, readable only by the current user. Throws (and leaves no file) on failure. */
66
+ export function writeSecretFile(path, text) {
67
+ const file = resolve(path);
68
+ const dir = dirname(file);
69
+ assertDedicatedDir(dir);
70
+ const user = WIN ? windowsUser() : null;
71
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
72
+ lock(dir, true, user); // new files in the directory now inherit owner only access
73
+ const tmp = join(dir, `.${basename(file)}.${randomBytes(6).toString('hex')}.tmp`);
74
+ let renamed = false;
75
+ try {
76
+ const fd = openSync(tmp, 'wx', 0o600);
77
+ try {
78
+ writeFileSync(fd, text, 'utf8');
79
+ fsyncSync(fd);
80
+ } finally {
81
+ closeSync(fd);
82
+ }
83
+ lock(tmp, false, user);
84
+ renameSync(tmp, file);
85
+ renamed = true;
86
+ lock(file, false, user);
87
+ } catch (err) {
88
+ rmSync(tmp, { force: true });
89
+ if (renamed) rmSync(file, { force: true }); // fail closed, but never delete a file this call did not replace
90
+ throw err;
91
+ }
92
+ return file;
93
+ }
@@ -0,0 +1,54 @@
1
+ {
2
+ "en": {
3
+ "title": "Scoring",
4
+ "blocks": [
5
+ {
6
+ "list": [
7
+ "Probabilities are stored in basis points, from 0 to 10000. A Yes outcome is 10000 and a No outcome is 0.",
8
+ "Brier = (p minus outcome) squared. This site divides it by 100,000,000, so 0 is perfect and 1 is the worst possible. Lower is better.",
9
+ "Baseline Brier is the same formula applied to the market price: the order book mid price posted onchain in the last 15 minutes before the commit deadline. A round without a baseline is still scored, with skill 0.",
10
+ "Skill = baseline Brier minus your Brier. Positive skill means you beat the market price on that question.",
11
+ "Void questions (a split payout, a resolution seen before the round was sealed, or a question still unresolved after the reveal deadline plus the round's resolution wait) are skipped for everyone.",
12
+ "A commit that is never revealed is a forfeit: every non void question counts as the worst possible Brier. Revealing is never worse than forfeiting."
13
+ ]
14
+ },
15
+ {
16
+ "h": "Leaderboard rank"
17
+ },
18
+ {
19
+ "list": [
20
+ "Score = sum of skill / (questions with a baseline + 20). The 20 pulls small samples toward zero skill.",
21
+ "To be ranked you need at least 5 scored rounds and 20 questions with a baseline. Sample size and participation rate are shown next to every score.",
22
+ "Rank uses skill against the market, never raw Brier. Raw Brier mostly measures how easy the questions were; skill rewards only information beyond the market price.",
23
+ "Raw Brier and calibration are shown as diagnostics and never used for rank."
24
+ ]
25
+ }
26
+ ]
27
+ },
28
+ "zh": {
29
+ "title": "评分",
30
+ "blocks": [
31
+ {
32
+ "list": [
33
+ "概率以基点存储,范围 0 到 10000。结果为是记为 10000,为否记为 0。",
34
+ "Brier = (p 减去结果) 的平方。本网站将其除以 100,000,000,因此 0 为完美,1 为最差。越低越好。",
35
+ "基准 Brier 对市场价格使用同一公式:提交截止前最后 15 分钟内上链公布的订单簿中间价。没有基准的轮次仍会评分,技能分为 0。",
36
+ "技能分 = 基准 Brier 减去你的 Brier。正值表示你在该问题上优于市场价格。",
37
+ "作废的问题(分割赔付、在轮次封存前已结算,或在揭示截止加上本轮结算等待期后仍未结算)对所有人都跳过。",
38
+ "提交后从未揭示即为弃权:每个未作废的问题都按最差 Brier 计算。揭示永远不会比弃权更差。"
39
+ ]
40
+ },
41
+ {
42
+ "h": "排行榜排名"
43
+ },
44
+ {
45
+ "list": [
46
+ "得分 = 技能分之和 / (有基准的问题数 + 20)。这个 20 会把小样本拉向零技能。",
47
+ "进入排名需要至少 5 个已评分轮次和 20 个有基准的问题。每个分数旁都显示样本量和揭示率。",
48
+ "排名只看相对市场的技能分,从不看原始 Brier。原始 Brier 主要反映问题的难易;技能分只奖励超出市场价格的信息。",
49
+ "原始 Brier 和校准仅作为诊断显示,从不用于排名。"
50
+ ]
51
+ }
52
+ ]
53
+ }
54
+ }