'use strict'; // PROPOSED pure rules. Trusted evidence/approvals are injected fixtures, not authentication. const {createHash} = require('node:crypto'); const {isDeepStrictEqual} = require('node:util'); const SCALE = 10n ** 18n; function fail(code) { throw Object.assign(new Error(code), {code}); } function required(value, code = 'IDENTITY_REQUIRED') { if (typeof value !== 'string' || !value.trim()) fail(code); return value; } function decimal(value) { if (typeof value !== 'string' || !/^\d+(\.\d{1,18})?$/.test(value)) fail('INVALID_DECIMAL'); const [whole, fraction = ''] = value.split('.'); const normalized = whole.replace(/^0+(?=\d)/, ''); if (normalized.length > 20) fail('INVALID_DECIMAL'); return BigInt(normalized) * SCALE + BigInt(fraction.padEnd(18, '0')); } function positive(value) { const amount = decimal(value); if (amount <= 0n) fail('AMOUNT_NOT_POSITIVE'); return amount; } function canonical(value) { if (Array.isArray(value)) return value.map(canonical); if (value && typeof value === 'object') { return Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])])); } return value; } function snapshotHash(snapshot) { return createHash('sha256').update(JSON.stringify(canonical(snapshot))).digest('hex'); } function obligation(state) { const accepted = state.accepted; if (!accepted || accepted.hash !== snapshotHash(accepted.snapshot) || accepted.buyerAcceptedHash !== accepted.hash || accepted.sellerAcceptedHash !== accepted.hash) fail('OBLIGATION_NOT_ACCEPTED'); const o = accepted.snapshot; required(o.orderId); required(o.currency); required(o.instrumentId); required(o.networkRef); const cash = positive(o.cashAmount), units = positive(o.assetUnits); if (!Array.isArray(o.portions) || !o.portions.length) fail('PORTIONS_REQUIRED'); const ids = new Set(); let allocatedCash = 0n, allocatedUnits = 0n; for (const portion of o.portions) { required(portion.id); if (ids.has(portion.id)) fail('DUPLICATE_PORTION'); ids.add(portion.id); allocatedCash += positive(portion.cashAmount); allocatedUnits += positive(portion.assetUnits); } // Partial amounts must be explicitly accepted; no inferred ratio, rounding or tolerance. if (allocatedCash !== cash || allocatedUnits !== units) fail('ALLOCATION_MISMATCH'); return o; } function destination(expected, leg, o, context) { if (!expected) fail('DESTINATION_UNVERIFIED'); for (const field of ['snapshotHash', 'recipientPartyRef', 'destinationRef']) required(expected[field], 'DESTINATION_UNVERIFIED'); const approved = context.destinations?.find(d => d.snapshotHash === expected.snapshotHash); if (!approved || approved.status !== 'verified' || !isDeepStrictEqual(approved.snapshot, expected) || !approved.evidenceDocumentId?.trim() || !approved.reviewedBy?.trim()) fail('DESTINATION_REAPPROVAL_REQUIRED'); if (leg === 'asset' && (approved.instrumentId !== o.instrumentId || approved.networkRef !== o.networkRef)) fail('DESTINATION_REAPPROVAL_REQUIRED'); } function confirmed(event, leg, expectedAmount, portionId, o, context) { if (event.leg !== leg) fail('LEG_MISMATCH'); if (event.orderId !== o.orderId || event.settlementPortionRef !== portionId) fail('EVIDENCE_SCOPE_MISMATCH'); for (const field of ['sourceRef', 'providerEventId', 'evidenceDocumentId']) required(event[field], 'CONFIRMATION_EVIDENCE_REQUIRED'); const proof = context.evidence?.find(e => e.id === event.evidenceDocumentId); if (!proof || proof.status !== 'verified' || !isDeepStrictEqual(proof.event, event)) fail('CONFIRMATION_EVIDENCE_UNVERIFIED'); if (positive(event.amount) !== positive(expectedAmount)) fail('AMOUNT_MISMATCH'); if (event.unitOrCurrency !== (leg === 'cash' ? o.currency : o.instrumentId)) fail(leg === 'cash' ? 'CURRENCY_MISMATCH' : 'INSTRUMENT_MISMATCH'); if (leg === 'asset' && event.instrumentId !== o.instrumentId) fail('INSTRUMENT_MISMATCH'); if (leg === 'asset' && event.networkRef !== o.networkRef) fail('NETWORK_MISMATCH'); const d = o[`${leg}Destination`]; if (event.destinationSnapshotHash !== d.snapshotHash || event.destinationRef !== d.destinationRef || event.recipientPartyRef !== d.recipientPartyRef) fail('DESTINATION_MISMATCH'); return JSON.stringify([event.sourceRef, event.providerEventId]); } function settle(state, command, context) { const o = obligation(state); destination(o.cashDestination, 'cash', o, context); destination(o.assetDestination, 'asset', o, context); const portion = o.portions.find(p => p.id === command.portionId); if (!portion) fail('PORTION_NOT_ACCEPTED'); const history = state.settlements || []; if (history.some(p => p.portionId === portion.id)) fail('SETTLEMENT_REPLAY'); const pending = [command.cash, command.asset].some(e => !e || e.status !== 'confirmed'); if (pending) return {state, result: {status: 'pending', settledCash: '0', settledUnits: '0', feeEligible: false, completed: false}}; const cashKey = confirmed(command.cash, 'cash', portion.cashAmount, portion.id, o, context); const assetKey = confirmed(command.asset, 'asset', portion.assetUnits, portion.id, o, context); const used = state.usedSourceEvents || []; if (cashKey === assetKey || used.includes(cashKey) || used.includes(assetKey)) fail('SOURCE_EVENT_REPLAY'); const review = context.review; if (!review || review.decision !== 'approved' || review.orderId !== o.orderId || review.portionId !== portion.id || review.cashEvidenceId !== command.cash.evidenceDocumentId || review.assetEvidenceId !== command.asset.evidenceDocumentId || !review.reviewerId?.trim() || !review.evidenceRef?.trim()) fail('RECONCILIATION_REQUIRED'); let cash = positive(portion.cashAmount), units = positive(portion.assetUnits); const priorIds = new Set(); for (const prior of history) { const agreed = o.portions.find(p => p.id === prior.portionId); if (!agreed || priorIds.has(prior.portionId) || prior.status !== 'reconciled' || decimal(prior.cashAmount) !== positive(agreed.cashAmount) || decimal(prior.assetUnits) !== positive(agreed.assetUnits)) fail('HISTORY_INVALID'); priorIds.add(prior.portionId); cash += positive(prior.cashAmount); units += positive(prior.assetUnits); } if (cash > positive(o.cashAmount) || units > positive(o.assetUnits)) fail('CUMULATIVE_OVERDELIVERY'); const next = structuredClone(state); next.settlements = [...history, {portionId: portion.id, cashAmount: portion.cashAmount, assetUnits: portion.assetUnits, status: 'reconciled', cashEvidenceId: command.cash.evidenceDocumentId, assetEvidenceId: command.asset.evidenceDocumentId, reviewEvidenceRef: review.evidenceRef}]; next.usedSourceEvents = [...used, cashKey, assetKey]; return {state: next, result: {status: 'reconciled', settledCash: portion.cashAmount, settledUnits: portion.assetUnits, feeEligible: true, completed: cash === positive(o.cashAmount) && units === positive(o.assetUnits)}}; } module.exports = {decimal, snapshotHash, settle};