diff --git a/backend/.env.example b/backend/.env.example index d4a4ceb6..2fb40dd5 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -159,6 +159,7 @@ EMAIL_RATE_LIMIT_PER_HOUR=100 # Soroban rail and submission processor. SOROBAN_ENABLED=false STELLAR_ESCROW_CONTRACT_ID=your_stellar_escrow_contract_id +STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID=your_stellar_revenue_distribution_contract_id STELLAR_SECRET_KEY=your_stellar_secret_key STELLAR_NETWORK=your_stellar_network_passphrase STELLAR_BENEFICIARY_ADDRESS=your_stellar_beneficiary_address diff --git a/backend/src/app.service.spec.ts b/backend/src/app.service.spec.ts new file mode 100644 index 00000000..0ed48ed5 --- /dev/null +++ b/backend/src/app.service.spec.ts @@ -0,0 +1,40 @@ +jest.mock('ioredis', () => ({ + __esModule: true, + default: jest.fn().mockImplementation(() => ({ + connect: jest.fn().mockResolvedValue(undefined), + ping: jest.fn().mockResolvedValue('PONG'), + quit: jest.fn().mockResolvedValue('OK'), + disconnect: jest.fn(), + })), +})); + +import { ConfigService } from '@nestjs/config'; +import { DataSource } from 'typeorm'; +import { AppService } from './app.service'; +import { SorobanRailStatus } from './payments/soroban/soroban-rail-status'; + +describe('AppService.getHealth', () => { + it('reports a Soroban version-check failure as a degraded dependency', async () => { + const status = new SorobanRailStatus(); + status.markUnavailable('payment_escrow interface version mismatch'); + const service = new AppService( + { query: jest.fn().mockResolvedValue([]) } as unknown as DataSource, + { + get: jest.fn((_key: string, fallback: unknown) => fallback), + } as unknown as ConfigService, + status, + ); + + await expect(service.getHealth()).resolves.toMatchObject({ + status: 'degraded', + dependencies: { + postgres: { status: 'up' }, + redis: { status: 'up' }, + soroban: { + status: 'down', + detail: 'payment_escrow interface version mismatch', + }, + }, + }); + }); +}); diff --git a/backend/src/app.service.ts b/backend/src/app.service.ts index 39404639..5bd166e3 100644 --- a/backend/src/app.service.ts +++ b/backend/src/app.service.ts @@ -2,12 +2,14 @@ import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { DataSource } from 'typeorm'; import Redis from 'ioredis'; +import { SorobanRailStatus } from './payments/soroban/soroban-rail-status'; @Injectable() export class AppService { constructor( private readonly dataSource: DataSource, private readonly config: ConfigService, + private readonly sorobanRailStatus: SorobanRailStatus, ) {} async getHealth(): Promise<{ @@ -15,22 +17,27 @@ export class AppService { dependencies: { postgres: { status: 'up' | 'down'; detail?: string }; redis: { status: 'up' | 'down'; detail?: string }; + soroban: + | { status: 'disabled' | 'up' } + | { status: 'down'; detail: string }; }; }> { const [postgres, redis] = await Promise.all([ this.checkPostgres(), this.checkRedis(), ]); + const soroban = this.sorobanRailStatus.getHealth(); - const failed = [postgres, redis].filter((entry) => entry.status === 'down'); + const dependencies = [postgres, redis, soroban]; + const failed = dependencies.filter((entry) => entry.status === 'down'); const status = failed.length === 0 ? 'ok' - : failed.length === 2 + : failed.length === dependencies.length ? 'unhealthy' : 'degraded'; - return { status, dependencies: { postgres, redis } }; + return { status, dependencies: { postgres, redis, soroban } }; } private async checkPostgres(): Promise<{ diff --git a/backend/src/payments/payments.module.ts b/backend/src/payments/payments.module.ts index 3f92a0fd..4c4fc528 100644 --- a/backend/src/payments/payments.module.ts +++ b/backend/src/payments/payments.module.ts @@ -37,6 +37,8 @@ import { createSorobanRpcServer, parseSorobanRpcTimeoutMs, } from './soroban/soroban-rpc-client'; +import { assertSorobanContractVersions } from './soroban/soroban-contract-version'; +import { SorobanRailStatus } from './soroban/soroban-rail-status'; import { ESCROW_CONTRACT_CLIENT, SOROBAN_CONFIG, @@ -78,10 +80,51 @@ import { // SOROBAN_RAIL_ADAPTER itself, which is what PaymentRailRegistry // checks. A disabled rail never makes an RPC call or touches a // wallet; it's simply unavailable, with a clear error if selected. + SorobanRailStatus, { provide: SOROBAN_CONFIG, - inject: [ConfigService], - useFactory: (config: ConfigService) => loadSorobanConfig(config), + inject: [ConfigService, SorobanRailStatus], + useFactory: async ( + config: ConfigService, + railStatus: SorobanRailStatus, + ) => { + const sorobanConfig = loadSorobanConfig(config); + if (!sorobanConfig) { + railStatus.markDisabled(); + return null; + } + + const timeoutMs = parseSorobanRpcTimeoutMs( + config.get( + 'SOROBAN_RPC_TIMEOUT_MS', + DEFAULT_SOROBAN_RPC_TIMEOUT_MS, + ), + ); + try { + const startupRpc = new SorobanRpcClient( + sorobanConfig.rpcUrls.map(createSorobanRpcServer), + timeoutMs, + ); + await assertSorobanContractVersions( + sorobanConfig, + async (contractId, sourceAccountPublicKey) => + new EscrowContractClient( + startupRpc, + contractId, + sorobanConfig.networkPassphrase, + ).getContractVersion(sourceAccountPublicKey), + ); + railStatus.markReady(); + return sorobanConfig; + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + railStatus.markUnavailable(detail); + new Logger(PaymentsModule.name).error( + `Soroban rail disabled: ${detail}`, + ); + return null; + } + }, }, { provide: SorobanRpcClient, @@ -167,6 +210,7 @@ import { PaymentConfirmationService, ReconciliationService, EXTERNAL_PAYOUT_RAIL, + SorobanRailStatus, ], }) export class PaymentsModule implements OnModuleInit { diff --git a/backend/src/payments/soroban/README.md b/backend/src/payments/soroban/README.md index c4da0d90..c51f396d 100644 --- a/backend/src/payments/soroban/README.md +++ b/backend/src/payments/soroban/README.md @@ -14,7 +14,8 @@ skipped: - **No live testnet deployment.** `SOROBAN_ENABLED` defaults to `false`; nothing here activates until an operator deploys a contract and sets - `STELLAR_ESCROW_CONTRACT_ID` and friends (see `.env.example`). Doing an + `STELLAR_ESCROW_CONTRACT_ID`, `STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID`, + and friends (see `.env.example`). Doing an actual testnet deployment is an operational action (funding an account, running the Stellar CLI) outside what a PR's CI can respons­ibly do. - **`escrow-contract.client.ts` is hand-written, not generated.** @@ -24,6 +25,9 @@ skipped: swap them in — nothing else in this module depends on how a call is XDR-encoded, only on the method signatures `EscrowContractClient` exposes now. +- On startup, the backend simulates `version()` on both configured contracts. + A mismatch or failed version check disables the Soroban rail and marks it + unhealthy in `/health/dependencies`. ## Escrow-ID discipline diff --git a/backend/src/payments/soroban/contract-error-codes.spec.ts b/backend/src/payments/soroban/contract-error-codes.spec.ts new file mode 100644 index 00000000..598d0115 --- /dev/null +++ b/backend/src/payments/soroban/contract-error-codes.spec.ts @@ -0,0 +1,54 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const contractsDirectory = resolve(__dirname, '../../../../contracts'); + +function parseEnum(source: string, expression: RegExp): [string, number][] { + const body = source.match(expression)?.[1]; + if (!body) { + throw new Error(`Could not find enum in source`); + } + const members: [string, number][] = []; + for (const line of body.split('\n')) { + const match = line + .replace(/\/\/.*$/, '') + .match(/^\s*(\w+)\s*=\s*(\d+)\s*,?\s*$/); + if (match) { + members.push([match[1], Number(match[2])]); + } + } + return members.sort((left, right) => left[1] - right[1]); +} + +describe('shared Soroban contract error codes', () => { + const sharedCodes = readFileSync( + resolve(contractsDirectory, 'shared/error-codes.ts'), + 'utf8', + ); + const paymentRust = readFileSync( + resolve(contractsDirectory, 'payment_escrow/src/lib.rs'), + 'utf8', + ); + const revenueRust = readFileSync( + resolve(contractsDirectory, 'revenue_distribution/src/lib.rs'), + 'utf8', + ); + + it('matches every payment_escrow Rust error code', () => { + expect( + parseEnum( + sharedCodes, + /export enum PaymentEscrowError\s*\{([\s\S]*?)\n\}/, + ), + ).toEqual(parseEnum(paymentRust, /pub enum Error\s*\{([\s\S]*?)\n\}/)); + }); + + it('matches every revenue_distribution Rust error code', () => { + expect( + parseEnum( + sharedCodes, + /export enum RevenueDistributionError\s*\{([\s\S]*?)\n\}/, + ), + ).toEqual(parseEnum(revenueRust, /pub enum Error\s*\{([\s\S]*?)\n\}/)); + }); +}); diff --git a/backend/src/payments/soroban/escrow-contract.client.spec.ts b/backend/src/payments/soroban/escrow-contract.client.spec.ts index e725bc81..0f5e4145 100644 --- a/backend/src/payments/soroban/escrow-contract.client.spec.ts +++ b/backend/src/payments/soroban/escrow-contract.client.spec.ts @@ -4,7 +4,7 @@ import { attachSignature, } from './escrow-contract.client'; import { EscrowStatus } from './escrow-status.enum'; -import { Account, Keypair, StrKey } from '@stellar/stellar-sdk'; +import { Account, Keypair, nativeToScVal, StrKey } from '@stellar/stellar-sdk'; const CONTRACT_ID = StrKey.encodeContract(Buffer.alloc(32, 1)); @@ -155,6 +155,29 @@ describe('EscrowContractClient', () => { }); }); + describe('getContractVersion', () => { + it('simulates version() and returns the contract interface version', async () => { + const rpc = makeRpc({ + getAccount: jest + .fn() + .mockResolvedValue(new Account(Keypair.random().publicKey(), '1')), + simulateTransaction: jest.fn().mockResolvedValue({ + result: { retval: nativeToScVal(2, { type: 'u32' }) }, + }), + }); + const client = new EscrowContractClient( + rpc as any, + CONTRACT_ID, + 'passphrase', + ); + + await expect( + client.getContractVersion(Keypair.random().publicKey()), + ).resolves.toBe(2); + expect(rpc.simulateTransaction).toHaveBeenCalledTimes(1); + }); + }); + describe('attachSignature', () => { it('appends a decorated signature carrying the signer public key hint', () => { const signer = Keypair.random(); diff --git a/backend/src/payments/soroban/escrow-contract.client.ts b/backend/src/payments/soroban/escrow-contract.client.ts index 707e9492..1e0a301d 100644 --- a/backend/src/payments/soroban/escrow-contract.client.ts +++ b/backend/src/payments/soroban/escrow-contract.client.ts @@ -40,20 +40,8 @@ import { withSpan } from '../../common/tracing'; import { SorobanRpcClient } from './soroban-rpc-client'; import { EscrowStatus } from './escrow-status.enum'; -// --------------------------------------------------------------------------- -// Generated contract-error enum (mirrors contracts/payment_escrow Error) -// --------------------------------------------------------------------------- -export enum ContractError { - NotFound = 1, - AlreadyResolved = 2, - InvalidAmount = 3, - AlreadyExists = 4, - ArithmeticOverflow = 5, - TokenNotAllowed = 22, - TransferShortfall = 23, -} +export { PaymentEscrowError as ContractError } from '../../../../contracts/shared/error-codes'; -// --------------------------------------------------------------------------- // Generated client class — preserves all public method names / signatures // --------------------------------------------------------------------------- export class EscrowContractClient { @@ -160,6 +148,26 @@ export class EscrowContractClient { }); } + async getContractVersion(sourceAccountPublicKey: string): Promise { + const tx = await this.build(sourceAccountPublicKey, 'version', []); + const sim = await this.rpc.simulateTransaction(tx); + if (SorobanRpc.Api.isSimulationError(sim)) { + throw new Error(`Contract version() simulation failed: ${sim.error}`); + } + + const retval = sim.result?.retval ?? sim.results?.[0]?.retval; + if (!retval) { + throw new Error('Contract version() simulation returned no value'); + } + const version = Number(scValToNative(retval)); + if (!Number.isSafeInteger(version) || version < 0) { + throw new Error( + `Contract version() returned an invalid value: ${version}`, + ); + } + return version; + } + private static mapRawStatus(raw: number): EscrowStatus { switch (raw) { case 1: diff --git a/backend/src/payments/soroban/escrow-submission.processor.ts b/backend/src/payments/soroban/escrow-submission.processor.ts index 178e3f42..45d70e1c 100644 --- a/backend/src/payments/soroban/escrow-submission.processor.ts +++ b/backend/src/payments/soroban/escrow-submission.processor.ts @@ -201,27 +201,35 @@ export class EscrowSubmissionProcessor { ): Promise { const mapping = mapSorobanError(error); - if (mapping.alreadySucceeded) { + if (mapping.disposition === 'already-succeeded') { // A retried create against the contract's own idempotent guard — // resolve from fresh state rather than assuming anything. - await this.resolveFromFreshState(payment, escrowId, payerAddress, 'retry'); + await this.resolveFromFreshState( + payment, + escrowId, + payerAddress, + 'retry', + ); return; } - if (mapping.reason === null) { - // Indeterminate (network/timeout/RPC down) — NOT a definite verdict - // that the transaction didn't land. Never fail the payment and - // never resubmit here; reconciliation asks the chain directly, - // independent of this attempt's own bounded poll. + if (mapping.disposition !== 'terminal') { + // Retryable, manual-review and indeterminate errors stay pending so + // reconciliation can re-read the chain without trusting this attempt. this.logger.warn( - `Payment ${payment.id}: create submission indeterminate (` + + `Payment ${payment.id}: create submission ${mapping.disposition} (` + (error instanceof Error ? error.message : String(error)) + ') — leaving AWAITING_CONFIRMATION', ); return; } - await this.applyOutcome(payment, escrowId, 'failed', mapping.reason); + await this.applyOutcome( + payment, + escrowId, + 'failed', + mapping.reason ?? PaymentFailureReason.CONTRACT_REVERTED, + ); } private async applyOutcome( @@ -372,7 +380,11 @@ export class EscrowSubmissionProcessor { ); return; } - await this.submitTreasuryAction(data.escrowIdHex, 'release', payerAddress); + await this.submitTreasuryAction( + data.escrowIdHex, + 'release', + payerAddress, + ); } catch (error) { const mapping = mapSorobanError(error); if (mapping.alreadySucceeded) { diff --git a/backend/src/payments/soroban/soroban-config.spec.ts b/backend/src/payments/soroban/soroban-config.spec.ts index 17fdab9e..0ed25307 100644 --- a/backend/src/payments/soroban/soroban-config.spec.ts +++ b/backend/src/payments/soroban/soroban-config.spec.ts @@ -26,7 +26,7 @@ describe('loadSorobanConfig', () => { const config = makeConfig({ SOROBAN_ENABLED: 'true' }); expect(() => loadSorobanConfig(config as any)).toThrow( - /STELLAR_ESCROW_CONTRACT_ID.*STELLAR_SECRET_KEY.*STELLAR_NETWORK.*STELLAR_BENEFICIARY_ADDRESS.*STELLAR_ESCROW_TOKEN_ADDRESSES/, + /STELLAR_ESCROW_CONTRACT_ID.*STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID.*STELLAR_SECRET_KEY.*STELLAR_NETWORK.*STELLAR_BENEFICIARY_ADDRESS.*STELLAR_ESCROW_TOKEN_ADDRESSES/, ); }); @@ -34,6 +34,7 @@ describe('loadSorobanConfig', () => { const config = makeConfig({ SOROBAN_ENABLED: 'true', STELLAR_ESCROW_CONTRACT_ID: 'CCONTRACT', + STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID: 'CDISTRIBUTION', STELLAR_SECRET_KEY: TREASURY.secret(), STELLAR_NETWORK: 'Test SDF Network ; September 2015', STELLAR_BENEFICIARY_ADDRESS: 'GBENEFICIARY', @@ -43,6 +44,7 @@ describe('loadSorobanConfig', () => { expect(loadSorobanConfig(config as any)).toEqual({ contractId: 'CCONTRACT', + revenueDistributionContractId: 'CDISTRIBUTION', networkPassphrase: 'Test SDF Network ; September 2015', treasurySecretKey: TREASURY.secret(), treasuryPublicKey: TREASURY.publicKey(), @@ -56,6 +58,7 @@ describe('loadSorobanConfig', () => { const config = makeConfig({ SOROBAN_ENABLED: 'true', STELLAR_ESCROW_CONTRACT_ID: 'CCONTRACT', + STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID: 'CDISTRIBUTION', STELLAR_SECRET_KEY: TREASURY.secret(), STELLAR_NETWORK: 'Test SDF Network ; September 2015', STELLAR_BENEFICIARY_ADDRESS: 'GBENEFICIARY', diff --git a/backend/src/payments/soroban/soroban-config.ts b/backend/src/payments/soroban/soroban-config.ts index 59410d87..c65da20e 100644 --- a/backend/src/payments/soroban/soroban-config.ts +++ b/backend/src/payments/soroban/soroban-config.ts @@ -3,6 +3,7 @@ import { Keypair } from '@stellar/stellar-sdk'; export interface SorobanConfig { contractId: string; + revenueDistributionContractId: string; networkPassphrase: string; treasurySecretKey: string; /** Derived once at load time — the treasury's own signing key never leaves loadSorobanConfig. */ @@ -19,6 +20,7 @@ export interface SorobanConfig { const REQUIRED_KEYS = [ 'STELLAR_ESCROW_CONTRACT_ID', + 'STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID', 'STELLAR_SECRET_KEY', 'STELLAR_NETWORK', 'STELLAR_BENEFICIARY_ADDRESS', @@ -31,7 +33,10 @@ const REQUIRED_KEYS = [ */ function parseEscrowTokenAddresses(raw: string): Record { const result: Record = {}; - for (const pair of raw.split(',').map((p) => p.trim()).filter(Boolean)) { + for (const pair of raw + .split(',') + .map((p) => p.trim()) + .filter(Boolean)) { const [currency, address] = pair.split(':').map((p) => p.trim()); if (currency && address) { result[currency.toUpperCase()] = address; @@ -90,6 +95,9 @@ export function loadSorobanConfig(config: ConfigService): SorobanConfig | null { return { contractId: config.get('STELLAR_ESCROW_CONTRACT_ID')!, + revenueDistributionContractId: config.get( + 'STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID', + )!, networkPassphrase: config.get('STELLAR_NETWORK')!, treasurySecretKey, treasuryPublicKey: Keypair.fromSecret(treasurySecretKey).publicKey(), diff --git a/backend/src/payments/soroban/soroban-contract-version.spec.ts b/backend/src/payments/soroban/soroban-contract-version.spec.ts new file mode 100644 index 00000000..490f485e --- /dev/null +++ b/backend/src/payments/soroban/soroban-contract-version.spec.ts @@ -0,0 +1,35 @@ +import { assertSorobanContractVersions } from './soroban-contract-version'; + +describe('assertSorobanContractVersions', () => { + const config = { + contractId: 'CESCROW', + revenueDistributionContractId: 'CDISTRIBUTION', + treasuryPublicKey: 'GTREASURY', + }; + + it('checks both configured contracts against their expected versions', async () => { + const readVersion = jest + .fn() + .mockResolvedValueOnce(2) + .mockResolvedValueOnce(2); + + await expect( + assertSorobanContractVersions(config, readVersion), + ).resolves.toBeUndefined(); + expect(readVersion.mock.calls).toEqual([ + ['CESCROW', 'GTREASURY'], + ['CDISTRIBUTION', 'GTREASURY'], + ]); + }); + + it('rejects a mismatched version with the contract name and expected value', async () => { + const readVersion = jest.fn().mockResolvedValueOnce(1); + + await expect( + assertSorobanContractVersions(config, readVersion), + ).rejects.toThrow( + 'payment_escrow interface version mismatch: expected 2, got 1', + ); + expect(readVersion).toHaveBeenCalledTimes(1); + }); +}); diff --git a/backend/src/payments/soroban/soroban-contract-version.ts b/backend/src/payments/soroban/soroban-contract-version.ts new file mode 100644 index 00000000..d8fefffb --- /dev/null +++ b/backend/src/payments/soroban/soroban-contract-version.ts @@ -0,0 +1,41 @@ +import { SorobanConfig } from './soroban-config'; + +export const PAYMENT_ESCROW_INTERFACE_VERSION = 2; +export const REVENUE_DISTRIBUTION_INTERFACE_VERSION = 2; + +export async function assertSorobanContractVersions( + config: Pick< + SorobanConfig, + 'contractId' | 'revenueDistributionContractId' | 'treasuryPublicKey' + >, + readVersion: ( + contractId: string, + sourceAccountPublicKey: string, + ) => Promise, +): Promise { + const contracts = [ + { + name: 'payment_escrow', + contractId: config.contractId, + expectedVersion: PAYMENT_ESCROW_INTERFACE_VERSION, + }, + { + name: 'revenue_distribution', + contractId: config.revenueDistributionContractId, + expectedVersion: REVENUE_DISTRIBUTION_INTERFACE_VERSION, + }, + ]; + + for (const contract of contracts) { + const actualVersion = await readVersion( + contract.contractId, + config.treasuryPublicKey, + ); + if (actualVersion !== contract.expectedVersion) { + throw new Error( + `${contract.name} interface version mismatch: expected ` + + `${contract.expectedVersion}, got ${actualVersion}`, + ); + } + } +} diff --git a/backend/src/payments/soroban/soroban-error-mapping.spec.ts b/backend/src/payments/soroban/soroban-error-mapping.spec.ts index 4c25f523..650f705a 100644 --- a/backend/src/payments/soroban/soroban-error-mapping.spec.ts +++ b/backend/src/payments/soroban/soroban-error-mapping.spec.ts @@ -1,14 +1,42 @@ import { mapSorobanError } from './soroban-error-mapping'; import { PaymentFailureReason } from '../enums/payment-failure-reason.enum'; import { + ContractError, EscrowSubmissionError, SimulationFailedError, } from './escrow-contract.client'; describe('mapSorobanError', () => { + it.each([ + [ContractError.NotFound, 'terminal'], + [ContractError.AlreadyResolved, 'already-succeeded'], + [ContractError.InvalidAmount, 'terminal'], + [ContractError.AlreadyExists, 'retry'], + [ContractError.ArithmeticOverflow, 'manual-review'], + [ContractError.AlreadyReleased, 'already-succeeded'], + [ContractError.AlreadyRefunded, 'already-succeeded'], + [ContractError.AlreadyInitialized, 'manual-review'], + [ContractError.NotInitialized, 'manual-review'], + [ContractError.Unauthorized, 'manual-review'], + [ContractError.Paused, 'retry'], + [ContractError.NoPendingAdmin, 'terminal'], + [ContractError.AmountExceedsEscrow, 'manual-review'], + [ContractError.NothingToRefund, 'terminal'], + [ContractError.TokenNotAllowed, 'manual-review'], + [ContractError.TransferShortfall, 'manual-review'], + ] as const)('maps contract error code %i to %s', (code, disposition) => { + expect( + mapSorobanError(new Error(`Error(Contract, #${code})`)), + ).toMatchObject({ + disposition, + alreadySucceeded: disposition === 'already-succeeded', + }); + }); + it('treats an "already released" guard as success, not a failure', () => { expect(mapSorobanError(new Error('escrow already released'))).toEqual({ alreadySucceeded: true, + disposition: 'already-succeeded', reason: null, }); }); @@ -16,6 +44,7 @@ describe('mapSorobanError', () => { it('treats an "already refunded" guard as success, not a failure', () => { expect(mapSorobanError(new Error('Error: already_refunded'))).toEqual({ alreadySucceeded: true, + disposition: 'already-succeeded', reason: null, }); }); @@ -23,6 +52,7 @@ describe('mapSorobanError', () => { it('maps a simulation failure to SIMULATION_FAILED', () => { expect(mapSorobanError(new SimulationFailedError('boom'))).toEqual({ alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.SIMULATION_FAILED, }); }); @@ -30,6 +60,7 @@ describe('mapSorobanError', () => { it('maps a sequence-number conflict to SEQUENCE_CONFLICT', () => { expect(mapSorobanError(new Error('txBAD_SEQ'))).toEqual({ alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.SEQUENCE_CONFLICT, }); }); @@ -37,6 +68,7 @@ describe('mapSorobanError', () => { it('maps an underpriced fee to INSUFFICIENT_FEE', () => { expect(mapSorobanError(new Error('txINSUFFICIENT_FEE'))).toEqual({ alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.INSUFFICIENT_FEE, }); }); @@ -44,6 +76,7 @@ describe('mapSorobanError', () => { it('maps an expired transaction to TRANSACTION_EXPIRED', () => { expect(mapSorobanError(new Error('txTOO_LATE: expired'))).toEqual({ alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.TRANSACTION_EXPIRED, }); }); @@ -53,6 +86,7 @@ describe('mapSorobanError', () => { mapSorobanError(new EscrowSubmissionError('{"code":"txFAILED"}')), ).toEqual({ alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.CONTRACT_REVERTED, }); }); @@ -60,6 +94,7 @@ describe('mapSorobanError', () => { it('treats an unrecognized error as indeterminate, never a definite failure', () => { expect(mapSorobanError(new Error('ECONNRESET'))).toEqual({ alreadySucceeded: false, + disposition: 'indeterminate', reason: null, }); }); @@ -67,6 +102,7 @@ describe('mapSorobanError', () => { it('treats a plain timeout as indeterminate', () => { expect(mapSorobanError(new Error('Request timed out'))).toEqual({ alreadySucceeded: false, + disposition: 'indeterminate', reason: null, }); }); diff --git a/backend/src/payments/soroban/soroban-error-mapping.ts b/backend/src/payments/soroban/soroban-error-mapping.ts index 3ee928aa..8bd54c87 100644 --- a/backend/src/payments/soroban/soroban-error-mapping.ts +++ b/backend/src/payments/soroban/soroban-error-mapping.ts @@ -1,9 +1,17 @@ import { PaymentFailureReason } from '../enums/payment-failure-reason.enum'; import { + ContractError, EscrowSubmissionError, SimulationFailedError, } from './escrow-contract.client'; +export type SorobanErrorDisposition = + | 'already-succeeded' + | 'retry' + | 'terminal' + | 'manual-review' + | 'indeterminate'; + export interface SorobanErrorMapping { /** * True when what looks like a failure is actually the contract's own @@ -11,75 +19,112 @@ export interface SorobanErrorMapping { * must be treated as success, not an error. */ alreadySucceeded: boolean; - /** - * Null means "indeterminate" (network error, RPC unreachable, timeout) - * — NOT a definite on-chain rejection. The caller must never fail a - * Payment on a null reason; the chain must be asked again later. - */ + disposition: SorobanErrorDisposition; + /** Null means the contract error should not immediately fail the payment. */ reason: PaymentFailureReason | null; } +const CONTRACT_ERROR_DISPOSITIONS: Record< + ContractError, + Exclude +> = { + [ContractError.NotFound]: 'terminal', + [ContractError.AlreadyResolved]: 'already-succeeded', + [ContractError.InvalidAmount]: 'terminal', + [ContractError.AlreadyExists]: 'retry', + [ContractError.ArithmeticOverflow]: 'manual-review', + [ContractError.AlreadyReleased]: 'already-succeeded', + [ContractError.AlreadyRefunded]: 'already-succeeded', + [ContractError.AlreadyInitialized]: 'manual-review', + [ContractError.NotInitialized]: 'manual-review', + [ContractError.Unauthorized]: 'manual-review', + [ContractError.Paused]: 'retry', + [ContractError.NoPendingAdmin]: 'terminal', + [ContractError.AmountExceedsEscrow]: 'manual-review', + [ContractError.NothingToRefund]: 'terminal', + [ContractError.TokenNotAllowed]: 'manual-review', + [ContractError.TransferShortfall]: 'manual-review', +}; + +function mapContractError(code: number): SorobanErrorMapping | undefined { + if (!Object.values(ContractError).includes(code)) { + return undefined; + } + const disposition = CONTRACT_ERROR_DISPOSITIONS[code as ContractError]; + return { + alreadySucceeded: disposition === 'already-succeeded', + disposition, + reason: + disposition === 'terminal' + ? PaymentFailureReason.CONTRACT_REVERTED + : null, + }; +} + /** * Maps a Soroban submission/simulation error to the failure taxonomy - * (issue #1574, feeding #1572's pattern). Pattern-matches on the error - * message because we don't have a live contract's exact error codes to - * match against structurally — once one exists, replace the regexes below - * with the contract's real typed error enum. + * (issue #1574, feeding #1572's pattern). */ export function mapSorobanError(error: unknown): SorobanErrorMapping { const message = error instanceof Error ? error.message : String(error); if (/already[_ ]?(released|refunded|resolved)/i.test(message)) { - return { alreadySucceeded: true, reason: null }; + return { + alreadySucceeded: true, + disposition: 'already-succeeded', + reason: null, + }; } - // Try to decode structured Error(Contract, #N) from Soroban - try { - // Look for patterns like Error(Contract, #2) or Error(Object, #2) - const contractErrorMatch = message.match(/Error\([^,]+,\s*#(\d+)\)/i); - if (contractErrorMatch) { - const code = parseInt(contractErrorMatch[1], 10); - // Already resolved = error code 2 for escrow contract - if (code === 2) { - return { alreadySucceeded: true, reason: null }; - } + const contractErrorMatch = message.match(/Error\([^,]+,\s*#(\d+)\)/i); + if (contractErrorMatch) { + const mapping = mapContractError(Number(contractErrorMatch[1])); + if (mapping) { + return mapping; } - } catch { - // ignore } if (error instanceof SimulationFailedError) { return { alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.SIMULATION_FAILED, }; } if (/bad_seq|sequence/i.test(message)) { return { alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.SEQUENCE_CONFLICT, }; } if (/insufficient.*fee|underpriced|txINSUFFICIENT_FEE/i.test(message)) { return { alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.INSUFFICIENT_FEE, }; } if (/expired|too_late|txTOO_LATE/i.test(message)) { return { alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.TRANSACTION_EXPIRED, }; } if (error instanceof EscrowSubmissionError || /contract/i.test(message)) { return { alreadySucceeded: false, + disposition: 'terminal', reason: PaymentFailureReason.CONTRACT_REVERTED, }; } // Unrecognized — most likely a network/timeout/RPC-unreachable error, // not a definite on-chain verdict. Never map this to a failure reason. - return { alreadySucceeded: false, reason: null }; + return { + alreadySucceeded: false, + disposition: 'indeterminate', + reason: null, + }; } diff --git a/backend/src/payments/soroban/soroban-rail-status.ts b/backend/src/payments/soroban/soroban-rail-status.ts new file mode 100644 index 00000000..468e5a19 --- /dev/null +++ b/backend/src/payments/soroban/soroban-rail-status.ts @@ -0,0 +1,27 @@ +import { Injectable } from '@nestjs/common'; + +export type SorobanRailHealth = + | { status: 'disabled' } + | { status: 'up' } + | { status: 'down'; detail: string }; + +@Injectable() +export class SorobanRailStatus { + private health: SorobanRailHealth = { status: 'disabled' }; + + markReady(): void { + this.health = { status: 'up' }; + } + + markDisabled(): void { + this.health = { status: 'disabled' }; + } + + markUnavailable(detail: string): void { + this.health = { status: 'down', detail }; + } + + getHealth(): SorobanRailHealth { + return { ...this.health }; + } +} diff --git a/contracts/CHANGELOG.md b/contracts/CHANGELOG.md index 6a6dd731..7926d881 100644 --- a/contracts/CHANGELOG.md +++ b/contracts/CHANGELOG.md @@ -5,6 +5,14 @@ backend and indexer integrators can track compatibility across releases (#1877). ## Unreleased +### Changed +- Route the legacy `payment_escrow::refund` entrypoint through the same + validation and transfer path as `refund_remaining`; new integrations should + use `refund_remaining`, which returns the amount refunded (#2169). +- Check both contract error enums against the shared TypeScript error codes + and map each escrow error code to an explicit backend disposition (#2166, + #2167). + ### Toolchain - Bump the contracts toolchain to Rust 1.98.1 and check in the resolved Cargo lockfile so CI can build the workspace with current transitive dependencies. diff --git a/contracts/README.md b/contracts/README.md index 1c2d395b..d2b3b568 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -49,15 +49,44 @@ backend maps that error to `NOT_FOUND`. ### Error Codes -| Code | Error | Meaning | -| ---- | --------------------- | ---------------------------------------------------- | -| `1` | `NotFound` | No escrow exists for the id | -| `2` | `AlreadyResolved` | The escrow is no longer `Locked` | -| `3` | `InvalidAmount` | Amount must be positive | -| `4` | `AlreadyExists` | An escrow with this id already exists | -| `5` | `ArithmeticOverflow` | Checked arithmetic failed | -| `20` | `AmountExceedsEscrow` | A partial release would exceed the locked amount | -| `21` | `NothingToRefund` | Nothing remains to refund | +`contracts/shared/error-codes.ts` exports separate enums for each contract; +`backend/src/payments/soroban/contract-error-codes.spec.ts` verifies every +numeric value against its Rust `Error` enum. + +| Code | `payment_escrow` error | Meaning | +| ---- | --------------------- | ------- | +| `1` | `NotFound` | No escrow exists for the id | +| `2` | `AlreadyResolved` | The escrow is no longer `Locked` | +| `3` | `InvalidAmount` | Amount must be positive | +| `4` | `AlreadyExists` | An escrow with this id already exists | +| `5` | `ArithmeticOverflow` | Checked arithmetic failed | +| `6` | `AlreadyReleased` | The escrow has already been released | +| `7` | `AlreadyRefunded` | The escrow has already been refunded | +| `10` | `AlreadyInitialized` | Initialization has already completed | +| `11` | `NotInitialized` | The contract has no admin yet | +| `12` | `Unauthorized` | Caller is not authorized | +| `13` | `Paused` | Creating escrows is paused | +| `14` | `NoPendingAdmin` | No admin transfer is pending | +| `20` | `AmountExceedsEscrow` | A partial release exceeds the locked amount | +| `21` | `NothingToRefund` | Nothing remains to refund | +| `22` | `TokenNotAllowed` | The token is not allow-listed | +| `23` | `TransferShortfall` | Token transfer did not deliver the exact amount | + +| Code | `revenue_distribution` error | Meaning | +| ---- | ----------------------------- | ------- | +| `1` | `InvalidBasisPoints` | Shares do not total 10,000 basis points | +| `2` | `NotConfigured` | No distribution configuration exists | +| `3` | `Unauthorized` | Caller is not authorized | +| `4` | `EmptyRecipients` | Recipient list is empty | +| `5` | `ArithmeticOverflow` | Checked arithmetic failed | +| `6` | `InvalidShare` | A recipient share is zero | +| `7` | `InvalidAmount` | Amount must be positive | +| `8` | `TokenNotAllowed` | The token is not allow-listed | +| `9` | `TooManyBeneficiaries` | Recipient limit exceeded | +| `10` | `AlreadyInitialized` | Initialization has already completed | +| `11` | `NotInitialized` | The contract has no admin yet | +| `12` | `NoPendingAdmin` | No admin transfer is pending | +| `13` | `DuplicateBeneficiary` | A recipient address is duplicated | ### Amount Units and Token Decimals @@ -86,11 +115,17 @@ These environment variables bind the backend to the on-chain contract | ------------------------------ | --------------------------------------------------------------------------- | | `SOROBAN_ENABLED` | `"true"` to activate the Stellar escrow rail; any other value disables it | | `STELLAR_ESCROW_CONTRACT_ID` | StrKey-encoded address of the deployed `payment_escrow` contract | +| `STELLAR_REVENUE_DISTRIBUTION_CONTRACT_ID` | StrKey-encoded address of the deployed `revenue_distribution` contract | | `STELLAR_NETWORK` | Stellar network passphrase (e.g. `Test SDF Network ; September 2015`) | | `STELLAR_RPC_URLS` | Comma-separated Soroban RPC endpoints | | `STELLAR_SECRET_KEY` | Treasury/operator secret key for signing releases and refunds | | `STELLAR_BENEFICIARY_ADDRESS` | Default beneficiary Stellar address | +When enabled, startup simulates `version()` on both configured contracts. A +version mismatch or failed check disables the Soroban rail and reports the +reason in `/health/dependencies`; update the deployed contracts or expected +interface versions before enabling it. + ### Escrow ID Derivation The backend derives escrow IDs as the **SHA-256 hash** of the `Payment` entity UUID, diff --git a/contracts/payment_escrow/src/lib.rs b/contracts/payment_escrow/src/lib.rs index 5802f63a..c0560689 100644 --- a/contracts/payment_escrow/src/lib.rs +++ b/contracts/payment_escrow/src/lib.rs @@ -106,6 +106,42 @@ pub enum Error { TransferShortfall = 23, } +fn refund_escrow( + env: &Env, + escrow_id: &BytesN<32>, + payer: &Address, +) -> Result { + let key = DataKey::Escrow(payer.clone(), escrow_id.clone()); + let mut escrow: Escrow = env + .storage() + .persistent() + .get(&key) + .ok_or(Error::NotFound)?; + + escrow.beneficiary.require_auth(); + + if escrow.state != EscrowState::Locked { + return Err(Error::AlreadyResolved); + } + let remaining = escrow + .amount + .checked_sub(escrow.released) + .ok_or(Error::ArithmeticOverflow)?; + if remaining <= 0 { + return Err(Error::NothingToRefund); + } + + token::Client::new(env, &escrow.token).transfer( + &env.current_contract_address(), + &escrow.payer, + &remaining, + ); + escrow.state = EscrowState::Refunded; + env.storage().persistent().set(&key, &escrow); + events::emit_refunded(env, escrow_id, &escrow.beneficiary); + Ok(remaining) +} + #[contract] pub struct PaymentEscrowContract; @@ -424,69 +460,15 @@ impl PaymentEscrowContract { /// escrow as `Refunded`. Only the beneficiary may authorise it. Returns /// the refunded amount. pub fn refund_remaining(env: Env, escrow_id: BytesN<32>, payer: Address) -> Result { - let key = DataKey::Escrow(payer, escrow_id.clone()); - let mut escrow: Escrow = env - .storage() - .persistent() - .get(&key) - .ok_or(Error::NotFound)?; - - escrow.beneficiary.require_auth(); - - if escrow.state != EscrowState::Locked { - return Err(Error::AlreadyResolved); - } - let remaining = escrow - .amount - .checked_sub(escrow.released) - .ok_or(Error::ArithmeticOverflow)?; - if remaining <= 0 { - return Err(Error::NothingToRefund); - } - - token::Client::new(&env, &escrow.token).transfer( - &env.current_contract_address(), - &escrow.payer, - &remaining, - ); - escrow.state = EscrowState::Refunded; - env.storage().persistent().set(&key, &escrow); - events::emit_refunded(&env, &escrow_id, &escrow.beneficiary); - Ok(remaining) + refund_escrow(&env, &escrow_id, &payer) } /// Refund escrowed funds back to the payer. Only the beneficiary — the /// party giving up their claim — may authorize a refund (CT-72). + /// Kept as a compatibility entrypoint; shares `refund_remaining`'s + /// validation and transfer behavior. pub fn refund(env: Env, escrow_id: BytesN<32>, payer: Address) -> Result<(), Error> { - let key = DataKey::Escrow(payer, escrow_id.clone()); - let mut escrow: Escrow = env - .storage() - .persistent() - .get(&key) - .ok_or(Error::NotFound)?; - - escrow.beneficiary.require_auth(); - - match escrow.state { - EscrowState::Locked => {} - EscrowState::Released => return Err(Error::AlreadyReleased), - EscrowState::Refunded => return Err(Error::AlreadyRefunded), - EscrowState::Completed => return Err(Error::AlreadyResolved), - } - - let remaining = escrow - .amount - .checked_sub(escrow.released) - .ok_or(Error::ArithmeticOverflow)?; - token::Client::new(&env, &escrow.token).transfer( - &env.current_contract_address(), - &escrow.payer, - &remaining, - ); - escrow.state = EscrowState::Refunded; - env.storage().persistent().set(&key, &escrow); - events::emit_refunded(&env, &escrow_id, &escrow.beneficiary); - Ok(()) + refund_escrow(&env, &escrow_id, &payer).map(|_| ()) } /// Return the full escrow record, including the token and held amount. @@ -638,7 +620,7 @@ mod escrow_test { ); assert_eq!( f.client.try_refund(&refunded, &f.payer), - Err(Ok(Error::AlreadyRefunded)) + Err(Ok(Error::AlreadyResolved)) ); assert_eq!( f.client.try_release(&refunded, &f.payer), @@ -646,7 +628,7 @@ mod escrow_test { ); assert_eq!( f.client.try_refund(&released, &f.payer), - Err(Ok(Error::AlreadyReleased)) + Err(Ok(Error::AlreadyResolved)) ); } @@ -771,6 +753,26 @@ mod partial_release_test { assert_eq!(client.refund_remaining(&id, &payer), 750); assert_eq!(client.get_status(&id, &payer), 3); } + + #[test] + fn both_refund_entrypoints_reject_a_zero_remainder_consistently() { + let (env, client, payer, ben, token) = setup(); + let id = BytesN::from_array(&env, &[4u8; 32]); + client.create(&id, &payer, &ben, &1_000, &token); + client.release_partial(&id, &payer, &1_000); + let payer_balance = token::Client::new(&env, &token).balance(&payer); + + assert_eq!( + client.try_refund(&id, &payer), + Err(Ok(Error::AlreadyResolved)) + ); + assert_eq!( + client.try_refund_remaining(&id, &payer), + Err(Ok(Error::AlreadyResolved)) + ); + assert_eq!(token::Client::new(&env, &token).balance(&payer), payer_balance); + assert_eq!(client.get_status(&id, &payer), 4); + } } #[cfg(test)] @@ -876,8 +878,8 @@ mod model_test { prop_assert!(r.is_ok()); model[i as usize] = Some((M::Refunded, a, rel)); } - Some((M::Released, _, _)) => prop_assert!(matches!(r, Err(Ok(Error::AlreadyReleased)))), - Some((M::Refunded, _, _)) => prop_assert!(matches!(r, Err(Ok(Error::AlreadyRefunded)))), + Some((M::Released, _, _)) => prop_assert!(matches!(r, Err(Ok(Error::AlreadyResolved)))), + Some((M::Refunded, _, _)) => prop_assert!(matches!(r, Err(Ok(Error::AlreadyResolved)))), Some(_) => prop_assert!(matches!(r, Err(Ok(Error::AlreadyResolved)))), } } diff --git a/contracts/shared/error-codes.ts b/contracts/shared/error-codes.ts index 473c72a8..e77752e6 100644 --- a/contracts/shared/error-codes.ts +++ b/contracts/shared/error-codes.ts @@ -1,28 +1,36 @@ -/** - * Shared contract `Error` enum codes (#1885). - * - * The Soroban contracts return numeric error codes. Exposing them here lets the - * backend client compare against named constants instead of magic numbers, and - * gives a single place to update when the contract error enum changes. - */ -export enum ContractError { - AlreadyExists = 1, - NotFound = 2, +/** Error codes returned by the payment_escrow contract. */ +export enum PaymentEscrowError { + NotFound = 1, + AlreadyResolved = 2, InvalidAmount = 3, - Unauthorized = 4, - InvalidState = 5, + AlreadyExists = 4, + ArithmeticOverflow = 5, + AlreadyReleased = 6, + AlreadyRefunded = 7, + AlreadyInitialized = 10, + NotInitialized = 11, + Unauthorized = 12, + Paused = 13, + NoPendingAdmin = 14, + AmountExceedsEscrow = 20, + NothingToRefund = 21, + TokenNotAllowed = 22, + TransferShortfall = 23, } -export const CONTRACT_ERROR_NAMES: Readonly> = - Object.freeze({ - [ContractError.AlreadyExists]: "AlreadyExists", - [ContractError.NotFound]: "NotFound", - [ContractError.InvalidAmount]: "InvalidAmount", - [ContractError.Unauthorized]: "Unauthorized", - [ContractError.InvalidState]: "InvalidState", - }); - -/** Human-readable name for a contract error code, if known. */ -export function contractErrorName(code: number): string { - return CONTRACT_ERROR_NAMES[code] ?? `Unknown(${code})`; +/** Error codes returned by the revenue_distribution contract. */ +export enum RevenueDistributionError { + InvalidBasisPoints = 1, + NotConfigured = 2, + Unauthorized = 3, + EmptyRecipients = 4, + ArithmeticOverflow = 5, + InvalidShare = 6, + InvalidAmount = 7, + TokenNotAllowed = 8, + TooManyBeneficiaries = 9, + AlreadyInitialized = 10, + NotInitialized = 11, + NoPendingAdmin = 12, + DuplicateBeneficiary = 13, }