deviant/scripts/chipnet-vote-escalator-test.mjs
walerikus 599202a721 chore: checkpoint working tree — shell Tier-B retirement + accumulated WIP
Snapshot of accumulated work-in-progress on top of the baseline commit.

This session — retire Tier B from the wallet shell (single-tier model, glossary
"Tiers & trust"):
- SendFlow.tsx: BCH-only; removed the non-functional Tier-B send path, the D-4/D-5
  raw-BCH co-display, and the ADR-0013 friction ladder.
- ArtemisionScreen.tsx: Create wizard collapsed to a single 5-step on-chain genesis
  flow; tier-selection step + Tier-B branch (prepareTierBImport) deleted.
- QuickActions.tsx / SettingsScreen.tsx: receive note reworded; "Send friction
  thresholds" + "Tier explainer" rows removed; registry-trust note reworded.
- Verified: tsc clean, vitest 74/74, full preview walkthrough, no console errors.

Pre-existing uncommitted work also folded in:
- USDm -> FIATm family rename/reorg (Parameters/FIATm/, design records)
- ~130 chipnet + sim-fiatm scripts (catalytic-converter, hyperinflation backtests)
- snapshots 0153-0168; wiki updates (glossary, decisions, index); ADR-0044/0045
- mockups + additional shell screens (Agora, Apps, MainScreen, AssetDetail, ...)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 01:01:37 +02:00

111 lines
7.1 KiB
JavaScript

#!/usr/bin/env node
/**
* chipnet-vote-escalator-test.mjs — anti-plutocracy voting asset (EscalatingVoteNFT).
*
* Each vote carries a FIXED redeemable backing (baseBacking = 100,000 sats), but the
* acquisition PRICE escalates x10 per vote (carried in the identity NFT commitment);
* the premium fee = price - baseBacking is NON-recoverable → treasury. Proves:
* vote 1: price 100,000 fee 0 unit backed 100,000 (refundable)
* vote 2: price 1,000,000 fee 900,000 unit backed 100,000
* vote 3: price 10,000,000 fee 9,900,000 unit backed 100,000
*
* Voter = A, treasury = C. Writes .chipnet-vote-escalator-test.json.
* Run: node --import tsx scripts/chipnet-vote-escalator-test.mjs --yes
*/
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { TestNetWallet } from 'mainnet-js';
import { Contract, ElectrumNetworkProvider, TransactionBuilder, SignatureTemplate } from 'cashscript';
const ROOT = join(import.meta.dirname, '..');
const STATE_FILE = join(ROOT, 'ChipnetTests', '.chipnet-vote-escalator-test.json');
const ARTIFACT_PATH = join(ROOT, 'contracts/dist/EscalatingVoteNFT.json');
const VOTER_KEYS = join(ROOT, '.chipnet-keys.json'); // A
const TREASURY_KEYS = join(ROOT, '.chipnet-keys-c.json'); // C
const BASE = 100_000n, SUPPLY = 10n, POSITION_VALUE = 1000n, VOTES = 3;
const hexToBin = (h) => { const o = new Uint8Array(h.length / 2); for (let i = 0; i < o.length; i++) o[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16); return o; };
const binToHex = (b) => Buffer.from(b).toString('hex');
const txidToConsensusBytes = (h) => { const d = hexToBin(h); const o = new Uint8Array(d.length); for (let i = 0; i < d.length; i++) o[i] = d[d.length - 1 - i]; return o; };
const p2pkh = (pkh) => { const o = new Uint8Array(25); o[0] = 0x76; o[1] = 0xa9; o[2] = 0x14; o.set(pkh, 3); o[23] = 0x88; o[24] = 0xac; return o; };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function scriptNum(n) { if (n === 0n) return new Uint8Array([]); let v = n; const o = []; while (v > 0n) { o.push(Number(v & 0xffn)); v >>= 8n; } if (o[o.length - 1] & 0x80) o.push(0x00); return Uint8Array.from(o); }
const priceHex = (n) => binToHex(scriptNum(n));
function decodeNum(hex) { const b = hexToBin(hex); let p = 0n; for (let k = b.length - 1; k >= 0; k--) p = (p << 8n) | BigInt(b[k] & (k === b.length - 1 ? 0x7f : 0xff)); return p; }
async function ensureEligibleUtxo(w) {
let u = await w.getUtxos(); let e = u.filter((x) => x.vout === 0 && !x.token);
if (e.length) return e[0];
const bad = u.filter((x) => !(x.vout === 0 && !x.token));
const r = await w.send([{ cashaddr: w.cashaddr, value: 5000n, unit: 'sat' }], bad.length ? { utxoIds: bad } : undefined);
console.log(` splitter ${r?.txId ?? r?.txid}`); await sleep(12_000);
u = await w.getUtxos(); e = u.filter((x) => x.vout === 0 && !x.token);
if (!e.length) throw new Error('no eligible vout-0'); return e[0];
}
async function main() {
if (!process.argv.includes('--yes')) { console.log('Re-run with --yes.'); return; }
const artifact = JSON.parse(readFileSync(ARTIFACT_PATH, 'utf8'));
const voter = await TestNetWallet.fromWIF(JSON.parse(readFileSync(VOTER_KEYS, 'utf8')).wif);
const treasury = await TestNetWallet.fromWIF(JSON.parse(readFileSync(TREASURY_KEYS, 'utf8')).wif);
const provider = new ElectrumNetworkProvider('chipnet');
const sig = new SignatureTemplate(voter.privateKey);
const founderLB = p2pkh(treasury.publicKeyHash);
const recipientLB = p2pkh(voter.publicKeyHash);
const ctor = (cat) => [txidToConsensusBytes(cat), founderLB, BASE];
const state = existsSync(STATE_FILE) ? JSON.parse(readFileSync(STATE_FILE, 'utf8')) : { votes: [] };
if (!state.categoryId) {
const utxo = await ensureEligibleUtxo(voter);
const cat = utxo.txid;
const contract = new Contract(artifact, ctor(cat), { provider });
console.log(`contract ${contract.tokenAddress}\ncategory ${cat}`);
const r = await voter.tokenGenesis(
{ cashaddr: contract.tokenAddress, amount: SUPPLY, value: POSITION_VALUE,
nft: { capability: 'mutable', commitment: priceHex(BASE) } }, [], { utxoIds: [utxo] });
console.log(`genesis ${r?.txId ?? r?.txid} (commitment ${priceHex(BASE)} = price ${BASE})`);
state.categoryId = cat; state.contractTokenAddress = contract.tokenAddress;
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2)); await sleep(10_000);
}
const contract = new Contract(artifact, ctor(state.categoryId), { provider });
for (let i = state.votes.length; i < VOTES; i++) {
const ru = await provider.getUtxos(contract.tokenAddress);
const pos = ru.find((u) => u.token?.nft && u.token?.category === state.categoryId && u.token?.amount > 0n);
if (!pos) throw new Error('position not found');
const price = decodeNum(pos.token.nft.commitment);
const fee = price - BASE;
console.log(`\nvote #${i + 1}: price ${price} · backing ${BASE} (redeemable) · fee ${fee} → treasury`);
const cash = (await provider.getUtxos(voter.cashaddr)).filter((u) => !u.token).sort((a, b) => Number(BigInt(b.satoshis) - BigInt(a.satoshis)));
const minerFee = 2000n;
const need = BASE + fee + minerFee + 1000n;
const picked = []; let tot = 0n;
for (const u of cash) { picked.push(u); tot += BigInt(u.satoshis); if (tot >= need) break; }
if (tot < need) throw new Error(`insufficient BCH ${tot} < ${need}`);
const change = BigInt(pos.satoshis) + tot - POSITION_VALUE - BASE - fee - minerFee;
const tb = new TransactionBuilder({ provider });
tb.addInput(pos, contract.unlock.buy(recipientLB));
for (const u of picked) tb.addInput(u, sig.unlockP2PKH());
tb.addOutput({ to: contract.tokenAddress, amount: POSITION_VALUE,
token: { amount: BigInt(pos.token.amount) - 1n, category: state.categoryId, nft: { capability: 'mutable', commitment: priceHex(price * 10n) } } });
tb.addOutput({ to: voter.tokenaddr, amount: BASE, token: { amount: 1n, category: state.categoryId } });
if (fee > 0n) tb.addOutput({ to: treasury.cashaddr, amount: fee });
if (change >= 546n) tb.addOutput({ to: voter.cashaddr, amount: change });
const sent = await tb.send();
const txid = typeof sent === 'string' ? sent : sent?.txid ?? sent?.txId;
console.log(` ✓ vote acquired · treasury +${fee} · unit redeemable for ${BASE} · next price ${price * 10n} · ${txid}`);
state.votes.push({ n: i + 1, price: price.toString(), backing: BASE.toString(), fee: fee.toString(), txid });
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2)); await sleep(10_000);
}
let totFee = 0n, totBack = 0n;
console.log(`\n=== RESULT — anti-plutocracy vote escalator ===`);
for (const v of state.votes) { totFee += BigInt(v.fee); totBack += BigInt(v.backing); console.log(` vote #${v.n}: price ${v.price} · redeemable ${v.backing} · non-recoverable fee ${v.fee}`); }
console.log(` voter holds ${state.votes.length} votes, redeemable for ${totBack} sats total`);
console.log(` treasury (C) received ${totFee} sats non-recoverable (the anti-plutocracy cost)`);
}
main().catch((e) => { console.error('FAILED:', e?.message ?? e); if (e?.stack) console.error(e.stack); process.exit(1); });