deviant/scripts/chipnet-superexp-dra-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

114 lines
7.2 KiB
JavaScript

#!/usr/bin/env node
/**
* chipnet-superexp-dra-test.mjs — SUPER-EXPONENTIAL DRA proof (DeviantSuperExpDRA).
*
* Escalation law: rate -> (rate * 314/100)^3 = (rate * 3.14)^3, per unit.
* Proves the covenant COMPUTES the cube-of-(rate*3.14) on-chain (integer pi +
* cube via repeated multiply, no pow). One claim at the start rate (1000 sats,
* cheap) forces the commitment to (1000*3.14)^3 = 30,959,144,000. A 2nd unit
* would cost ~310 BCH (beyond any test wallet) — the wall IS the proof.
* Verifies the on-chain commitment equals the off-chain formula.
* Buyer = B. Writes .chipnet-superexp-dra-test.json.
* Run: node --import tsx scripts/chipnet-superexp-dra-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-superexp-dra-test.json');
const ARTIFACT_PATH = join(ROOT, 'contracts/dist/DeviantSuperExpDRA.json');
const KEYS = join(ROOT, '.chipnet-keys-b.json');
const START_RATE = 1000n, MUL_NUM = 314n, MUL_DEN = 100n, SUPPLY = 20n, POSITION_VALUE = 1000n;
const nextRate = (r) => { const a = r * MUL_NUM / MUL_DEN; return a * a * a; };
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 rateHex = (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 w = await TestNetWallet.fromWIF(JSON.parse(readFileSync(KEYS, 'utf8')).wif);
const provider = new ElectrumNetworkProvider('chipnet');
const sig = new SignatureTemplate(w.privateKey);
const recipientLB = p2pkh(w.publicKeyHash);
const ctor = (cat) => [txidToConsensusBytes(cat), MUL_NUM, MUL_DEN];
const state = existsSync(STATE_FILE) ? JSON.parse(readFileSync(STATE_FILE, 'utf8')) : {};
const save = () => writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
if (!state.categoryId) {
const utxo = await ensureEligibleUtxo(w);
const cat = utxo.txid;
const contract = new Contract(artifact, ctor(cat), { provider });
console.log(`contract ${contract.tokenAddress}\ncategory ${cat} (law: (rate*${MUL_NUM}/${MUL_DEN})^3 = (rate*3.14)^3)`);
const r = await w.tokenGenesis(
{ cashaddr: contract.tokenAddress, amount: SUPPLY, value: POSITION_VALUE,
nft: { capability: 'mutable', commitment: rateHex(START_RATE) } }, [], { utxoIds: [utxo] });
console.log(`genesis ${r?.txId ?? r?.txid} (start rate ${START_RATE})`);
state.categoryId = cat; state.contractTokenAddress = contract.tokenAddress; save(); await sleep(10_000);
}
const contract = new Contract(artifact, ctor(state.categoryId), { provider });
if (!state.claim) {
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('reservoir not found');
const rate = decodeNum(pos.token.nft.commitment);
const expected = nextRate(rate);
console.log(`\nclaim: pay current rate ${rate} sats → commitment must become (${rate}*3.14)^3 = ${expected}`);
const cash = (await provider.getUtxos(w.cashaddr)).filter((u) => !u.token).sort((a, b) => Number(BigInt(b.satoshis) - BigInt(a.satoshis)));
const minerFee = 2000n;
const picked = []; let tot = 0n;
for (const u of cash) { picked.push(u); tot += BigInt(u.satoshis); if (tot >= rate + minerFee + 1000n) break; }
if (tot < rate + minerFee + 1000n) throw new Error(`insufficient ${tot}`);
const change = BigInt(pos.satoshis) + tot - POSITION_VALUE - rate - minerFee;
const tb = new TransactionBuilder({ provider });
tb.addInput(pos, contract.unlock.claim(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: rateHex(expected) } } });
tb.addOutput({ to: w.tokenaddr, amount: rate, token: { amount: 1n, category: state.categoryId } });
if (change >= 546n) tb.addOutput({ to: w.cashaddr, amount: change });
const sent = await tb.send();
const txid = typeof sent === 'string' ? sent : sent?.txid ?? sent?.txId;
console.log(` ✓ claimed 1 unit @ ${rate} · commitment → ${expected} · ${txid}`);
state.claim = { rate: rate.toString(), expectedNext: expected.toString(), txid }; save(); await sleep(9_000);
}
// verify the on-chain commitment equals the off-chain formula
const ru = await provider.getUtxos(contract.tokenAddress);
const pos = ru.find((u) => u.token?.nft && u.token?.category === state.categoryId);
const onchain = pos ? decodeNum(pos.token.nft.commitment) : null;
const expected = BigInt(state.claim.expectedNext);
state.verified = onchain !== null && onchain === expected;
state.onchainCommitment = onchain?.toString() ?? null; save();
console.log(`\n=== RESULT — super-exponential DRA (rate*3.14)^3 ===`);
console.log(` claim @ ${state.claim.rate} sats (${state.claim.txid})`);
console.log(` on-chain commitment: ${onchain}`);
console.log(` off-chain formula : ${expected}`);
console.log(` MATCH: ${state.verified ? '✓ covenant computed (rate*3.14)^3 correctly' : '✗ MISMATCH'}`);
console.log(` next unit would cost ${(Number(expected) / 1e8).toFixed(2)} BCH — the wall (a 2nd unit is unbuyable).`);
}
main().catch((e) => { console.error('FAILED:', e?.message ?? e); if (e?.stack) console.error(e.stack); process.exit(1); });