Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 40 additions & 0 deletions backend/src/app.service.spec.ts
Original file line number Diff line number Diff line change
@@ -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',
},
},
});
});
});
13 changes: 10 additions & 3 deletions backend/src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,42 @@ 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<{
status: 'ok' | 'degraded' | 'unhealthy';
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<{
Expand Down
48 changes: 46 additions & 2 deletions backend/src/payments/payments.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<unknown>(
'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,
Expand Down Expand Up @@ -167,6 +210,7 @@ import {
PaymentConfirmationService,
ReconciliationService,
EXTERNAL_PAYOUT_RAIL,
SorobanRailStatus,
],
})
export class PaymentsModule implements OnModuleInit {
Expand Down
6 changes: 5 additions & 1 deletion backend/src/payments/soroban/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.**
Expand All @@ -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

Expand Down
54 changes: 54 additions & 0 deletions backend/src/payments/soroban/contract-error-codes.spec.ts
Original file line number Diff line number Diff line change
@@ -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\}/));
});
});
25 changes: 24 additions & 1 deletion backend/src/payments/soroban/escrow-contract.client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down Expand Up @@ -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();
Expand Down
34 changes: 21 additions & 13 deletions backend/src/payments/soroban/escrow-contract.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -160,6 +148,26 @@ export class EscrowContractClient {
});
}

async getContractVersion(sourceAccountPublicKey: string): Promise<number> {
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:
Expand Down
32 changes: 22 additions & 10 deletions backend/src/payments/soroban/escrow-submission.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,27 +201,35 @@ export class EscrowSubmissionProcessor {
): Promise<void> {
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(
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading