Skip to content
Open
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
4 changes: 4 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,6 @@
"ts-jest": "^29.4.12",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.3.3"
"typescript": "^5.9.3"
}
}
32 changes: 15 additions & 17 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export function createApp({
cors({
origin: http?.corsAllowedOrigins ?? true,
credentials: http?.corsAllowCredentials ?? false,
}),
})
);

if (kycService) {
Expand All @@ -122,28 +122,26 @@ export function createApp({

// FORCE RATE LIMITER (tests depend on it)
if (http?.rateLimit?.enabled !== false) {
applyRateLimiters(app, appLogger, {
global: http?.rateLimit
? {
windowMs: http.rateLimit.windowMs ?? 60_000,
max: http.rateLimit.max ?? 100,
}
: undefined,
});
}
applyRateLimiters(app, appLogger, {
global: http?.rateLimit
? {
windowMs: http.rateLimit.windowMs ?? 60_000,
max: http.rateLimit.max ?? 100,
}
: undefined,
});
}
app.use(
createRequestObservabilityMiddleware({
logger: appLogger,
metricsEnabled,
metricsRegistry,
}),
})
);

app.get("/health", (req, res) => {
const requestId =
(req.headers["x-request-id"] as string) ||
(req as RequestWithId).requestId ||
"unknown";
(req.headers["x-request-id"] as string) || (req as RequestWithId).requestId || "unknown";

res.setHeader("x-request-id", requestId);

Expand Down Expand Up @@ -212,7 +210,7 @@ export function createApp({
authService,
contractGuardService,
contractId: pauseGuardContractId,
}),
})
);
}

Expand All @@ -223,7 +221,7 @@ export function createApp({
settlementService,
contractGuardService,
contractId: pauseGuardContractId,
}),
})
);
}

Expand All @@ -234,7 +232,7 @@ export function createApp({
if (config?.admin?.ipWhitelist?.length) {
app.use(
"/api/v1/admin",
createAdminRouter({ dataSource, allowedCidrs: config.admin.ipWhitelist, invoiceService }),
createAdminRouter({ dataSource, allowedCidrs: config.admin.ipWhitelist, invoiceService })
);
}

Expand Down
4 changes: 3 additions & 1 deletion src/config/data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export async function initializeDataSource(): Promise<void> {
}
} catch (error) {
logger.error("Failed to initialize DataSource", { error });
throw new Error(`DataSource initialization failed: ${error instanceof Error ? error.message : String(error)}`);
throw new Error(
`DataSource initialization failed: ${error instanceof Error ? error.message : String(error)}`
);
}
}
16 changes: 13 additions & 3 deletions src/config/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ let lastPoolErrorLog = 0;
* Logs a warn when utilisation exceeds 80% and error at 100%.
* Each log is emitted at most once per 30 seconds.
*/
export function startPoolMonitor(getPool: () => { totalCount: number; idleCount: number; waitingCount: number } | null): void {
export function startPoolMonitor(
getPool: () => { totalCount: number; idleCount: number; waitingCount: number } | null
): void {
setInterval(() => {
const pool = getPool();
if (!pool) return;
Expand Down Expand Up @@ -85,9 +87,17 @@ if (!isDevelopment) {
startPoolMonitor(() => {
try {
// TypeORM exposes the underlying pg pool via driver.master/slave
const pool = (dataSource.driver as unknown as { master?: { totalCount: number; idleCount: number; waitingCount: number } })?.master;
const pool = (
dataSource.driver as unknown as {
master?: { totalCount: number; idleCount: number; waitingCount: number };
}
)?.master;
if (pool && typeof pool.totalCount === "number") {
return { totalCount: pool.totalCount, idleCount: pool.idleCount, waitingCount: pool.waitingCount };
return {
totalCount: pool.totalCount,
idleCount: pool.idleCount,
waitingCount: pool.waitingCount,
};
}
} catch {
// Ignore — pool not yet initialised
Expand Down
14 changes: 5 additions & 9 deletions src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ export interface AppConfig {
};
}


// ---------------- DEFAULTS ----------------

const DEFAULT_PORT = 3000;
Expand Down Expand Up @@ -97,7 +96,6 @@ const DEFAULT_IPFS_ALLOWED_MIME_TYPES = [
const DEFAULT_IPFS_UPLOAD_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000;
const DEFAULT_IPFS_UPLOAD_RATE_LIMIT_MAX_UPLOADS = 10;


// ---------------- HELPERS ----------------

function parsePort(value?: string): number {
Expand Down Expand Up @@ -130,7 +128,10 @@ function parseBoolean(value: string | undefined, fallback: boolean, name: string

function parseCsv(value?: string): string[] {
if (!value) return [];
return value.split(",").map(v => v.trim()).filter(Boolean);
return value
.split(",")
.map((v) => v.trim())
.filter(Boolean);
}

function parseTrustProxy(value?: string): boolean | number | string {
Expand Down Expand Up @@ -166,7 +167,6 @@ function requireString(value: string | undefined, name: string): string {
return value;
}


// ---------------- MAIN CONFIG ----------------

export function getConfig(): AppConfig {
Expand Down Expand Up @@ -216,11 +216,7 @@ export function getConfig(): AppConfig {
60000,
"RATE_LIMIT_WINDOW_MS"
),
max: parsePositiveInteger(
process.env.RATE_LIMIT_MAX,
100,
"RATE_LIMIT_MAX"
),
max: parsePositiveInteger(process.env.RATE_LIMIT_MAX, 100, "RATE_LIMIT_MAX"),
},
},

Expand Down
29 changes: 8 additions & 21 deletions src/config/stellar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,25 +52,21 @@ export function getSorobanConfig(): SorobanConfig {
"https://soroban-testnet.stellar.org";

const networkPassphrase =
process.env.STELLAR_NETWORK_PASSPHRASE ??
"Test SDF Network ; September 2015";
process.env.STELLAR_NETWORK_PASSPHRASE ?? "Test SDF Network ; September 2015";

const escrowContractId =
process.env.SOROBAN_ESCROW_CONTRACT_ID ??
process.env.ESCROW_CONTRACT_ID ??
"CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM";

const tokenContractId =
process.env.SOROBAN_TOKEN_CONTRACT_ID ??
process.env.TOKEN_CONTRACT_ID;
const tokenContractId = process.env.SOROBAN_TOKEN_CONTRACT_ID ?? process.env.TOKEN_CONTRACT_ID;

const paymentDistributorContractId =
process.env.SOROBAN_PAYMENT_DISTRIBUTOR_CONTRACT_ID ??
process.env.PAYMENT_DISTRIBUTOR_CONTRACT_ID;

const platformSecretKey =
process.env.STELLAR_PLATFORM_SECRET_KEY ??
process.env.PLATFORM_SECRET_KEY;
process.env.STELLAR_PLATFORM_SECRET_KEY ?? process.env.PLATFORM_SECRET_KEY;
const platformFeeRecipient = process.env.PLATFORM_FEE_RECIPIENT;
const platformFeeBps = Number(process.env.PLATFORM_FEE_BPS ?? "0");
if (!Number.isInteger(platformFeeBps) || platformFeeBps < 0 || platformFeeBps > 10_000) {
Expand All @@ -92,29 +88,20 @@ export function getSorobanConfig(): SorobanConfig {
export function getPaymentVerificationConfig(): PaymentVerificationConfig {
return {
horizonUrl: requireEnv(process.env.STELLAR_HORIZON_URL, "STELLAR_HORIZON_URL"),
usdcAssetCode: requireEnv(
process.env.STELLAR_USDC_ASSET_CODE,
"STELLAR_USDC_ASSET_CODE",
),
usdcAssetIssuer: requireEnv(
process.env.STELLAR_USDC_ASSET_ISSUER,
"STELLAR_USDC_ASSET_ISSUER",
),
escrowPublicKey: requireEnv(
process.env.STELLAR_ESCROW_PUBLIC_KEY,
"STELLAR_ESCROW_PUBLIC_KEY",
),
usdcAssetCode: requireEnv(process.env.STELLAR_USDC_ASSET_CODE, "STELLAR_USDC_ASSET_CODE"),
usdcAssetIssuer: requireEnv(process.env.STELLAR_USDC_ASSET_ISSUER, "STELLAR_USDC_ASSET_ISSUER"),
escrowPublicKey: requireEnv(process.env.STELLAR_ESCROW_PUBLIC_KEY, "STELLAR_ESCROW_PUBLIC_KEY"),
allowedAmountDelta:
process.env.STELLAR_VERIFY_ALLOWED_AMOUNT_DELTA ?? DEFAULT_ALLOWED_AMOUNT_DELTA,
retryAttempts: parsePositiveInteger(
process.env.STELLAR_VERIFY_RETRY_ATTEMPTS,
DEFAULT_RETRY_ATTEMPTS,
"STELLAR_VERIFY_RETRY_ATTEMPTS",
"STELLAR_VERIFY_RETRY_ATTEMPTS"
),
retryBaseDelayMs: parsePositiveInteger(
process.env.STELLAR_VERIFY_RETRY_BASE_DELAY_MS,
DEFAULT_RETRY_BASE_DELAY_MS,
"STELLAR_VERIFY_RETRY_BASE_DELAY_MS",
"STELLAR_VERIFY_RETRY_BASE_DELAY_MS"
),
};
}
10 changes: 4 additions & 6 deletions src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ import type { AuthenticatedRequest } from "../types/auth";
export function createAuthController(authService: AuthService) {
return {
// Request challenge for signing
challenge: async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
challenge: async (req: AuthenticatedRequest, res: Response): Promise<void> => {
const challenge = await authService.createChallenge(req.body.publicKey);
res.status(201).json({ challenge });
},
Expand All @@ -20,7 +17,8 @@ export function createAuthController(authService: AuthService) {
res: Response
): Promise<void> => {
const forwarded = req.headers["x-forwarded-for"];
const ipAddress = (Array.isArray(forwarded) ? forwarded[0] : forwarded?.split(",")[0]?.trim()) ?? req.ip;
const ipAddress =
(Array.isArray(forwarded) ? forwarded[0] : forwarded?.split(",")[0]?.trim()) ?? req.ip;
const session = await authService.verifyChallenge({ ...req.body, ipAddress });
res.status(200).json(session);
},
Expand All @@ -36,4 +34,4 @@ export function createAuthController(authService: AuthService) {
res.status(200).json({ user });
},
};
}
}
9 changes: 6 additions & 3 deletions src/controllers/investment.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ export class InvestmentController {
data: investment,
});
} catch (err: unknown) {
const statusCode = (err as { status?: number }).status || (err as { statusCode?: number }).statusCode || 400;
const statusCode =
(err as { status?: number }).status || (err as { statusCode?: number }).statusCode || 400;
return res.status(statusCode).json({
error: {
code: (err as { code?: string }).code || "INTERNAL_ERROR",
Expand All @@ -63,7 +64,8 @@ export class InvestmentController {
data: dashboard,
});
} catch (err: unknown) {
const statusCode = (err as { status?: number }).status || (err as { statusCode?: number }).statusCode || 500;
const statusCode =
(err as { status?: number }).status || (err as { statusCode?: number }).statusCode || 500;
return res.status(statusCode).json({
error: {
code: (err as { code?: string }).code || "INTERNAL_ERROR",
Expand All @@ -87,7 +89,8 @@ export class InvestmentController {
data: analytics,
});
} catch (err: unknown) {
const statusCode = (err as { status?: number }).status || (err as { statusCode?: number }).statusCode || 500;
const statusCode =
(err as { status?: number }).status || (err as { statusCode?: number }).statusCode || 500;
return res.status(statusCode).json({
error: {
code: (err as { code?: string }).code || "INTERNAL_ERROR",
Expand Down
Loading