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>
113 lines
7.4 KiB
JavaScript
113 lines
7.4 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* chipnet-dual-ladder-test.mjs — proves the DUAL ladder on chipnet:
|
|
* rate x10 (in NFT commitment) AND fee% x10 (derived: baseFeeBps*price/startPrice).
|
|
* Per buy: total = rate (redeemable backing) + fee (non-recoverable -> treasury).
|
|
* Makes the "total spent per step" column on-chain reality.
|
|
*
|
|
* vote 1: rate 100,000 fee% 1% fee 1,000 total 101,000
|
|
* vote 2: rate 1,000,000 fee% 10% fee 100,000 total 1,100,000
|
|
* vote 3: rate 10,000,000 fee% 100% fee 10,000,000 total 20,000,000
|
|
*
|
|
* Voter = A, treasury = C. Writes .chipnet-dual-ladder-test.json.
|
|
* Run: node --import tsx scripts/chipnet-dual-ladder-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-dual-ladder-test.json');
|
|
const ARTIFACT_PATH = join(ROOT, 'contracts/dist/EscalatingDualLadderNFT.json');
|
|
const VOTER_KEYS = join(ROOT, '.chipnet-keys.json'); // A (most BCH)
|
|
const TREASURY_KEYS = join(ROOT, '.chipnet-keys-c.json'); // C
|
|
|
|
const START = 100_000n, BASE_FEE_BPS = 100n, 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; }
|
|
const grp = (s) => BigInt(s).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
|
|
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, START, BASE_FEE_BPS];
|
|
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(START) } }, [], { utxoIds: [utxo] });
|
|
console.log(`genesis ${r?.txId ?? r?.txid} (commitment ${priceHex(START)} = rate ${grp(START)})`);
|
|
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); // rate
|
|
const feeBps = (BASE_FEE_BPS * price) / START; // mirror the covenant
|
|
const fee = (price * feeBps) / 10000n;
|
|
const total = price + fee;
|
|
console.log(`\nvote #${i + 1}: rate ${grp(price)} · fee% ${Number(feeBps) / 100}% · fee ${grp(fee)} · TOTAL ${grp(total)} sats`);
|
|
|
|
const cash = (await provider.getUtxos(voter.cashaddr)).filter((u) => !u.token).sort((a, b) => Number(BigInt(b.satoshis) - BigInt(a.satoshis)));
|
|
const minerFee = 8000n;
|
|
const need = price + 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 ${grp(tot)} < ${grp(need)}`);
|
|
const change = BigInt(pos.satoshis) + tot - POSITION_VALUE - price - 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: price, token: { amount: 1n, category: state.categoryId } });
|
|
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(` ✓ paid TOTAL ${grp(total)} (backing ${grp(price)} redeemable + fee ${grp(fee)} → C) · next rate ${grp(price * 10n)} · ${txid}`);
|
|
state.votes.push({ n: i + 1, rate: price.toString(), feeBps: feeBps.toString(), fee: fee.toString(), total: total.toString(), txid });
|
|
writeFileSync(STATE_FILE, JSON.stringify(state, null, 2)); await sleep(10_000);
|
|
}
|
|
|
|
let tFee = 0n, tBack = 0n, tTotal = 0n;
|
|
console.log(`\n=== RESULT — dual ladder (rate x10 + fee% x10) ===`);
|
|
for (const v of state.votes) { tFee += BigInt(v.fee); tBack += BigInt(v.rate); tTotal += BigInt(v.total); console.log(` #${v.n}: rate ${grp(v.rate)} · fee% ${Number(v.feeBps) / 100}% · fee ${grp(v.fee)} · total ${grp(v.total)}`); }
|
|
console.log(` cumulative TOTAL spent: ${grp(tTotal)} sats (redeemable backing ${grp(tBack)} + non-recoverable fee ${grp(tFee)} → treasury C)`);
|
|
}
|
|
|
|
main().catch((e) => { console.error('FAILED:', e?.message ?? e); if (e?.stack) console.error(e.stack); process.exit(1); });
|