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>
153 lines
13 KiB
JavaScript
153 lines
13 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* chipnet-tote2-k4-test.mjs — multi-outcome (K=4) Tier-2 tote on chipnet
|
|
* (ADR-0024, K>2 approach #1: fixed small K, inline totals).
|
|
* Contract: contracts/ParimutuelToteOpenK4.cash (BCH, single state-NFT pool UTXO).
|
|
*
|
|
* 4 outcomes. Bettors (sats): A=10000 + B=30000 on outcome 0 (two winners);
|
|
* C=20000 on outcome 1; D=15000 on outcome 2; outcome 3 empty. Oracle attests
|
|
* outcome 0 -> pool 75000 splits among outcome-0 bettors pro-rata:
|
|
* A = floor(10000*75000/40000) = 18750; B last drains the remainder (56250 + seed).
|
|
* Losers C (outcome 1) and D (outcome 2) cannot claim (covenant winner-gate).
|
|
*
|
|
* Roles: founder/fees = C. Resumable state JSON.
|
|
*/
|
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { randomBytes } from 'node:crypto';
|
|
import { TestNetWallet } from 'mainnet-js';
|
|
import { Contract, ElectrumNetworkProvider, TransactionBuilder, SignatureTemplate } from 'cashscript';
|
|
import { secp256k1, sha256 } from '@bitauth/libauth';
|
|
|
|
const ROOT = join(import.meta.dirname, '..');
|
|
const STATE = join(ROOT, 'ChipnetTests', '.chipnet-tote2-k4-test.json');
|
|
const ART = join(ROOT, 'contracts/dist/ParimutuelToteOpenK4.json');
|
|
const KEYS = { a: join(ROOT, '.chipnet-keys.json'), b: join(ROOT, '.chipnet-keys-b.json'), c: join(ROOT, '.chipnet-keys-c.json'), d: join(ROOT, '.chipnet-keys-d.json') };
|
|
const SEED = 1000n, DUST = 1000n, MF = 6000n;
|
|
|
|
function 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;}
|
|
function binToHex(b){return Array.from(b,(x)=>x.toString(16).padStart(2,'0')).join('');}
|
|
function txidLE(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;}
|
|
function 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;}
|
|
function u64le(n){let v=BigInt(n);const o=new Uint8Array(8);for(let i=0;i<8;i++){o[i]=Number(v&0xffn);v>>=8n;}return binToHex(o);}
|
|
function u64leToBig(hex){let v=0n;for(let i=0;i<8;i++){v|=BigInt(parseInt(hex.slice(i*2,i*2+2),16))<<BigInt(8*i);}return v;}
|
|
function betCommit(t0,t1,t2,t3){return '00'+u64le(t0)+u64le(t1)+u64le(t2)+u64le(t3);} // 33 bytes
|
|
function claimCommit(oc,pool,win,rws){return '01'+oc+u64le(pool)+u64le(win)+u64le(rws);} // 26 bytes
|
|
function receiptCommit(claimed,oc,stake){return claimed+oc+u64le(stake);} // 10 bytes
|
|
const sleep=(ms)=>new Promise(r=>setTimeout(r,ms));
|
|
function divider(c='='){console.log(c.repeat(80));}
|
|
function step(t){console.log('');divider();console.log(t);divider();}
|
|
function load(){return existsSync(STATE)?JSON.parse(readFileSync(STATE,'utf8')):{};}
|
|
function save(s){writeFileSync(STATE,JSON.stringify(s,(k,v)=>typeof v==='bigint'?v.toString():v,2));}
|
|
function pickBch(u,need){const p=[];let t=0n;for(const x of u){p.push(x);t+=BigInt(x.satoshis);if(t>=need)break;}return{p,t};}
|
|
function txidOf(s){return typeof s==='string'?s:s?.txid??s?.txId;}
|
|
function oracleSign(privHex,evBin,outByte){const m=new Uint8Array([...evBin,outByte]);const sig=secp256k1.signMessageHashDER(hexToBin(privHex),sha256.hash(m));if(typeof sig==='string')throw new Error('sign '+sig);return{message:m,sig};}
|
|
|
|
async function main(){
|
|
const art=JSON.parse(readFileSync(ART,'utf8'));
|
|
const A=await TestNetWallet.fromWIF(JSON.parse(readFileSync(KEYS.a,'utf8')).wif);
|
|
const B=await TestNetWallet.fromWIF(JSON.parse(readFileSync(KEYS.b,'utf8')).wif);
|
|
const C=await TestNetWallet.fromWIF(JSON.parse(readFileSync(KEYS.c,'utf8')).wif);
|
|
const D=await TestNetWallet.fromWIF(JSON.parse(readFileSync(KEYS.d,'utf8')).wif);
|
|
const provider=new ElectrumNetworkProvider('chipnet');
|
|
const sig={a:new SignatureTemplate(A.privateKey),b:new SignatureTemplate(B.privateKey),c:new SignatureTemplate(C.privateKey),d:new SignatureTemplate(D.privateKey)};
|
|
let st=load();
|
|
if(!st.oracle){let p;do{p=randomBytes(32);}while(typeof secp256k1.derivePublicKeyCompressed(p)==='string');st.oracle={priv:binToHex(p),pub:binToHex(secp256k1.derivePublicKeyCompressed(p))};save(st);}
|
|
const oraclePub=hexToBin(st.oracle.pub);
|
|
const PHASE0=betCommit(0,0,0,0);
|
|
console.log(`Oracle ${st.oracle.pub}`);
|
|
|
|
async function eligible(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:2000n,unit:'sat'}],bad.length?{utxoIds:bad}:undefined);console.log(` splitter ${txidOf(r)}`);await sleep(12000);u=await w.getUtxos();e=u.filter(x=>x.vout===0&&!x.token);if(!e.length)throw new Error('splitter failed');return e[0];}
|
|
async function cBch(need){const u=(await provider.getUtxos(C.cashaddr)).filter(x=>!x.token).sort((a,b)=>Number(b.satoshis)-Number(a.satoshis));return pickBch(u,need);}
|
|
async function bchOf(w){return (await provider.getUtxos(w.cashaddr)).filter(x=>!x.token).sort((a,b)=>Number(b.satoshis)-Number(a.satoshis));}
|
|
|
|
step('Genesis tote NFT (K=4 state) + deploy covenant');
|
|
if(!st.cat){const u=await eligible(C);st.cat=u.txid;const r=await C.tokenGenesis({cashaddr:C.tokenaddr,amount:0n,value:SEED,nft:{capability:'minting',commitment:PHASE0}},[],{utxoIds:[u]});console.log(` genesis ${txidOf(r)} — ${u.txid}`);const tip=await provider.getBlockHeight();st.betDL=tip;st.sweepDL=tip+500000;st.event=binToHex(randomBytes(16));save(st);await sleep(10000);}
|
|
const cat=st.cat;
|
|
const tote=new Contract(art,[txidLE(cat),oraclePub,hexToBin(st.event),BigInt(st.betDL),BigInt(st.sweepDL),C.publicKeyHash],{provider});
|
|
console.log(` contract ${tote.tokenAddress}`);
|
|
async function pool(){return (await provider.getUtxos(tote.tokenAddress)).find(x=>x.token?.category===cat&&x.token?.nft?.capability==='minting');}
|
|
|
|
if(!st.relocate){const g=(await provider.getUtxos(C.cashaddr)).find(x=>x.token?.category===cat&&x.token?.nft?.capability==='minting');const {p,t}=await cBch(MF+SEED);const tb=new TransactionBuilder({provider});tb.addInput(g,sig.c.unlockP2PKH());for(const x of p)tb.addInput(x,sig.c.unlockP2PKH());tb.addOutput({to:tote.tokenAddress,amount:SEED,token:{amount:0n,category:cat,nft:{capability:'minting',commitment:PHASE0}}});tb.addOutput({to:C.cashaddr,amount:BigInt(g.satoshis)+t-SEED-MF});st.relocate=txidOf(await tb.send());save(st);console.log(` pool seeded — ${st.relocate}`);await sleep(10000);}
|
|
|
|
// bets: [key, wallet, sig, outcomeHex, stakeSats]
|
|
const bets=[['a',A,sig.a,'00',10000n],['b',B,sig.b,'00',30000n],['c',C,sig.c,'01',20000n],['d',D,sig.d,'02',15000n]];
|
|
step('BET — A,B→outcome0; C→outcome1; D→outcome2');
|
|
st.bets=st.bets||{};st.t=st.t||{0:'0',1:'0',2:'0',3:'0'};
|
|
for(const [k,w,s,oc,stake] of bets){
|
|
if(st.bets[k]){console.log(` ${k} bet`);continue;}
|
|
const u=await pool();const idx=parseInt(oc,16);const t=[BigInt(st.t[0]),BigInt(st.t[1]),BigInt(st.t[2]),BigInt(st.t[3])];t[idx]+=stake;
|
|
const newCommit=betCommit(t[0],t[1],t[2],t[3]);
|
|
const bch=await bchOf(w);const {p,tt}=(()=>{const r=pickBch(bch,stake+DUST+MF+1000n);return{p:r.p,tt:r.t};})();
|
|
if(tt<stake+DUST+MF+1000n)throw new Error(`${k}: low BCH`);
|
|
const tb=new TransactionBuilder({provider});
|
|
tb.addInput(u,tote.unlock.bet(stake,hexToBin(oc)));
|
|
for(const x of p)tb.addInput(x,s.unlockP2PKH());
|
|
tb.addOutput({to:tote.tokenAddress,amount:BigInt(u.satoshis)+stake,token:{amount:0n,category:cat,nft:{capability:'minting',commitment:newCommit}}});
|
|
tb.addOutput({to:w.tokenaddr,amount:DUST,token:{amount:0n,category:cat,nft:{capability:'mutable',commitment:receiptCommit('00',oc,stake)}}});
|
|
tb.addOutput({to:w.cashaddr,amount:tt-stake-DUST-MF});
|
|
console.log(` ${k} bets ${stake} on outcome ${oc} — ${txidOf(await tb.send())}`);
|
|
st.bets[k]=true;st.t={0:t[0].toString(),1:t[1].toString(),2:t[2].toString(),3:t[3].toString()};save(st);await sleep(10000);
|
|
}
|
|
const totalPool=BigInt(st.t[0])+BigInt(st.t[1])+BigInt(st.t[2])+BigInt(st.t[3]);
|
|
const winTotal=BigInt(st.t[0]); // attest outcome 0
|
|
|
|
step(`ATTEST outcome 0 — totalPool=${totalPool}, winTotal(o0)=${winTotal}`);
|
|
if(!st.attest){
|
|
const u=await pool();const {message,sig:oSig}=oracleSign(st.oracle.priv,hexToBin(st.event),0x00);
|
|
const newCommit=claimCommit('00',totalPool,winTotal,winTotal);
|
|
const {p,t}=await cBch(MF+1000n);const tb=new TransactionBuilder({provider});tb.setLocktime(Number(st.betDL));
|
|
tb.addInput(u,tote.unlock.attest(oSig,message));for(const x of p)tb.addInput(x,sig.c.unlockP2PKH());
|
|
tb.addOutput({to:tote.tokenAddress,amount:BigInt(u.satoshis),token:{amount:0n,category:cat,nft:{capability:'minting',commitment:newCommit}}});
|
|
tb.addOutput({to:C.cashaddr,amount:t-MF});
|
|
st.attest=txidOf(await tb.send());save(st);console.log(` attested — ${st.attest}`);await sleep(10000);
|
|
} else console.log(` (attest ${st.attest})`);
|
|
|
|
async function findReceipt(w,oc,stake){const rc=receiptCommit('00',oc,stake);return (await provider.getUtxos(w.cashaddr)).find(x=>x.token?.category===cat&&x.token?.nft?.capability==='mutable'&&x.token?.nft?.commitment===rc);}
|
|
const isReject=(e)=>/ParimutuelToteOpenK4\.cash|Require statement failed|mandatory-script|Verify/i.test((e?.message??e).toString());
|
|
async function notLast(w,s,oc,stake){
|
|
const u=await pool();const rcpt=await findReceipt(w,oc,stake);if(!rcpt)throw new Error('claim: receipt missing');
|
|
const rwsNow=u64leToBig(u.token.nft.commitment.slice(36,52));const payout=stake*totalPool/winTotal;const newCommit=claimCommit('00',totalPool,winTotal,rwsNow-stake);
|
|
const {p,t}=await cBch(MF+1000n);const tb=new TransactionBuilder({provider});
|
|
tb.addInput(u,tote.unlock.claim(p2pkh(w.publicKeyHash)));tb.addInput(rcpt,s.unlockP2PKH());for(const x of p)tb.addInput(x,sig.c.unlockP2PKH());
|
|
tb.addOutput({to:tote.tokenAddress,amount:BigInt(u.satoshis)-payout,token:{amount:0n,category:cat,nft:{capability:'minting',commitment:newCommit}}});
|
|
tb.addOutput({to:w.cashaddr,amount:payout});
|
|
tb.addOutput({to:w.tokenaddr,amount:DUST,token:{amount:0n,category:cat,nft:{capability:'mutable',commitment:receiptCommit('01',oc,stake)}}});
|
|
tb.addOutput({to:C.cashaddr,amount:BigInt(rcpt.satoshis)+t-payout-DUST-MF});
|
|
return {txid:txidOf(await tb.send()),payout};
|
|
}
|
|
async function last(w,s,oc,stake){
|
|
const u=await pool();const rcpt=await findReceipt(w,oc,stake);if(!rcpt)throw new Error('last: receipt missing');
|
|
const {p,t}=await cBch(MF+1000n);const tb=new TransactionBuilder({provider,allowImplicitFungibleTokenBurn:true});
|
|
tb.addInput(u,tote.unlock.claim(p2pkh(w.publicKeyHash)));tb.addInput(rcpt,s.unlockP2PKH());for(const x of p)tb.addInput(x,sig.c.unlockP2PKH());
|
|
tb.addOutput({to:w.cashaddr,amount:BigInt(u.satoshis)});
|
|
tb.addOutput({to:w.tokenaddr,amount:DUST,token:{amount:0n,category:cat,nft:{capability:'mutable',commitment:receiptCommit('01',oc,stake)}}});
|
|
tb.addOutput({to:C.cashaddr,amount:BigInt(rcpt.satoshis)+t-DUST-MF});
|
|
return {txid:txidOf(await tb.send()),drained:BigInt(u.satoshis)};
|
|
}
|
|
|
|
step('NEG — loser C (outcome 1) claims -> covenant must REJECT on-chain');
|
|
if(!st.loser){let r=false;try{await notLast(C,sig.c,'01',20000n);}catch(e){if(isReject(e)){r=true;console.log(` rejected: ${(e?.message??e).toString().slice(0,100)}`);}else throw e;}if(!r)throw new Error('SECURITY: losing outcome accepted');st.loser=true;save(st);} else console.log(' (loser ok)');
|
|
|
|
step('CLAIM A (outcome0) — floor 10000*75000/40000 = 18750');
|
|
if(!st.claimA){const r=await notLast(A,sig.a,'00',10000n);st.claimA=r.txid;st.payA=r.payout.toString();save(st);console.log(` A=${r.payout} — ${r.txid}`);await sleep(10000);} else console.log(` (A ${st.claimA})`);
|
|
step('CLAIM B (last, outcome0) — drains pool');
|
|
if(!st.claimB){const r=await last(B,sig.b,'00',30000n);st.claimB=r.txid;st.drainedB=r.drained.toString();save(st);console.log(` B drained ${r.drained} — ${r.txid}`);await sleep(10000);} else console.log(` (B ${st.claimB})`);
|
|
|
|
step('VERIFY');
|
|
const checks=[
|
|
[`A pro-rata ${st.payA} (=18750)`, st.payA==='18750'],
|
|
['losing outcome rejected on-chain', !!st.loser],
|
|
[`B last-claim drained ${st.drainedB}`, !!st.claimB],
|
|
['pool consumed (state NFT burned)', !(await pool())],
|
|
];
|
|
let ok=true;for(const [l,p] of checks){console.log(` [${p?'PASS':'FAIL'}] ${l}`);ok=ok&&p;}
|
|
step('SUMMARY — multi-outcome (K=4) tote, approach #1 inline totals');
|
|
console.log(` category ${cat}\n attest ${st.attest}\n claimA/claimB ${st.claimA} / ${st.claimB}`);
|
|
console.log(' 4-outcome covenant: per-outcome inline totals in the bet phase, collapsed');
|
|
console.log(' to {winner,totalPool,winTotal} at attest; winning-outcome bettors split pro-rata.');
|
|
divider();
|
|
if(!ok){console.error('VERIFY FAILED');process.exit(1);}
|
|
process.exit(0);
|
|
}
|
|
main().catch((e)=>{console.error('FAILED:',e?.message??e);if(e?.stack)console.error(e.stack);process.exit(1);});
|