'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); const {decimal, snapshotHash, settle} = require('./settlement-safety.cjs'); function fixture(portionId = 'p1') { const snapshot = {orderId: 'order-1', currency: 'USD', cashAmount: '100.00', instrumentId: 'instrument-1', assetUnits: '10', networkRef: 'network-1', cashDestination: {snapshotHash: 'cash-v1', recipientPartyRef: 'seller', destinationRef: 'bank-1'}, assetDestination: {snapshotHash: 'asset-v1', recipientPartyRef: 'buyer', destinationRef: 'wallet-1'}, portions: [{id: 'p1', cashAmount: '25', assetUnits: '2.5'}, {id: 'p2', cashAmount: '75', assetUnits: '7.5'}]}; const hash = snapshotHash(snapshot); const state = {accepted: {snapshot, hash, buyerAcceptedHash: hash, sellerAcceptedHash: hash}, settlements: [], usedSourceEvents: []}; const portion = snapshot.portions.find(p => p.id === portionId); const leg = (name, amount, unitOrCurrency) => ({leg: name, status: 'confirmed', sourceRef: 'provider-1', orderId: snapshot.orderId, settlementPortionRef: portionId, providerEventId: `${portionId}-${name}`, evidenceDocumentId: `evidence-${portionId}-${name}`, amount, unitOrCurrency, destinationSnapshotHash: snapshot[`${name}Destination`].snapshotHash, recipientPartyRef: snapshot[`${name}Destination`].recipientPartyRef, destinationRef: snapshot[`${name}Destination`].destinationRef, ...(name === 'asset' ? {instrumentId: snapshot.instrumentId, networkRef: snapshot.networkRef} : {})}); const command = {portionId, cash: leg('cash', portion.cashAmount, snapshot.currency), asset: leg('asset', portion.assetUnits, snapshot.instrumentId)}; const context = {destinations: ['cash', 'asset'].map(name => ({snapshotHash: snapshot[`${name}Destination`].snapshotHash, snapshot: structuredClone(snapshot[`${name}Destination`]), status: 'verified', evidenceDocumentId: `dest-${name}`, reviewedBy: 'destination-reviewer', ...(name === 'asset' ? {instrumentId: snapshot.instrumentId, networkRef: snapshot.networkRef} : {})})), evidence: [], review: {decision: 'approved', orderId: snapshot.orderId, portionId, cashEvidenceId: command.cash.evidenceDocumentId, assetEvidenceId: command.asset.evidenceDocumentId, reviewerId: 'independent-reviewer', evidenceRef: `review-${portionId}`}}; return refresh({state, command, context}); } function refresh(f) { f.context.evidence = [f.command.cash, f.command.asset].filter(Boolean).map(e => ({id: e.evidenceDocumentId, status: 'verified', event: structuredClone(e)})); return f; } function reject(f, code) { const before = structuredClone(f); assert.throws(() => settle(f.state, f.command, f.context), {code}); assert.deepEqual(f, before, 'denial must not mutate input'); } test('explicitly accepted partial then final settlement; no premature completion or float arithmetic', () => { const f = fixture(); const before = structuredClone(f); const first = settle(f.state, f.command, f.context); assert.deepEqual(first.result, {status: 'reconciled', settledCash: '25', settledUnits: '2.5', feeEligible: true, completed: false}); assert.deepEqual(f, before); const second = fixture('p2'); second.state = first.state; assert.equal(settle(second.state, second.command, second.context).result.completed, true); assert.equal(decimal('0.1') + decimal('0.2'), decimal('0.3')); }); for (const leg of ['cash', 'asset']) { for (const field of ['sourceRef', 'providerEventId', 'evidenceDocumentId']) { test(`confirmed ${leg} rejects empty ${field}`, () => {const f = fixture(); f.command[leg][field] = ' '; refresh(f); reject(f, 'CONFIRMATION_EVIDENCE_REQUIRED');}); } test(`confirmed ${leg} requires independently verified matching evidence`, () => { const f = fixture(); f.context.evidence.find(e => e.id === f.command[leg].evidenceDocumentId).status = 'pending'; reject(f, 'CONFIRMATION_EVIDENCE_UNVERIFIED'); }); test(`${leg} wrong recipient/destination/hash is rejected`, () => { for (const field of ['recipientPartyRef', 'destinationRef', 'destinationSnapshotHash']) { const f = fixture(); f.command[leg][field] = 'wrong'; refresh(f); reject(f, 'DESTINATION_MISMATCH'); } }); test(`${leg} missing or pending is not settled or fee eligible`, () => { for (const status of [null, 'reported', 'disputed', 'reversed']) { const f = fixture(); if (status) f.command[leg].status = status; else f.command[leg] = null; const out = settle(f.state, f.command, f.context); assert.equal(out.result.feeEligible, false); assert.equal(out.result.completed, false); assert.equal(out.result.settledCash, '0'); assert.strictEqual(out.state, f.state); } }); } for (const [leg, field, value, code] of [ ['cash', 'unitOrCurrency', 'EUR', 'CURRENCY_MISMATCH'], ['asset', 'unitOrCurrency', 'other-token', 'INSTRUMENT_MISMATCH'], ['asset', 'instrumentId', 'other-token', 'INSTRUMENT_MISMATCH'], ['asset', 'networkRef', 'other-network', 'NETWORK_MISMATCH'], ['cash', 'amount', '24.999999999999999999', 'AMOUNT_MISMATCH'], ['cash', 'amount', '25.000000000000000001', 'AMOUNT_MISMATCH'], ['asset', 'amount', '2.4', 'AMOUNT_MISMATCH'], ['asset', 'amount', '2.6', 'AMOUNT_MISMATCH'] ]) test(`${leg} ${field} mismatch ${value}`, () => {const f = fixture(); f.command[leg][field] = value; refresh(f); reject(f, code);}); test('changed destination needs a new verified snapshot and renewed acceptance', () => { const f = fixture(); f.state.accepted.snapshot.assetDestination.destinationRef = 'wallet-2'; reject(f, 'OBLIGATION_NOT_ACCEPTED'); const hash = snapshotHash(f.state.accepted.snapshot); Object.assign(f.state.accepted, {hash, buyerAcceptedHash: hash, sellerAcceptedHash: hash}); reject(f, 'DESTINATION_REAPPROVAL_REQUIRED'); f.state.accepted.snapshot.assetDestination.snapshotHash = 'asset-v2'; const renewed = snapshotHash(f.state.accepted.snapshot); Object.assign(f.state.accepted, {hash: renewed, buyerAcceptedHash: renewed, sellerAcceptedHash: renewed}); const approval = f.context.destinations[1]; approval.snapshotHash = 'asset-v2'; approval.snapshot = structuredClone(f.state.accepted.snapshot.assetDestination); Object.assign(f.command.asset, {destinationSnapshotHash: 'asset-v2', destinationRef: 'wallet-2'}); refresh(f); assert.equal(settle(f.state, f.command, f.context).result.feeEligible, true); }); test('revoked destination and wrong destination network block progress', () => { const revoked = fixture(); revoked.context.destinations[1].status = 'revoked'; reject(revoked, 'DESTINATION_REAPPROVAL_REQUIRED'); const network = fixture(); network.context.destinations[1].networkRef = 'wrong'; reject(network, 'DESTINATION_REAPPROVAL_REQUIRED'); }); test('duplicate settlement portion and globally used source event reject replay', () => { const f = fixture(); f.state = settle(f.state, f.command, f.context).state; reject(f, 'SETTLEMENT_REPLAY'); const other = fixture(); other.state.usedSourceEvents.push(JSON.stringify([other.command.cash.sourceRef, other.command.cash.providerEventId])); reject(other, 'SOURCE_EVENT_REPLAY'); }); test('unaccepted portion and altered accepted allocation fail closed', () => { const f = fixture(); f.command.portionId = 'p3'; reject(f, 'PORTION_NOT_ACCEPTED'); const bad = fixture(); bad.state.accepted.snapshot.portions[1].cashAmount = '76'; const hash = snapshotHash(bad.state.accepted.snapshot); Object.assign(bad.state.accepted, {hash, buyerAcceptedHash: hash, sellerAcceptedHash: hash}); reject(bad, 'ALLOCATION_MISMATCH'); }); test('corrupt cumulative history and duplicate prior portion cannot increase settled principal', () => { const f = fixture('p2'); f.state.settlements = [{portionId: 'p1', cashAmount: '26', assetUnits: '2.5', status: 'reconciled'}]; reject(f, 'HISTORY_INVALID'); const duplicate = fixture('p2'); const prior = {portionId: 'p1', cashAmount: '25', assetUnits: '2.5', status: 'reconciled'}; duplicate.state.settlements = [prior, {...prior}]; reject(duplicate, 'HISTORY_INVALID'); }); test('confirmation alone without bound independent reconciliation is not fee eligible', () => { const f = fixture(); f.context.review.portionId = 'other'; reject(f, 'RECONCILIATION_REQUIRED'); }); test('altered evidence payload, missing buyer acceptance and invalid decimals are rejected', () => { const evidence = fixture(); evidence.command.cash.amount = '26'; reject(evidence, 'CONFIRMATION_EVIDENCE_UNVERIFIED'); const acceptance = fixture(); acceptance.state.accepted.buyerAcceptedHash = 'wrong'; reject(acceptance, 'OBLIGATION_NOT_ACCEPTED'); for (const field of ['orderId', 'settlementPortionRef']) {const scope = fixture(); scope.command.cash[field] = 'other'; refresh(scope); reject(scope, 'EVIDENCE_SCOPE_MISMATCH');} const zero = fixture(); zero.command.cash.amount = '0'; refresh(zero); reject(zero, 'AMOUNT_NOT_POSITIVE'); for (const value of ['NaN', '-1', '1e3', '0.0000000000000000001', 25]) assert.throws(() => decimal(value), {code: 'INVALID_DECIMAL'}); });