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
19 changes: 10 additions & 9 deletions scripts/alert-failed-charges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

import { DatabaseSync } from "node:sqlite";
import { logger } from "./logger";

// ── Types ─────────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -62,15 +63,15 @@ async function sendWebhook(url: string, payload: AlertPayload): Promise<void> {
body: JSON.stringify(payload),
});
if (!response.ok) {
console.error(
logger.error(
`Webhook responded with HTTP ${response.status}: ${response.statusText}`
);
} else {
console.error(`Webhook delivered successfully (HTTP ${response.status})`);
logger.error(`Webhook delivered successfully (HTTP ${response.status})`);
}
} catch (err) {
// Log failure but do not crash — callers rely on non-zero exit only for fatal errors
console.error(`Webhook delivery failed: ${err}`);
logger.error(`Webhook delivery failed: ${err}`);
}
}

Expand All @@ -79,7 +80,7 @@ async function sendWebhook(url: string, payload: AlertPayload): Promise<void> {
async function main(): Promise<void> {
const webhookUrl = process.env.WEBHOOK_URL;
if (!webhookUrl) {
console.error("Error: WEBHOOK_URL environment variable is required.");
logger.error("Error: WEBHOOK_URL environment variable is required.");
process.exit(1);
}

Expand All @@ -91,7 +92,7 @@ async function main(): Promise<void> {
try {
db = new DatabaseSync(dbPath, { open: true });
} catch (err) {
console.error(`Failed to open database at ${dbPath}: ${err}`);
logger.error(`Failed to open database at ${dbPath}: ${err}`);
process.exit(1);
}

Expand Down Expand Up @@ -120,16 +121,16 @@ async function main(): Promise<void> {
};

if (failedCharges.length === 0) {
console.error("No failed charges found. No webhook sent.");
console.log(JSON.stringify(payload, null, 2));
logger.error("No failed charges found. No webhook sent.");
logger.info(JSON.stringify(payload, null, 2));
return;
}

console.log(JSON.stringify(payload, null, 2));
logger.info(JSON.stringify(payload, null, 2));
await sendWebhook(webhookUrl, payload);
}

main().catch((err) => {
console.error(`Fatal error: ${err}`);
logger.error(`Fatal error: ${err}`);
process.exit(1);
});
41 changes: 21 additions & 20 deletions scripts/check-allowances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { MultiEndpointServer } from "./rpc-client.js";
import {
import { logger } from "./logger";
Contract,
Networks,
TransactionBuilder,
Expand All @@ -24,8 +25,8 @@ const CONTRACT_ID = process.env.CONTRACT_ID || "";
const NETWORK_PASSPHRASE = (process.env.NETWORK_PASSPHRASE ?? Networks.TESTNET) as string;

if (!CONTRACT_ID) {
console.error("Error: CONTRACT_ID environment variable is required");
console.error(
logger.error("Error: CONTRACT_ID environment variable is required");
logger.error(
"Usage: CONTRACT_ID=your_contract_id tsx check-allowances.ts [--file subscribers.txt] [--json] [address1 address2 ...]"
);
process.exit(1);
Expand All @@ -49,13 +50,13 @@ async function parseAddressListFromFile(path: string): Promise<string[]> {
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith("#"));
} catch (err) {
console.error(`Error reading file ${path}: ${err}`);
logger.error(`Error reading file ${path}: ${err}`);
process.exit(1);
}
}

function showHelp(): void {
console.log(`
logger.info(`
Usage: tsx check-allowances.ts [options] [addresses...]

Options:
Expand Down Expand Up @@ -242,54 +243,54 @@ function printHumanReadable(results: AuditResult[]): void {
const noSub = results.filter((r) => r.error === "no_subscription");
const healthy = results.filter((r) => !r.atRisk && !r.error && r.active);

console.log(`\nAudited ${results.length} subscriber(s)\n`);
logger.info(`\nAudited ${results.length} subscriber(s)\n`);

if (noSub.length > 0) {
console.log(`${noSub.length} with no subscription:`);
logger.info(`${noSub.length} with no subscription:`);
for (const r of noSub) {
console.log(` ${r.address}`);
logger.info(` ${r.address}`);
}
console.log();
logger.info();
}

if (atRisk.length > 0) {
console.log(`${atRisk.length} at risk of failed charge:`);
logger.info(`${atRisk.length} at risk of failed charge:`);
const header =
" ADDRESS".padEnd(56) +
"AMOUNT".padStart(10) +
"ALLOWANCE".padStart(12) +
"GAP".padStart(10) +
"TOKEN".padStart(56);
console.log(header);
logger.info(header);
for (const r of atRisk) {
const line =
r.address.padEnd(56) +
stroopsToXlm(r.subscriptionAmount).padStart(10) +
stroopsToXlm(r.allowance).padStart(12) +
stroopsToXlm(r.gap).padStart(10) +
r.token.padStart(56);
console.log(` ${line}`);
logger.info(` ${line}`);
}
console.log();
logger.info();
}

if (healthy.length > 0) {
console.log(`${healthy.length} healthy:`);
logger.info(`${healthy.length} healthy:`);
for (const r of healthy) {
console.log(
logger.info(
` ${r.address.padEnd(56)} ${stroopsToXlm(r.subscriptionAmount).padStart(10)} ${stroopsToXlm(r.allowance).padStart(10)}`
);
}
console.log();
logger.info();
}

console.log(
logger.info(
`Summary: healthy=${healthy.length}, atRisk=${atRisk.length}, noSubscription=${noSub.length}`
);
}

function printJson(results: AuditResult[]): void {
console.log(JSON.stringify(results, null, 2));
logger.info(JSON.stringify(results, null, 2));
}

// ── Main ─────────────────────────────────────────────────────────────────────────
Expand All @@ -310,7 +311,7 @@ async function main(): Promise<void> {
} else if (arg === "--file") {
filePath = argv[++i];
} else if (arg.startsWith("-")) {
console.error(`Unknown option: ${arg}`);
logger.error(`Unknown option: ${arg}`);
showHelp();
} else {
addresses.push(arg);
Expand All @@ -328,7 +329,7 @@ async function main(): Promise<void> {
}

if (allAddresses.length === 0) {
console.error("No valid addresses provided.");
logger.error("No valid addresses provided.");
process.exit(1);
}

Expand All @@ -346,6 +347,6 @@ async function main(): Promise<void> {
}

main().catch((error) => {
console.error(`Fatal error: ${error}`);
logger.error(`Fatal error: ${error}`);
process.exit(1);
});
7 changes: 4 additions & 3 deletions scripts/daily-revenue-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/

import { DatabaseSync } from "node:sqlite";
import { logger } from "./logger";

// ── Types ─────────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -76,7 +77,7 @@ function main(): void {

// Validate date format
if (!/^\d{4}-\d{2}-\d{2}$/.test(targetDate)) {
console.error(`Invalid date format: ${targetDate}. Expected YYYY-MM-DD.`);
logger.error(`Invalid date format: ${targetDate}. Expected YYYY-MM-DD.`);
process.exit(1);
}

Expand All @@ -88,7 +89,7 @@ function main(): void {
try {
db = new DatabaseSync(dbPath, { open: true });
} catch (err) {
console.error(`Failed to open database at ${dbPath}: ${err}`);
logger.error(`Failed to open database at ${dbPath}: ${err}`);
process.exit(1);
}

Expand Down Expand Up @@ -142,7 +143,7 @@ function main(): void {
net_merchant_revenue: totalAmount - totalFees,
};

console.log(JSON.stringify(summary, null, 2));
logger.info(JSON.stringify(summary, null, 2));
}

main();
11 changes: 6 additions & 5 deletions scripts/export-merchant-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import { Contract, Networks, TransactionBuilder, BASE_FEE, nativeToScVal, Address, xdr } from "@stellar/stellar-sdk";
import { Server } from "@stellar/stellar-sdk/rpc";
import { logger } from "./logger";

const RPC_URL = process.env.VITE_RPC_URL ?? "https://soroban-testnet.stellar.org";
const NETWORK_PASSPHRASE = process.env.VITE_NETWORK_PASSPHRASE ?? Networks.TESTNET;
Expand Down Expand Up @@ -235,7 +236,7 @@ async function main() {
}

if (!["csv", "json", "ndjson"].includes(format)) {
console.error(`ERROR: Invalid format '${format}'. Supported formats: csv, json, ndjson`);
logger.error(`ERROR: Invalid format '${format}'. Supported formats: csv, json, ndjson`);
process.exit(1);
}

Expand All @@ -244,8 +245,8 @@ async function main() {
const parsedFields = fieldsStr.split(",").map((f) => f.trim());
const invalidFields = parsedFields.filter((f) => !VALID_FIELDS.includes(f as ValidField));
if (invalidFields.length > 0) {
console.error(`ERROR: Invalid field(s): ${invalidFields.join(", ")}.`);
console.error(`Valid fields are: ${VALID_FIELDS.join(", ")}`);
logger.error(`ERROR: Invalid field(s): ${invalidFields.join(", ")}.`);
logger.error(`Valid fields are: ${VALID_FIELDS.join(", ")}`);
process.exit(1);
}
selectedFields = parsedFields as ValidField[];
Expand Down Expand Up @@ -283,13 +284,13 @@ async function main() {
if (output) {
const fs = await import("fs/promises");
await fs.writeFile(output, formattedOutput, "utf-8");
console.log(`Report written to ${output}`);
logger.info(`Report written to ${output}`);
} else {
process.stdout.write(formattedOutput);
}
}

main().catch((err) => {
console.error("Export report failed:", err instanceof Error ? err.message : err);
logger.error("Export report failed:", err instanceof Error ? err.message : err);
process.exit(1);
});
5 changes: 3 additions & 2 deletions scripts/fee-revenue-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import { DatabaseSync } from "node:sqlite";
import { writeFileSync } from "node:fs";
import { logger } from "./logger";

interface EventRow {
data: string;
Expand Down Expand Up @@ -44,7 +45,7 @@ function toDateStr(ts: number): string {

function main() {
const dbPath = getArg("--db");
if (!dbPath) { console.error("--db <path> required"); process.exit(1); }
if (!dbPath) { logger.error("--db <path> required"); process.exit(1); }

const db = new DatabaseSync(dbPath, { open: true });

Expand Down Expand Up @@ -86,7 +87,7 @@ function main() {

const out = getArg("--out");
const json = JSON.stringify(report, null, 2);
if (out) { writeFileSync(out, json); console.log(`Wrote report to ${out}`); }
if (out) { writeFileSync(out, json); logger.info(`Wrote report to ${out}`); }
else process.stdout.write(json + "\n");
}

Expand Down
5 changes: 3 additions & 2 deletions scripts/health-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import { Contract, Networks, TransactionBuilder, BASE_FEE, Address } from "@stellar/stellar-sdk";
import { MultiEndpointServer } from "./rpc-client.js";
import { logger } from "./logger";

// ── Configuration ────────────────────────────────────────────────────────────

Expand All @@ -44,9 +45,9 @@ function timestamp(): string {
function log(status: "healthy" | "unhealthy", detail?: string): void {
const line = `${timestamp()} contract=${CONTRACT_ID || "NOT_SET"} status=${status}`;
if (detail) {
console.log(`${line} detail=${detail}`);
logger.info(`${line} detail=${detail}`);
} else {
console.log(line);
logger.info(line);
}
}

Expand Down
Loading
Loading