const test = require('node:test'); const assert = require('node:assert/strict'); const M = require('./model.js'); const A = require('./adapters.js'); const now = '2026-10-20T12:00:00.000Z'; const actors = Object.fromEntries(M.ROLES.map(role => [role, {id:'demo-'+role,role,partyId:role==='holder'?'ORG-001':role==='buyer'?'DEMO-BUYER-AE':null}])); const buyer = {id:'DEMO-BUYER-AE',country:'AE',qualified:true,verified:true,suspended:false,gatewayApproved:true,validUntil:'2026-11-20T00:00:00.000Z'}; let serial = 0; function rig() { let s = M.seed(now); const run = (action,role,input={},ctx={}) => { const r=s.requests.find(r=>r.id===input.id)||s.requests[0]; const payload={commandId:'TEST-'+(++serial),expectedRevision:s.revision,expectedVersion:r?.version,...(action==='create'?{}:{id:r?.id}),...input}; s=M.dispatch(s,action,payload,typeof role==='string'?actors[role]:role,{now,buyer,...ctx});return s; }; return {run,get:()=>s,create(input={}){return run('create','holder',{positionId:'RS-AE-01',quantity:'250',price:'105',days:7,agent:false,thirdParty:'',acknowledged:true,...input});}}; } const checks={ownership:true,transfer:true,issuer:true,jurisdiction:true,unencumbered:true,gateway:true,documents:true,sourceRevision:1,reference:'OWNERSHIP-CHECK'}; function listed() {const r=rig();r.create();r.run('submit','holder');r.run('verify','compliance',checks);r.run('publish','holder');return r;} function agreed() {const r=listed();r.run('propose','buyer',{price:'105'});r.run('accept','holder',{proposalVersion:1,acknowledged:true});r.run('instructions','rails',begin);r.run('sign','holder',{proposalVersion:1,acknowledged:true,reference:'SELLER-AGREEMENT'});r.run('sign','buyer',{proposalVersion:1,acknowledged:true,reference:'BUYER-AGREEMENT'});return r;} const begin={reference:'SETTLEMENT-CASE',destination:'BUYER-EXTERNAL-ACCOUNT',beneficiary:'SELLER-BANK-ACCOUNT',controlRef:'ACCOUNT-REVIEW',gatewayRef:'PROVIDER-CASE'}; function settling(){const r=agreed();r.run('begin','rails',begin);return r;} const cash={reference:'PAYMENT-REF',amount:'26250',beneficiary:begin.beneficiary,currency:'USD'}; const delivery={reference:'TOKEN-TRANSFER-REF',quantity:'250',network:'DEMO-EVM',tokenRef:'DEMO-TOKEN-RS-AE-01',sourceAccount:'DEMO-EXTERNAL-ACCOUNT-ORG-001',destination:begin.destination}; const code=(fn,expected)=>assert.throws(fn,e=>e.code===expected); test('seed validates and has no automatic claims or requests',()=>{const s=M.seed(now);assert(M.valid(s));assert.equal(s.requests.length,0);assert.equal(s.events.length,0);}); test('decimal arithmetic supports 18 decimals without float drift',()=>{assert.equal(M.decimal('0.000000000000000001',18),'1');assert.equal(M.displayUnits('1000000000000000000',18),'1');assert.equal(M.displayUnits('1000000000',6),'1000');}); test('currency precision, exponent and negative input fail closed',()=>{code(()=>M.cents('1.234'),'precision');for(const x of ['1e8','-1','NaN','1,000',' 1','Infinity'])code(()=>M.cents(x),'invalidNumber');}); test('fee is 1%, optional additional agent 1%, unknown costs stay unknown',()=>{const e=M.economics(M.decimal('250',6),6,10500,true);assert.equal(e.principal,2625000);assert.equal(e.glemo,26250);assert.equal(e.agent,26250);assert.equal(e.thirdPartyCents,null);assert.equal(e.taxCents,null);assert.equal(e.netBeforeUnknownCostsAndTax,2572500);}); test('fractional quantities round final principal to cents',()=>{assert.equal(M.economics('1',6,500001,false).principal,1);code(()=>M.economics('1',6,1,false),'invalidNumber');}); test('zero and excess quantity rejected without modifying state',()=>{for(const quantity of ['0','1001']){const r=rig();const before=r.get();code(()=>r.create({quantity}),'quantityError');assert.deepEqual(r.get(),before);}}); test('wrong account cannot sell another holder position',()=>{const s=M.seed(now);code(()=>M.dispatch(s,'create',{commandId:'x',expectedRevision:0,positionId:'RS-AE-01',quantity:'1',price:'100',days:7,agent:false,acknowledged:true},{...actors.holder,partyId:'OTHER'},{now}),'forbidden');}); test('lock and nontransferable positions are blocked',()=>{const r=rig();code(()=>r.create({positionId:'RS-AE-02'}),'locked');code(()=>r.create({positionId:'RS-AE-03'}),'notTransferable');}); test('draft does not reserve; submission reserves; competing submission fails',()=>{const r=rig();r.create({quantity:'800'});const first=r.get().requests[0].id;r.create({quantity:'800'});const second=r.get().requests[0].id;assert.equal(M.reserved(r.get(),'RS-AE-01'),0n);r.run('submit','holder',{id:first,expectedVersion:1});assert.equal(M.available(r.get(),r.get().positions[0]),M.decimal('200',6));code(()=>r.run('submit','holder',{id:second,expectedVersion:1}),'quantityError');}); test('pending request cannot bypass review to list',()=>{const r=rig();r.create();r.run('submit','holder');code(()=>r.run('publish','holder'),'transition');}); test('all transfer and issuer checks required',()=>{const r=rig();r.create();r.run('submit','holder');code(()=>r.run('verify','compliance',{...checks,issuer:false}),'checklistRequired');code(()=>r.run('verify','holder',checks),'forbidden');}); test('approval requires source revision and expires',()=>{const r=rig();r.create();r.run('submit','holder');code(()=>r.run('verify','compliance',{...checks,sourceRevision:2}),'staleProof');r.run('verify','compliance',checks);code(()=>r.run('publish','holder',{}, {now:'2026-10-21T13:00:00Z'}),'staleProof');}); test('buyer cannot self-trade, bypass KYC, class or jurisdiction',()=>{for(const bad of [{id:'ORG-001'},{verified:false},{qualified:false},{country:'BR'},{gatewayApproved:false},{suspended:true},{validUntil:'2026-10-01T00:00:00Z'}]){const r=listed();code(()=>r.run('propose','buyer',{price:'105'},{buyer:{...buyer,...bad}}),'buyerIneligible');}}); test('counteroffer increments version and clears previous consent',()=>{const r=listed();r.run('propose','buyer',{price:'102'});r.run('propose','holder',{price:'104'});assert.equal(r.get().requests[0].proposal.version,2);assert.equal(r.get().requests[0].proposal.accepted.buyer,false);code(()=>r.run('accept','buyer',{proposalVersion:1,acknowledged:true}),'quoteExpired');r.run('accept','buyer',{proposalVersion:2,acknowledged:true});assert.equal(r.get().requests[0].status,'agreement');}); test('negotiation cannot be silently replaced by a different buyer',()=>{const r=listed();r.run('propose','buyer',{price:'105'});code(()=>r.run('propose',{...actors.buyer,partyId:'OTHER'},{price:'104'},{buyer:{...buyer,id:'OTHER'}}),'buyerIneligible');}); test('expired proposal needs a fresh proposal and fresh review',()=>{const r=listed();r.run('propose','buyer',{price:'105'});r.run('verify','compliance',checks,{now:'2026-10-21T13:00:00Z'});code(()=>r.run('accept','holder',{proposalVersion:1,acknowledged:true},{now:'2026-10-21T13:01:00Z'}),'quoteExpired');}); test('no external settlement before both agreement acceptances',()=>{const r=listed();r.run('propose','buyer',{price:'105'});r.run('accept','holder',{proposalVersion:1,acknowledged:true});code(()=>r.run('begin','rails',begin),'signaturesRequired');}); test('settlement rechecks buyer and fresh ownership',()=>{const r=agreed();code(()=>r.run('begin','rails',begin,{buyer:{...buyer,suspended:true}}),'buyerIneligible');code(()=>r.run('begin','rails',begin,{now:'2026-10-22T00:00:00Z'}),'staleProof');}); test('cash mismatch has no ledger mutation',()=>{const r=settling();const s=r.get();for(const x of [{amount:'1'},{currency:'EUR'},{beneficiary:'WRONG'}])code(()=>r.run('cash','rails',{...cash,...x}),'cashMismatch');assert.deepEqual(r.get(),s);}); test('token, account, network, quantity and destination all must match',()=>{const r=settling();for(const x of [{quantity:'249'},{network:'WRONG'},{tokenRef:'OTHER'},{sourceAccount:'OTHER'},{destination:'OTHER'}])code(()=>r.run('delivery','rails',{...delivery,...x}),'deliveryMismatch');}); test('reconciliation requires two separate proof references',()=>{const r=settling();r.run('cash','rails',cash);code(()=>r.run('delivery','rails',{...delivery,reference:cash.reference}),'proofReused');code(()=>r.run('reconcile','auditor',{reference:'AUDIT'}),'bothLegsRequired');}); test('reconciliation is maker-checker and once only',()=>{const r=settling();r.run('cash','rails',cash);r.run('delivery','rails',delivery);code(()=>r.run('reconcile',{...actors.auditor,id:actors.rails.id},{reference:'AUDIT'}),'independence');r.run('reconcile','auditor',{reference:'AUDIT'});code(()=>r.run('reconcile','auditor',{reference:'AUDIT-2'}),'transition');}); test('partial sale updates remaining units, cost and realized result; issuer stays unchanged',()=>{const r=settling();r.run('cash','rails',cash);r.run('delivery','rails',delivery);r.run('reconcile','auditor',{reference:'AUDIT'});const s=r.get(),p=s.positions[0],q=s.requests[0],next=s.positions.find(p=>p.ownerId===buyer.id);assert.equal(p.quantity,M.decimal('750',6));assert.equal(p.costCents,7500000);assert.equal(q.receipt.allocatedCostCents,2500000);assert.equal(q.receipt.realizedBeforeUnknownCostsAndTax,98750);assert.equal(next.quantity,M.decimal('250',6));assert.equal(next.costCents,2625000);assert.equal(next.issuer,p.issuer);assert.equal(M.reserved(s,p.id),0n);assert(M.valid(s));}); test('cancellation releases only pre-agreement reservation',()=>{const r=listed();r.run('cancel','holder',{reason:'No buyer'});assert.equal(M.reserved(r.get(),'RS-AE-01'),0n);const q=settling();code(()=>q.run('cancel','holder',{reason:'Change of mind'}),'transition');}); test('expiry is explicit and cannot release in-flight settlement',()=>{const r=listed();code(()=>r.run('expire','admin'),'notExpired');r.run('expire','admin',{}, {now:'2026-10-28T00:00:00Z'});assert.equal(M.reserved(r.get(),'RS-AE-01'),0n);const q=settling();code(()=>q.run('expire','admin',{}, {now:'2026-11-01T00:00:00Z'}),'transition');}); test('exceptions block progress and require independent resolution',()=>{const r=settling();r.run('issue','compliance',{reason:'Payment discrepancy'});code(()=>r.run('cash','rails',cash),'issueOpen');code(()=>r.run('resolve','compliance',{reason:'Checked',reference:'RES'}),'independence');r.run('resolve','auditor',{reason:'External check completed',reference:'RES'});r.run('cash','rails',cash);assert(r.get().requests[0].cash);}); test('idempotent replay does not duplicate records; altered reuse fails',()=>{const s=M.seed(now),x={commandId:'ONCE',expectedRevision:0,positionId:'RS-AE-01',quantity:'1',price:'100',days:7,agent:false,acknowledged:true};const next=M.dispatch(s,'create',x,actors.holder,{now});assert.deepEqual(M.dispatch(next,'create',x,actors.holder,{now}),next);code(()=>M.dispatch(next,'create',{...x,quantity:'2'},actors.holder,{now}),'conflict');}); test('stale global revisions and request versions are rejected',()=>{const r=rig();r.create();code(()=>r.run('submit','holder',{expectedRevision:0}),'conflict');code(()=>r.run('submit','holder',{expectedVersion:0}),'conflict');}); test('corrupt storage stays intact and cannot silently seed over it',async()=>{let raw='{bad';const storage={getItem:()=>raw,setItem:v=>{raw=v;}};const store=M.createStore(storage);assert.equal(store.health(),'corrupt');await assert.rejects(()=>store.command('create',{},actors.holder),e=>e.code==='corrupt');assert.equal(raw,'{bad');}); test('stale tab fails without overwriting another tab',async()=>{let raw=null;const storage={getItem:()=>raw,setItem:(k,v)=>{raw=v;}};const a=M.createStore(storage,{now:()=>now}),b=M.createStore(storage,{now:()=>now});const x={commandId:'TAB-A',expectedRevision:0,positionId:'RS-AE-01',quantity:'1',price:'100',days:7,agent:false,acknowledged:true};await a.command('create',x,actors.holder,{now});const saved=raw;await assert.rejects(()=>b.command('create',{...x,commandId:'TAB-B'},actors.holder,{now}),e=>e.code==='conflict');assert.equal(raw,saved);assert.equal(b.get().revision,1);}); test('quota failure does not update the in-memory state',async()=>{const storage={getItem:()=>null,setItem:()=>{throw Error('Quota');}};const s=M.createStore(storage,{now:()=>now});const x={commandId:'QUOTA',expectedRevision:0,positionId:'RS-AE-01',quantity:'1',price:'100',days:7,agent:false,acknowledged:true};await assert.rejects(()=>s.command('create',x,actors.holder,{now}),e=>e.code==='storage');assert.equal(s.get().revision,0);}); test('platform adapter never imports unconfirmed or primary incomplete positions',()=>{assert.deepEqual(A.platform([{id:'T',marketAccess:{buyerId:'ORG-001'},workflow:{stage:'settlement_pending'}}],[],'ORG-001'),[]);}); test('newly reconciled external purchase imports as a historical position, not an ownership proof',()=>{const pos=A.platform([{id:'T-1',asset:'Example',marketAccess:{buyerId:'ORG-001',offerId:'A'},workflow:{stage:'reconciled'},externalExecution:{stage:'reconciled',reconciliation:{at:now},receipt:{},terms:{quantityUnits:'5000000',principalCents:10000},destination:{address:'EXT'},mirror:{decimals:6,network:'EVM',tokenRef:'TOKEN'}}}],[{id:'A',issuer:'ISSUER',issuanceCountry:'AE'}],'ORG-001')[0];const s=M.seed(now),x={positionId:pos.id,commandId:'IMPORT',expectedRevision:0};const next=M.dispatch(s,'importPosition',x,actors.holder,{now,position:pos});assert(M.valid(next));assert.equal(next.positions.at(-1).originalDeal,'T-1');assert.equal(next.requests.length,0);}); test('an eligible unrelated buyer cannot substitute for the agreed buyer at settlement',()=>{const r=agreed();code(()=>r.run('begin','rails',begin,{buyer:{...buyer,id:'OTHER-APPROVED-BUYER'}}),'buyerIneligible');}); test('instructions are bound into signatures; changes require renewed consent',()=>{const r=agreed();code(()=>r.run('begin','rails',{...begin,destination:'THIRD-PARTY'}),'instructionsChanged');r.run('instructions','rails',{...begin,destination:'NEW-ACCOUNT'});assert.equal(r.get().requests[0].signatures.holder,null);assert.equal(r.get().requests[0].signatures.buyer,null);code(()=>r.run('begin','rails',{reference:'BEGIN'}),'signaturesRequired');}); test('normalized evidence cannot be reused using surrounding whitespace',()=>{const r=settling();r.run('cash','rails',cash);code(()=>r.run('delivery','rails',{...delivery,reference:' '+cash.reference+' '}),'proofReused');}); test('inconsistent persisted legs and deleted audit fail validation',()=>{const r=settling();r.run('cash','rails',cash);r.run('delivery','rails',delivery);for(const edit of [s=>{s.requests[0].cash.amountCents=1;},s=>{s.requests[0].delivery.destination='WRONG';},s=>{s.events=[];s.revision=0;}]){const s=JSON.parse(JSON.stringify(r.get()));edit(s);assert.equal(M.valid(s),false);}}); test('expired signed agreement can close with mutual release and no movement evidence',()=>{const r=agreed();const later={now:'2026-10-28T00:00:00Z'};code(()=>r.run('begin','rails',begin,later),'expiredError');code(()=>r.run('closeAgreement','compliance',{reason:'Expiry',reference:'CLOSE'},later),'closureRequired');r.run('closeAgreement','compliance',{reason:'Mutual termination; no external movement',reference:'CLOSE',noMovement:true,holderReleaseRef:'SELLER-RELEASE',buyerReleaseRef:'BUYER-RELEASE',providerClosureRef:'PROVIDER-NO-MOVEMENT'},later);assert.equal(M.reserved(r.get(),'RS-AE-01'),0n);assert.equal(r.get().requests[0].status,'cancelled');}); test('unassigned buyer with null account cannot freeze a listing',()=>{const r=listed();code(()=>r.run('issue',{...actors.buyer,partyId:null},{reason:'Malicious hold'}),'forbidden');}); test('adapter preserves permitted buyer countries instead of issuance location',()=>{const tx={id:'T-1',asset:'Example',marketAccess:{buyerId:'ORG-001',offerId:'A'},workflow:{stage:'reconciled'},externalExecution:{stage:'reconciled',reconciliation:{at:now},receipt:{},terms:{quantityUnits:'5000000',principalCents:10000},destination:{address:'EXT'},mirror:{decimals:6,network:'EVM',tokenRef:'TOKEN'}}};const p=A.platform([tx],[{id:'A',issuer:'ISSUER',issuanceCountry:'AE',buyerCountries:['SG']}],'ORG-001')[0];assert.deepEqual(p.policy.countries,['SG']);assert.deepEqual(A.platform([tx],[{id:'A',issuer:'ISSUER',issuanceCountry:'AE'}],'ORG-001')[0].policy.countries,[]);}); test('persisted outer settlement accounts and asset identifiers must equal signed instructions',()=>{const r=settling();for(const key of ['destination','beneficiary','controlRef','gatewayRef','buyerId','sourceAccount','network','tokenRef','quantity','version']){const s=JSON.parse(JSON.stringify(r.get()));s.requests[0].settlement[key]=key==='version'?100:'TAMPERED';assert.equal(M.valid(s),false,key);}});