diff --git a/src/indexer/escrow-indexer.js b/src/indexer/escrow-indexer.js index 156be46b..7f1d571c 100644 --- a/src/indexer/escrow-indexer.js +++ b/src/indexer/escrow-indexer.js @@ -30,6 +30,7 @@ */ const { decodeEvent } = require('./decode'); +const chainSync = require('../services/chain-sync'); const { defaultStore } = require('./defaultEventStore'); const { getRpcServer } = require('../stellar/rpc'); const dataStore = require('../data/store'); @@ -148,6 +149,8 @@ async function indexChunk({ server, store, log, contractIds, cursorKey, maxPages let ingested = 0; let skipped = 0; let decodeFailures = 0; + let applied = 0; + let ignored = 0; let latestLedger = 0; let currentCursor = store.getCursor(cursorKey); @@ -219,6 +222,10 @@ async function indexChunk({ server, store, log, contractIds, cursorKey, maxPages ingested += appended; if (appended === 0) { skipped++; + } else { + const syncResult = chainSync.applyEvents([decoded]); + applied += syncResult.applied; + ignored += syncResult.ignored; } } catch (err) { decodeFailures++; @@ -248,7 +255,7 @@ async function indexChunk({ server, store, log, contractIds, cursorKey, maxPages } } - return { ingested, skipped, decodeFailures, cursor: store.getCursor(cursorKey), latestLedger }; + return { ingested, skipped, applied, ignored, decodeFailures, cursor: store.getCursor(cursorKey), latestLedger }; } let runOnceInFlight = false; @@ -315,6 +322,8 @@ async function runOnce({ let skipped = 0; let decodeFailures = 0; let ingested = 0; + let applied = 0; + let ignored = 0; let latestLedger = 0; /** @type {Record} */ const cursors = {}; @@ -332,6 +341,8 @@ async function runOnce({ }); ingested += result.ingested; skipped += result.skipped; + applied += result.applied || 0; + ignored += result.ignored || 0; decodeFailures += result.decodeFailures; latestLedger = result.latestLedger || latestLedger; lastCursor = result.cursor; @@ -341,6 +352,8 @@ async function runOnce({ return { ingested, skipped, + applied, + ignored, decodeFailures, cursor: contracts.length <= 1 ? _store.getCursor() : lastCursor, cursors, diff --git a/src/services/chain-sync.js b/src/services/chain-sync.js new file mode 100644 index 00000000..c65fb32c --- /dev/null +++ b/src/services/chain-sync.js @@ -0,0 +1,168 @@ +'use strict'; + +/** + * @fileoverview Applies decoded on-chain escrow events to the invoice data store. + * + * Idempotent: reapplying an event id is a no-op. Each applied event is audited + * with actor "indexer" and emits the same webhook events the API routes emit, + * so downstream subscriptions see on-chain-driven state changes identically. + * + * Event mapping (see src/indexer/decode.js EVENT_TYPE_MAP): + * funded — one investor contribution; records it via store.fund() + * funding_target_reached — invoice has reached its funding target (status already + * flipped by store.fund() when the last contribution arrived) + * settled — invoice settled; flip to settled, emit invoice.settled + * refunded — refund issued; flip to cancelled, emit invoice.cancelled + * funding_cancelled — funding cancelled; flip to cancelled, emit invoice.cancelled + * + * @module services/chain-sync + */ + +const defaultAuditLog = require('../audit/audit-log'); +const defaultEmitter = require('../webhooks/emitter'); +const defaultData = require('../data/store'); +const defaultContributions = require('../data/contributions'); + +/** Process-lifetime set of event ids already applied. */ +const appliedEventIds = new Set(); + +/** + * Returns the first present, non-empty field from `names` on `obj`. + * + * @param {object|null|undefined} obj + * @param {string[]} names + * @returns {unknown} + */ +function pickField(obj, names) { + if (!obj || typeof obj !== 'object') { return undefined; } + for (const n of names) { + const v = obj[n]; + if (v !== undefined && v !== null && v !== '') { return v; } + } + return undefined; +} + +/** + * @param {object[]} events decoded events (any order) + * @param {object} [opts] + * @param {object} [opts.data] invoice store (default: ../data/store) + * @param {object} [opts.contributions] contributions store (default: ../data/contributions) + * @param {object} [opts.audit] audit log (default: ../audit/audit-log.auditLog) + * @param {object} [opts.emitter] webhook emitter (default: ../webhooks/emitter) + * @param {Set} [opts.appliedIds] applied-id set (default: module singleton) + * @returns {{applied:number, ignored:number, byType:object, ignoredReasons:object}} + */ +function applyEvents(events, opts = {}) { + const data = opts.data || defaultData; + const contribs = opts.contributions || defaultContributions; + const auditLog = opts.audit || defaultAuditLog.auditLog; + const em = opts.emitter || defaultEmitter; + const appliedIds = opts.appliedIds || appliedEventIds; + + const summary = { applied: 0, ignored: 0, byType: {}, ignoredReasons: {} }; + const bump = (k) => { summary.byType[k] = (summary.byType[k] || 0) + 1; }; + const bumpIgnore = (k) => { summary.ignoredReasons[k] = (summary.ignoredReasons[k] || 0) + 1; }; + + const sorted = [...events].sort((a, b) => { + const la = Number(a.ledger ?? 0); const lb = Number(b.ledger ?? 0); + if (la !== lb) { return la - lb; } + return String(a.id || '').localeCompare(String(b.id || '')); + }); + + for (const evt of sorted) { + if (!evt || !evt.id || appliedIds.has(evt.id)) { + summary.ignored += 1; bumpIgnore('duplicate'); continue; + } + if (!evt.contractId) { + summary.ignored += 1; bumpIgnore('noContractId'); continue; + } + + const invoice = data.list().find((inv) => inv.escrowContractId === evt.contractId); + if (!invoice) { + summary.ignored += 1; bumpIgnore('unknownContract'); continue; + } + + const terminal = invoice.status === 'settled' || invoice.status === 'cancelled'; + let mutated = false; + + switch (evt.type) { + case 'funded': { + if (terminal) { summary.ignored += 1; bumpIgnore('stateConflict'); continue; } + const investor = pickField(evt.data, ['investor', 'investor_address', 'from', 'sender']); + const rawAmount = pickField(evt.data, ['amount', 'amount_minor', 'amountMinor', 'amount_i128', 'amt']); + if (!investor || rawAmount === undefined) { + summary.ignored += 1; bumpIgnore('malformedData'); continue; + } + try { + data.fund(invoice, Number(rawAmount), String(investor)); + } catch (err) { + summary.ignored += 1; bumpIgnore('fundRejected'); continue; + } + em.emit('invoice.funding_received', invoice); + mutated = true; + break; + } + case 'funding_target_reached': { + // Status was flipped by store.fund() when the last contribution arrived. + // Emit the webhook if the invoice is funded and we have not yet (the emitter + // is idempotent per subscriber; duplicate deliveries are acceptable per + // the existing webhook contract, and the applied-id set prevents re-firing + // for the same event). + if (invoice.status !== 'funded') { + summary.ignored += 1; bumpIgnore('stateConflict'); continue; + } + em.emit('invoice.funded', invoice); + mutated = true; + break; + } + case 'settled': { + if (invoice.status === 'settled') { summary.ignored += 1; bumpIgnore('duplicate'); continue; } + if (invoice.status === 'cancelled') { summary.ignored += 1; bumpIgnore('stateConflict'); continue; } + data.settle(invoice); + em.emit('invoice.settled', invoice); + mutated = true; + break; + } + case 'refunded': + case 'funding_cancelled': { + if (invoice.status === 'cancelled') { summary.ignored += 1; bumpIgnore('duplicate'); continue; } + if (invoice.status === 'settled') { summary.ignored += 1; bumpIgnore('stateConflict'); continue; } + data.cancel(invoice); + em.emit('invoice.cancelled', invoice); + mutated = true; + break; + } + default: { + summary.ignored += 1; bumpIgnore('unknownType:' + evt.type); continue; + } + } + + if (mutated) { + try { + if (auditLog && typeof auditLog.append === 'function') { + auditLog.append({ + action: 'invoice.chain_sync', + resourceType: 'invoice', + resourceId: invoice.id, + actor: 'indexer', + outcome: 'success', + statusCode: 200, + metadata: { eventId: evt.id, eventType: evt.type, ledger: evt.ledger, txHash: evt.txHash }, + }); + } + } catch (err) { + // Audit failures must not break sync + } + appliedIds.add(evt.id); + summary.applied += 1; + bump(evt.type); + } + } + + return summary; +} + +/** @returns {void} clears the applied-event-id set (tests only) */ +function resetAppliedIdsForTests() { appliedEventIds.clear(); } + +module.exports = { applyEvents, resetAppliedIdsForTests, _appliedIds: appliedEventIds }; \ No newline at end of file diff --git a/tests/chain-sync.test.js b/tests/chain-sync.test.js new file mode 100644 index 00000000..70edb765 --- /dev/null +++ b/tests/chain-sync.test.js @@ -0,0 +1,214 @@ +'use strict'; + +/** + * Tests for src/services/chain-sync.js + * + * Uses the in-memory adapter (fresh per test) so no DB or network is needed. + * Each test builds synthetic decoded events with the same shape decodeEvent() + * produces: { id, type, ledger, contractId, data: { ... } }. + */ + +const chainSync = require('../src/services/chain-sync'); +const store = require('../src/data/store'); +const contributions = require('../src/data/contributions'); +const emitter = require('../src/webhooks/emitter'); +const auditLog = require('../src/audit/audit-log'); + +const CONTRACT = 'CAAAAAAA0000000000000000000000000000000000000000000000'; +const OTHER_CONTRACT = 'CBBBBBBB0000000000000000000000000000000000000000000000'; + +function evt({ id, type, ledger = 1, contractId = CONTRACT, data = {} }) { + return { id, type, ledger, contractId, data }; +} + +function linkInvoice(invoiceId) { + const inv = store.get(invoiceId); + if (!inv) { throw new Error('no invoice ' + invoiceId); } + // Set the contract id directly: the seed data for INV_0001 already carries + // a (possibly non-empty) config.contractId, so linkEscrow() would return + // ALREADY_LINKED. Every test wants OUR contract id, so just assign it. + inv.escrowContractId = CONTRACT; + return inv; +} + +beforeEach(() => { + chainSync.resetAppliedIdsForTests(); + store.reset(); + auditLog.auditLog.resetForTests(); +}); + +describe('chain-sync.applyEvents', () => { + test('funded for a linked invoice records the contribution and returns applied:1', () => { + const inv = linkInvoice('INV_0002'); // seeded: remaining 7000 (fits amounts up to 7000) + const before = contributions.sumForInvoice(inv.id); + + const res = chainSync.applyEvents([ + evt({ id: 'e1', type: 'funded', data: { investor: 'GINVESTOR1', amount: '1000' } }), + ]); + + expect(res.applied).toBe(1); + expect(res.ignored).toBe(0); + expect(res.byType.funded).toBe(1); + expect(contributions.sumForInvoice(inv.id)).toBe(before + 1000n * 10000000n); // amount is whole units; sumForInvoice returns stroops + }); + + test('duplicate event is ignored (idempotent)', () => { + linkInvoice('INV_0002'); + const e = evt({ id: 'dup-1', type: 'funded', data: { investor: 'GINVESTOR1', amount: '500' } }); + + const first = chainSync.applyEvents([e]); + const second = chainSync.applyEvents([e]); + + expect(first.applied).toBe(1); + expect(second.applied).toBe(0); + expect(second.ignored).toBe(1); + expect(second.ignoredReasons.duplicate).toBe(1); + }); + + test('unknown contract is ignored', () => { + const res = chainSync.applyEvents([ + evt({ id: 'x1', type: 'funded', contractId: OTHER_CONTRACT, data: { investor: 'G', amount: '10' } }), + ]); + expect(res.applied).toBe(0); + expect(res.ignoredReasons.unknownContract).toBe(1); + }); + + test('malformed funded data is ignored (no investor or amount)', () => { + linkInvoice('INV_0002'); + const res = chainSync.applyEvents([ + evt({ id: 'm1', type: 'funded', data: {} }), + ]); + expect(res.ignoredReasons.malformedData).toBe(1); + }); + + test('funded against a settled invoice is ignored (state conflict)', () => { + const inv = linkInvoice('INV_0004'); // seeded as settled + const res = chainSync.applyEvents([ + evt({ id: 'sc1', type: 'funded', data: { investor: 'G', amount: '10' } }), + ]); + expect(res.applied).toBe(0); + expect(res.ignoredReasons.stateConflict).toBe(1); + expect(inv.status).toBe('settled'); + }); + + test('funding_target_reached flips status to funded and emits invoice.funded', () => { + const inv = linkInvoice('INV_0002'); // seeded: amountMinor 25000, fundedAmountMinor 18000, remaining 7000 + // Fund the remaining capacity to reach the target. + chainSync.applyEvents([ + evt({ id: 'f-full', type: 'funded', data: { investor: 'G', amount: '7000' } }), + ]); + expect(inv.status).toBe('funded'); + + const received = []; + const listener = (invoice) => received.push(invoice.id); + emitter.on('invoice.funded', listener); + try { + const res = chainSync.applyEvents([ + evt({ id: 'tgt-1', type: 'funding_target_reached', data: {} }), + ]); + expect(res.applied).toBe(1); + expect(res.byType.funding_target_reached).toBe(1); + expect(received).toEqual([inv.id]); + } finally { + emitter.off('invoice.funded', listener); + } + }); + + test('funding_target_reached on an unfunded invoice is ignored', () => { + linkInvoice('INV_0002'); // still open (only 7000 of 25000 remaining to fill) + const res = chainSync.applyEvents([ + evt({ id: 'tgt-bad', type: 'funding_target_reached', data: {} }), + ]); + expect(res.applied).toBe(0); + expect(res.ignoredReasons.stateConflict).toBe(1); + }); + + test('settled flips status, emits invoice.settled, and writes an audit entry with actor=indexer', () => { + const inv = linkInvoice('INV_0003'); // seeded as funded + const received = []; + const listener = (invoice) => received.push(invoice.id); + emitter.on('invoice.settled', listener); + try { + const res = chainSync.applyEvents([ + evt({ id: 'st-1', type: 'settled', ledger: 100, data: {} }), + ]); + expect(res.applied).toBe(1); + expect(inv.status).toBe('settled'); + expect(received).toEqual([inv.id]); + + const entries = auditLog.auditLog.entries(); + const entry = entries.find((e) => e.action === 'invoice.chain_sync' && e.resourceId === inv.id); + expect(entry).toBeDefined(); + expect(entry.actor).toBe('indexer'); + expect(entry.outcome).toBe('success'); + expect(entry.metadata.eventId).toBe('st-1'); + } finally { + emitter.off('invoice.settled', listener); + } + }); + + test('settled twice — second is duplicate', () => { + linkInvoice('INV_0003'); + const e = evt({ id: 'st-dup', type: 'settled' }); + chainSync.applyEvents([e]); + const second = chainSync.applyEvents([e]); + expect(second.ignoredReasons.duplicate).toBe(1); + }); + + test('refunded flips status to cancelled and emits invoice.cancelled', () => { + const inv = linkInvoice('INV_0003'); + const received = []; + const listener = (invoice) => received.push(invoice.id); + emitter.on('invoice.cancelled', listener); + try { + const res = chainSync.applyEvents([ + evt({ id: 'ref-1', type: 'refunded' }), + ]); + expect(res.applied).toBe(1); + expect(inv.status).toBe('cancelled'); + expect(received).toEqual([inv.id]); + } finally { + emitter.off('invoice.cancelled', listener); + } + }); + + test('funding_cancelled flips status to cancelled', () => { + const inv = linkInvoice('INV_0003'); + const res = chainSync.applyEvents([evt({ id: 'fc-1', type: 'funding_cancelled' })]); + expect(res.applied).toBe(1); + expect(inv.status).toBe('cancelled'); + }); + + test('out-of-order ledgers: settled at ledger 50 before funded at ledger 10 — settled is applied, funded then ignored as state conflict', () => { + const inv = linkInvoice('INV_0001'); // open, empty + // INV_0001 starts empty; funded applies at ledger 10, settled at ledger 50. + const res = chainSync.applyEvents([ + evt({ id: 'oo-settled', type: 'settled', ledger: 50 }), + evt({ id: 'oo-funded', type: 'funded', ledger: 10, data: { investor: 'G', amount: '100' } }), + ]); + + // Sorted by ledger: funded first (10), then settled (50). + expect(inv.status).toBe('settled'); + expect(res.applied).toBe(2); + }); + + test('full replay of the same event list is a no-op', () => { + linkInvoice('INV_0002'); // remaining capacity 7000 + const events = [ + evt({ id: 'r1', type: 'funded', data: { investor: 'G1', amount: '500' } }), + evt({ id: 'r2', type: 'settled' }), + ]; + const first = chainSync.applyEvents(events); + const second = chainSync.applyEvents(events); + expect(first.applied).toBe(2); + expect(second.applied).toBe(0); + expect(second.ignored).toBe(2); + }); + + test('unknown event type is ignored with a specific reason', () => { + linkInvoice('INV_0002'); + const res = chainSync.applyEvents([evt({ id: 'u1', type: 'unknown' })]); + expect(res.applied).toBe(0); + expect(Object.keys(res.ignoredReasons).some((k) => k.startsWith('unknownType:'))).toBe(true); + }); +}); \ No newline at end of file