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
1 change: 1 addition & 0 deletions coordinator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"fixtures:remove": "tsx src/remove-fixtures.ts"
},
"dependencies": {
"@oversync/sdk": "workspace:*",
"@stellar/stellar-sdk": "^13.0.0",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
Expand Down
21 changes: 1 addition & 20 deletions coordinator/src/persistence/orders-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -595,24 +595,5 @@ function deriveTransitions(status: OrderStatus): string[] {
default:
return [status];
}

async getMetrics(): Promise<OrderMetrics> {
const byStatus = await this.all<{ status: string; count: number }>(this.metricsByStatus);
const totalRow = await this.get<{ count: number }>(this.metricsTotal);
const lastUpdatedRow = await this.get<{ ts: number | null }>(this.metricsLastUpdated);

const statusMap: Record<string, number> = {};
for (const row of byStatus) {
statusMap[row.status] = Number(row.count);
}

return {
totalOrders: Number(totalRow?.count ?? 0),
byStatus: statusMap,
completedOrders: statusMap["completed"] ?? 0,
refundedOrders: statusMap["refunded"] ?? 0,
staleExpiredOrders: (statusMap["expired"] ?? 0) + (statusMap["failed"] ?? 0),
lastUpdatedTimestamp: lastUpdatedRow?.ts != null ? Number(lastUpdatedRow.ts) : null
};
}
}

37 changes: 37 additions & 0 deletions coordinator/src/server/routes/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { z } from "zod";
import type { OrderRow, OrderSnapshot } from "../../persistence/orders-repo.js";
import { announceSchema, OrderService, OrderValidationError } from "../../services/order-service.js";
import { encodeCursor, decodeCursor } from "./cursor-utils.js";
import { computeRefundEligibility } from "@oversync/sdk";

function serialiseOrder(order: OrderRow | null) {
if (!order) return null;
Expand All @@ -11,6 +12,11 @@ function serialiseOrder(order: OrderRow | null) {
direction: order.direction,
status: order.status,
hashlock: order.hashlock,
refundEligibility: computeRefundEligibility({
status: order.status,
timelock: order.srcTimelock,
direction: order.direction,
}),
src: {
chain: order.srcChain,
address: order.srcAddress,
Expand Down Expand Up @@ -130,6 +136,37 @@ export function ordersRoutes(orders: OrderService): Router {
}
});

router.get("/orders/:id/transitions", async (req, res, next) => {
const id = req.params.id;
try {
const transitions = await orders.getTransitions(id);
if (!transitions.length) {
const order = await orders.get(id);
if (!order) {
res.status(404).json({ error: "not_found" });
return;
}
}
res.json({ transitions });
} catch (err) {
next(err);
}
});

router.get("/orders/:id/refund-eligibility", async (req, res, next) => {
const id = req.params.id;
try {
const eligibility = await orders.getRefundEligibility(id);
if (eligibility.reasonCode === "unknown_order") {
res.status(404).json({ error: "not_found", refundEligibility: eligibility });
return;
}
res.json({ id, refundEligibility: eligibility });
} catch (err) {
next(err);
}
});

// Parameterized routes come AFTER specific routes
router.get("/orders/:id", async (req, res, next) => {
const id = req.params.id;
Expand Down
15 changes: 15 additions & 0 deletions coordinator/src/services/order-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { ordersTotal } from "../metrics.js";
import { QuoteService, QuoteExpiredError, QuoteNotFoundError } from "./quote-service.js";
import { loadConfig } from "../config.js";
import { validateTimelockOrdering } from "../utils/timelock-validator.js";
import { computeRefundEligibility, type RefundEligibilityResult } from "@oversync/sdk";


const HEX32 = /^0x[0-9a-fA-F]{64}$/;
const HEX_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
Expand Down Expand Up @@ -147,6 +149,19 @@ export class OrderService {
return this.repo.getTransitions(publicId);
}

async getRefundEligibility(publicId: string, nowUnixSeconds?: number): Promise<RefundEligibilityResult> {
const order = await this.repo.findByPublicId(publicId);
if (!order) {
return computeRefundEligibility({ status: null, nowUnixSeconds });
}
return computeRefundEligibility({
status: order.status,
timelock: order.srcTimelock,
direction: order.direction,
nowUnixSeconds,
});
}

history(address: string, limit?: number, offset?: number): Promise<OrderRow[]> {
return this.repo.findByAddress(address, limit, offset);
}
Expand Down
8 changes: 4 additions & 4 deletions coordinator/test/order-transitions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@ describe("OrderService transition summaries", () => {
orderId: "src-1",
txHash: "0xsrc",
blockNumber: 1,
timelock: 1000
timelock: 5000
});
await orders.recordDstLock({
publicId: order.publicId,
orderId: "dst-1",
txHash: "0xdst",
blockNumber: 2,
timelock: 2000,
timelock: 1000,
resolver: null
});
await orders.recordSecret(order.publicId, PREIMAGE, "0xsecret");
Expand Down Expand Up @@ -144,14 +144,14 @@ describe("GET /api/orders/:id/transitions", () => {
orderId: "src-3",
txHash: "0xsrc3",
blockNumber: 4,
timelock: 4000
timelock: 5000
});
await orders.recordDstLock({
publicId: order.publicId,
orderId: "dst-3",
txHash: "0xdst3",
blockNumber: 5,
timelock: 5000,
timelock: 1000,
resolver: null
});
await orders.recordSecret(order.publicId, PREIMAGE, "0xsecret3");
Expand Down
124 changes: 124 additions & 0 deletions coordinator/test/refund-eligibility-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { describe, it, expect, vi } from "vitest";
import request from "supertest";
import pino from "pino";
import { createApp } from "../src/server/app.js";
import type { OrderService } from "../src/services/order-service.js";
import type { SecretService } from "../src/services/secret-service.js";
import type { QuoteService } from "../src/services/quote-service.js";
import type { OrderRow } from "../src/persistence/orders-repo.js";

const log = pino({ level: "silent" });

const SAMPLE_ORDER: OrderRow = {
id: 1,
publicId: "order-123",
direction: "eth_to_xlm",
status: "src_locked",
hashlock: ("0x" + "a".repeat(64)) as `0x${string}`,
srcChain: "ethereum",
srcAddress: "0x1111111111111111111111111111111111111111",
srcAsset: "native",
srcAmount: "1000000000000000000",
srcSafetyDeposit: "0",
srcOrderId: "1",
srcLockTx: "0xlock",
srcLockBlock: 100,
srcTimelock: Math.floor(Date.now() / 1000) - 500, // Expired
dstChain: "stellar",
dstAddress: "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB422",
dstAsset: "native",
dstAmount: "100000000",
dstOrderId: null,
dstLockTx: null,
dstLockBlock: null,
dstTimelock: null,
preimage: null,
secretRevealedTx: null,
resolverAddress: null,
fixture: false,
createdAt: 1700000000,
updatedAt: 1700000100,
};

function buildApp() {
const orders = {
announce: vi.fn(),
get: vi.fn().mockImplementation(async (id: string) => {
if (id === "order-123") return SAMPLE_ORDER;
return null;
}),
getRefundEligibility: vi.fn().mockImplementation(async (id: string) => {
if (id === "order-123") {
return {
eligible: true,
reasonCode: "eligible",
reason: "eligible",
timeRemainingSeconds: 0,
};
}
return {
eligible: false,
reasonCode: "unknown_order",
reason: "unknown order",
timeRemainingSeconds: 0,
};
}),
history: vi.fn().mockResolvedValue([SAMPLE_ORDER]),
recordSrcLock: vi.fn(),
recordDstLock: vi.fn(),
} as unknown as OrderService;

const secrets = { reveal: vi.fn(), get: vi.fn() } as unknown as SecretService;
const quotes = {} as unknown as QuoteService;

const app = createApp({ log, corsOrigins: ["*"], maxRequestBodyBytes: 1024 * 1024, orders, secrets, quotes });
return { app, orders };
}

describe("GET /api/orders/:id/refund-eligibility", () => {
it("returns 200 with refund eligibility details for a valid order", async () => {
const { app } = buildApp();

const res = await request(app).get("/api/orders/order-123/refund-eligibility");

expect(res.status).toBe(200);
expect(res.body).toEqual({
id: "order-123",
refundEligibility: {
eligible: true,
reasonCode: "eligible",
reason: "eligible",
timeRemainingSeconds: 0,
},
});
});

it("returns 404 with unknown_order reason code for an unknown order", async () => {
const { app } = buildApp();

const res = await request(app).get("/api/orders/non-existent/refund-eligibility");

expect(res.status).toBe(404);
expect(res.body.error).toBe("not_found");
expect(res.body.refundEligibility).toEqual({
eligible: false,
reasonCode: "unknown_order",
reason: "unknown order",
timeRemainingSeconds: 0,
});
});

it("includes refundEligibility in GET /api/orders/history response", async () => {
const { app } = buildApp();

const res = await request(app).get("/api/orders/history?address=0x1111111111111111111111111111111111111111");

expect(res.status).toBe(200);
expect(res.body.transactions).toHaveLength(1);
const tx = res.body.transactions[0];
expect(tx.id).toBe("order-123");
expect(tx.refundEligibility).toBeDefined();
expect(tx.refundEligibility.eligible).toBe(true);
expect(tx.refundEligibility.reasonCode).toBe("eligible");
});
});
8 changes: 4 additions & 4 deletions coordinator/test/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,14 @@ describe("OrderService.getSnapshots", () => {
orderId: "0",
txHash: "0xsrctx",
blockNumber: 100,
timelock: 200
timelock: 3000
});
await orders.recordDstLock({
publicId: order.publicId,
orderId: "0",
txHash: "0xdsttx",
blockNumber: 200,
timelock: 300,
timelock: 1000,
resolver: null
});
await orders.recordSecret(order.publicId, "0x" + "a".repeat(64), "0xsecretx");
Expand Down Expand Up @@ -136,14 +136,14 @@ describe("OrderService.getSnapshots", () => {
orderId: "2",
txHash: "0xsrcrtx",
blockNumber: 50,
timelock: 150
timelock: 3000
});
await orders.recordDstLock({
publicId: order.publicId,
orderId: "2",
txHash: "0xdstrtx",
blockNumber: 100,
timelock: 200,
timelock: 1000,
resolver: null
});
await orders.markStatus(order.publicId, "refunded");
Expand Down
9 changes: 8 additions & 1 deletion frontend/src/components/TransactionHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { classifyOrderFreshness } from '../lib/orderFreshness';
import { buildHtlcReceipt } from '../lib/parseHtlcReceipt';
import type { Address } from 'viem';
import HtlcTimeline from './HtlcTimeline';
import { computeRefundEligibility, type RefundEligibilityResult } from '@oversync/sdk';

interface Transaction {
id: string;
Expand Down Expand Up @@ -40,6 +41,7 @@ interface Transaction {
autoRefundFailed?: boolean;
autoRefundError?: string;
networkMode?: 'mainnet' | 'testnet';
refundEligibility?: RefundEligibilityResult;
}

interface TransactionHistoryProps {
Expand Down Expand Up @@ -133,7 +135,12 @@ function mapCoordinatorOrderToTransaction(order: any): Transaction {
refundTxHash: order.status === 'refunded' ? order.secret?.revealedTx : undefined,
refundNetwork: isEthToXlm ? 'ethereum' : 'stellar',
refundedAt: order.status === 'refunded' ? order.updatedAt * 1000 : undefined,
networkMode: isTestnetMode ? 'testnet' : 'mainnet'
networkMode: isTestnetMode ? 'testnet' : 'mainnet',
refundEligibility: order.refundEligibility ?? computeRefundEligibility({
status: order.status,
timelock: order.src?.timelock,
direction: order.direction,
}),
};
}

Expand Down
8 changes: 8 additions & 0 deletions packages/sdk/src/state-machine/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,11 @@ export {
type RefundTimelineInput,
type RefundTimelineResult,
} from "./refund-timeline.js";

export {
computeRefundEligibility,
type RefundEligibilityReasonCode,
type RefundEligibilityInput,
type RefundEligibilityResult,
} from "./refund-eligibility.js";

Loading