From a64649b19f04fdc6cde402d17d6e203b5f16f47e Mon Sep 17 00:00:00 2001 From: Userhorlie <99200015+Userhorlie@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:43:07 +0100 Subject: [PATCH] Refresh public tracking and remove dead contract artifacts Closes #1850 Closes #1851 Closes #1852 Closes #1853 --- .github/workflows/ci.yml | 13 ++ contracts/escrow/README.md | 1 - contracts/escrow/escrow-dispute.test.ts | 70 -------- contracts/escrow/src/admin.rs | 174 ------------------- contracts/escrow/src/audit.md | 141 --------------- contracts/identity/carrier-whitelist.ts | 53 ------ contracts/shipment/shipment-metadata.ts | 48 ----- contracts/shipment/shipment-storage.ts | 52 ------ frontend/app/track/[trackingNumber]/page.tsx | 87 ++++++++-- 9 files changed, 87 insertions(+), 552 deletions(-) delete mode 100644 contracts/escrow/escrow-dispute.test.ts delete mode 100644 contracts/escrow/src/admin.rs delete mode 100644 contracts/escrow/src/audit.md delete mode 100644 contracts/identity/carrier-whitelist.ts delete mode 100644 contracts/shipment/shipment-metadata.ts delete mode 100644 contracts/shipment/shipment-storage.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c777fba84..6d123973d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -177,6 +177,19 @@ jobs: continue-on-error: true # non-blocking until pre-existing findings are triaged run: cargo audit + - name: Reject stray source files in contract crates + # Only Rust sources belong in a contract crate root; loose TS/JS files + # look like delivered on-chain features while compiling to nothing. + run: | + stray=$(find . -mindepth 2 -maxdepth 2 -type f \ + \( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' -o -name '*.py' -o -name '*.go' \) \ + ! -path './scripts/*') + if [ -n "$stray" ]; then + echo "Non-Rust source files found inside contract crates:" + echo "$stray" + exit 1 + fi + - name: Check formatting run: cargo fmt --all -- --check diff --git a/contracts/escrow/README.md b/contracts/escrow/README.md index 9fdc5511a..e0d529fe9 100644 --- a/contracts/escrow/README.md +++ b/contracts/escrow/README.md @@ -81,4 +81,3 @@ Actions: `funded`, `released`, `refunded`, `disputed`, `resolved`. - Pausing stops funding and settlement alike, so a paused contract holds funds in place until the admin unpauses (see [`SECURITY-MODEL.md`](../SECURITY-MODEL.md)). -- Historical notes on specific audits live in [`audit.md`](audit.md). diff --git a/contracts/escrow/escrow-dispute.test.ts b/contracts/escrow/escrow-dispute.test.ts deleted file mode 100644 index daa2e294c..000000000 --- a/contracts/escrow/escrow-dispute.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -// CT-26: Unit tests for Escrow dispute and resolution flow - -type EscrowStatus = "ACTIVE" | "DISPUTED" | "RELEASED" | "REFUNDED"; - -interface Escrow { - id: string; - shipper: string; - carrier: string; - admin: string; - amount: number; - fee: number; - status: EscrowStatus; -} - -function raiseDispute(escrow: Escrow, caller: string): void { - if (escrow.status !== "ACTIVE") throw new Error("Can only dispute an active escrow"); - if (caller !== escrow.shipper && caller !== escrow.carrier) throw new Error("Unauthorized"); - escrow.status = "DISPUTED"; -} - -function resolveDispute(escrow: Escrow, caller: string, releaseToCarrier: boolean): void { - if (caller !== escrow.admin) throw new Error("Only admin can resolve disputes"); - if (escrow.status !== "DISPUTED") throw new Error("Escrow is not disputed"); - escrow.status = releaseToCarrier ? "RELEASED" : "REFUNDED"; -} - -function makeEscrow(): Escrow { - return { id: "e1", shipper: "alice", carrier: "bob", admin: "admin", amount: 100, fee: 5, status: "ACTIVE" }; -} - -// --- Tests --- - -function test(name: string, fn: () => void) { - try { fn(); console.log(`✓ ${name}`); } - catch (e) { console.error(`✗ ${name}: ${(e as Error).message}`); } -} - -test("raise_dispute transitions escrow to Disputed", () => { - const e = makeEscrow(); - raiseDispute(e, "alice"); - if (e.status !== "DISPUTED") throw new Error("Expected DISPUTED"); -}); - -test("resolve_dispute releases funds to carrier", () => { - const e = makeEscrow(); - raiseDispute(e, "alice"); - resolveDispute(e, "admin", true); - if (e.status !== "RELEASED") throw new Error("Expected RELEASED"); -}); - -test("resolve_dispute refunds shipper", () => { - const e = makeEscrow(); - raiseDispute(e, "alice"); - resolveDispute(e, "admin", false); - if (e.status !== "REFUNDED") throw new Error("Expected REFUNDED"); -}); - -test("only admin can resolve disputes", () => { - const e = makeEscrow(); - raiseDispute(e, "alice"); - try { resolveDispute(e, "alice", true); throw new Error("Should have thrown"); } - catch (err) { if ((err as Error).message !== "Only admin can resolve disputes") throw err; } -}); - -test("raising dispute on already-disputed escrow is rejected", () => { - const e = makeEscrow(); - raiseDispute(e, "alice"); - try { raiseDispute(e, "bob"); throw new Error("Should have thrown"); } - catch (err) { if ((err as Error).message !== "Can only dispute an active escrow") throw err; } -}); diff --git a/contracts/escrow/src/admin.rs b/contracts/escrow/src/admin.rs deleted file mode 100644 index 2b4d44e4d..000000000 --- a/contracts/escrow/src/admin.rs +++ /dev/null @@ -1,174 +0,0 @@ -//! The contract's ABI surface. -//! -//! Every entrypoint is declared here in one `#[contractimpl]` block so the -//! externally callable interface can be read in one place; the logic behind -//! each one lives in [`crate::funding`] or [`crate::settlement`]. - -use soroban_sdk::{contract, contractimpl, Address, Env}; - -use crate::errors::EscrowError; -use crate::types::{DataKey, EscrowRecord}; -use crate::{funding, settlement, storage}; - -#[contract] -pub struct EscrowContract; - -#[contractimpl] -impl EscrowContract { - /// One-time initialisation. `token_contract` is the SEP-41 token address - /// (e.g. the Stellar native-XLM wrapper contract on Soroban). - pub fn initialize( - env: Env, - admin: Address, - token_contract: Address, - ) -> Result<(), EscrowError> { - if env.storage().instance().has(&DataKey::Admin) { - return Err(EscrowError::AlreadyInitialized); - } - env.storage().instance().set(&DataKey::Admin, &admin); - env.storage().instance().set(&DataKey::Paused, &false); - env.storage() - .instance() - .set(&DataKey::TokenContract, &token_contract); - Ok(()) - } - - /// Transfer admin rights to a new address. Callable only by the current admin. - pub fn rotate_admin( - env: Env, - current_admin: Address, - new_admin: Address, - ) -> Result<(), EscrowError> { - current_admin.require_auth(); - if current_admin != storage::admin(&env)? { - return Err(EscrowError::Unauthorized); - } - env.storage().instance().set(&DataKey::Admin, &new_admin); - Ok(()) - } - - /// Admin-only: pause all state-mutating entrypoints. - pub fn pause(env: Env, admin: Address) -> Result<(), EscrowError> { - admin.require_auth(); - if admin != storage::admin(&env)? { - return Err(EscrowError::Unauthorized); - } - env.storage().instance().set(&DataKey::Paused, &true); - Ok(()) - } - - /// Admin-only: resume state-mutating entrypoints. - pub fn unpause(env: Env, admin: Address) -> Result<(), EscrowError> { - admin.require_auth(); - if admin != storage::admin(&env)? { - return Err(EscrowError::Unauthorized); - } - env.storage().instance().set(&DataKey::Paused, &false); - Ok(()) - } - - /// Configure the shipment contract allowed to settle escrow atomically. - /// The platform admin remains supported for custody-model compatibility. - pub fn set_shipment_contract(env: Env, shipment_contract: Address) -> Result<(), EscrowError> { - storage::admin(&env)?.require_auth(); - storage::require_not_paused(&env)?; - env.storage() - .instance() - .set(&DataKey::ShipmentContract, &shipment_contract); - Ok(()) - } - - /// Admin-only: update the SEP-41 token contract address. - /// - /// `initialize` sets `DataKey::TokenContract` once; without this entrypoint - /// there is no in-place recovery path if the token is redeployed (e.g. a - /// migrated SEP-41 wrapper or a redeployed asset contract). Mirrors the - /// pattern already shipped for `set_authorized_contract` in the reputation - /// crate (closed issue [CONTRACT-64]). - /// - /// Requires admin auth and the contract to be unpaused, consistent with - /// `set_shipment_contract` in this same crate. - pub fn set_token_contract(env: Env, new_token: Address) -> Result<(), EscrowError> { - storage::admin(&env)?.require_auth(); - storage::require_not_paused(&env)?; - env.storage() - .instance() - .set(&DataKey::TokenContract, &new_token); - Ok(()) - } - - /// Shipper locks funds for a shipment. See [`funding::fund`]. - pub fn fund_escrow( - env: Env, - shipper: Address, - carrier: Address, - shipment_id: u64, - amount: i128, - ) -> Result<(), EscrowError> { - funding::fund(&env, shipper, carrier, shipment_id, amount) - } - - /// Pay the carrier. See [`settlement::release`]. - pub fn release_payment(env: Env, shipment_id: u64) -> Result<(), EscrowError> { - settlement::release(&env, shipment_id) - } - - /// Return the funds to the shipper. See [`settlement::refund`]. - pub fn refund_payment(env: Env, shipment_id: u64) -> Result<(), EscrowError> { - settlement::refund(&env, shipment_id) - } - - /// Cancel a shipment, retaining `fee_amount` (in the token's base unit) - /// for the platform and returning the remainder to the shipper. A - /// `fee_amount` of `0` is a full refund. See - /// [`settlement::refund_with_fee`]. - pub fn refund_payment_with_fee( - env: Env, - shipment_id: u64, - fee_amount: i128, - ) -> Result<(), EscrowError> { - settlement::refund_with_fee(&env, shipment_id, fee_amount) - } - - /// Either party disputes the escrow. See [`settlement::raise_dispute`]. - pub fn raise_dispute(env: Env, caller: Address, shipment_id: u64) -> Result<(), EscrowError> { - settlement::raise_dispute(&env, caller, shipment_id) - } - - /// Admin resolves a dispute. See [`settlement::resolve_dispute`]. - pub fn resolve_dispute( - env: Env, - shipment_id: u64, - release_to_carrier: bool, - ) -> Result<(), EscrowError> { - settlement::resolve_dispute(&env, shipment_id, release_to_carrier) - } - - pub fn get_escrow(env: Env, shipment_id: u64) -> Result { - storage::load(&env, shipment_id) - } - - /// The platform fee (in base units) retained the last time this escrow - /// was settled as a partial refund, or `0` if it has not been. - /// - /// Lets the backend's escrow reconciliation confirm that the fee it - /// recorded off-chain matches what the contract actually paid out. - pub fn get_settlement_fee(env: Env, shipment_id: u64) -> i128 { - storage::settlement_fee(&env, shipment_id) - } - - /// Read the configured admin address. - /// - /// Lets external callers (e.g. the backend's Soroban integration layer) - /// verify their loaded signing keypair actually matches this contract's - /// admin at startup, instead of discovering a mismatch on first real - /// admin-gated call. - pub fn get_admin(env: Env) -> Result { - storage::admin(&env) - } - - pub fn get_balance(env: Env) -> Result { - let token = storage::token(&env)?; - Ok(token.balance(&env.current_contract_address())) - } -} diff --git a/contracts/escrow/src/audit.md b/contracts/escrow/src/audit.md deleted file mode 100644 index 0d355cc9a..000000000 --- a/contracts/escrow/src/audit.md +++ /dev/null @@ -1,141 +0,0 @@ -# Batch Create Per-Item Validation Reporting - -## Summary - -Implemented per-item validation reporting for the batch-create shipments endpoint. Previously, the endpoint used an all-or-nothing transaction approach where any single failure would roll back the entire batch with no detailed feedback. Now, each shipment is processed individually, and the response includes detailed success/failure status for each item. - -## Changes Made - -### 1. New DTOs (`batch-create-result.dto.ts`) - -Created two new DTOs to structure the batch response: - -- **`BatchItemResultDto`**: Represents the result for a single item in the batch - - `index`: Position in the original batch (0-based) - - `success`: Boolean indicating if the item was created successfully - - `id?`: Shipment ID (present only if success=true) - - `error?`: Error message (present only if success=false) - -- **`BatchCreateResultDto`**: Aggregate response for the entire batch - - `total`: Total number of items in the batch - - `succeeded`: Count of successful items - - `failed`: Count of failed items - - `items`: Array of `BatchItemResultDto` with per-item details - -### 2. Service Layer (`shipments.service.ts`) - -Modified `batchCreate()` method: - -**Before:** - -- Single transaction wrapping all shipments -- All-or-nothing: any failure rolls back entire batch -- Returns `string[]` (array of created IDs) -- No per-item error reporting - -**After:** - -- Each shipment processed in its own transaction -- Partial success: valid shipments are created even if others fail -- Returns `BatchCreateResultDto` with detailed per-item results -- Each item's success or failure is tracked independently -- Failed items include error messages for debugging - -### 3. Controller Layer (`shipments.controller.ts`) - -Updated the batch-create endpoint: - -- Changed return type to `Promise` -- Updated API documentation to reflect per-item reporting -- Added `type: BatchCreateResultDto` to `@ApiResponse` decorator -- Updated description to clarify individual processing - -### 4. Tests (`shipments.service.spec.ts`) - -Updated and added tests: - -**Test 1: "creates multiple shipments and returns per-item results"** - -- Verifies successful batch creation -- Validates response structure with per-item details -- Confirms all items show success=true with IDs - -**Test 2: "returns per-item results with mixed success and failure"** - -- Tests batch with 3 items: 2 valid, 1 invalid -- Validates partial success behavior -- Confirms failed item includes error message -- Verifies successful items are still created -- Checks transaction behavior (2 commits, 1 rollback) - -## API Response Example - -### Successful Batch (All Items Valid) - -```json -{ - "total": 2, - "succeeded": 2, - "failed": 0, - "items": [ - { - "index": 0, - "success": true, - "id": "uuid-1" - }, - { - "index": 1, - "success": true, - "id": "uuid-2" - } - ] -} -``` - -### Partial Success (Mixed Valid/Invalid Items) - -```json -{ - "total": 3, - "succeeded": 2, - "failed": 1, - "items": [ - { - "index": 0, - "success": true, - "id": "uuid-1" - }, - { - "index": 1, - "success": false, - "error": "Validation error: weightKg must be a positive number" - }, - { - "index": 2, - "success": true, - "id": "uuid-3" - } - ] -} -``` - -## Benefits - -1. **Better Developer Experience**: Callers get clear, actionable feedback about which items failed and why -2. **Partial Success**: Valid shipments are created even if others fail, reducing the need for retries -3. **Debugging**: Error messages per item make it easy to identify and fix issues -4. **Backward Compatible**: The endpoint still accepts the same request format; only the response structure changed -5. **Transactional Integrity**: Each item is still processed transactionally, ensuring data consistency per shipment - -## Acceptance Criteria Met - -✅ A caller submitting a batch with one invalid shipment gets clear, per-item feedback about what succeeded and what didn't - -✅ Per-item results include: - -- Index position for mapping back to original request -- Success/failure boolean -- Shipment ID for successful items -- Error message for failed items - -✅ Tests cover mixed valid/invalid batches and verify partial success behavior diff --git a/contracts/identity/carrier-whitelist.ts b/contracts/identity/carrier-whitelist.ts deleted file mode 100644 index 29d25d12b..000000000 --- a/contracts/identity/carrier-whitelist.ts +++ /dev/null @@ -1,53 +0,0 @@ -// CT-28: Carrier whitelist registration for the Identity contract -// Manages admin-controlled carrier approval on-chain - -export type Address = string; - -export interface CarrierWhitelistStorage { - carrierWhitelist: Map; - admin: Address; - whitelistEnabled: boolean; -} - -export function initWhitelistStorage(admin: Address): CarrierWhitelistStorage { - return { carrierWhitelist: new Map(), admin, whitelistEnabled: true }; -} - -function assertAdmin(storage: CarrierWhitelistStorage, caller: Address): void { - if (caller !== storage.admin) throw new Error("Unauthorized: admin only"); -} - -export function approveCarrier( - storage: CarrierWhitelistStorage, - caller: Address, - wallet: Address -): void { - assertAdmin(storage, caller); - storage.carrierWhitelist.set(wallet, true); -} - -export function revokeCarrier( - storage: CarrierWhitelistStorage, - caller: Address, - wallet: Address -): void { - assertAdmin(storage, caller); - storage.carrierWhitelist.set(wallet, false); -} - -export function isApprovedCarrier( - storage: CarrierWhitelistStorage, - wallet: Address -): boolean { - if (!storage.whitelistEnabled) return true; - return storage.carrierWhitelist.get(wallet) === true; -} - -export function setWhitelistEnabled( - storage: CarrierWhitelistStorage, - caller: Address, - enabled: boolean -): void { - assertAdmin(storage, caller); - storage.whitelistEnabled = enabled; -} diff --git a/contracts/shipment/shipment-metadata.ts b/contracts/shipment/shipment-metadata.ts deleted file mode 100644 index 86f45faa3..000000000 --- a/contracts/shipment/shipment-metadata.ts +++ /dev/null @@ -1,48 +0,0 @@ -// CT-25: Custom metadata key-value store for the Shipment contract - -const MAX_ENTRIES = 10; -const MAX_LEN = 64; - -export interface ShipmentMetadata { - shipmentId: string; - parties: string[]; - metadata: Map; -} - -function validate(key: string, value: string): void { - if (key.length > MAX_LEN || value.length > MAX_LEN) - throw new Error("Key/value exceeds 64 character limit"); -} - -export function createShipment( - shipmentId: string, - parties: string[], - initialMetadata: Record = {} -): ShipmentMetadata { - const entries = Object.entries(initialMetadata); - if (entries.length > MAX_ENTRIES) throw new Error("Exceeds max 10 metadata entries"); - const metadata = new Map(); - for (const [k, v] of entries) { validate(k, v); metadata.set(k, v); } - return { shipmentId, parties, metadata }; -} - -export function updateMetadata( - shipment: ShipmentMetadata, - caller: string, - key: string, - value: string -): void { - if (!shipment.parties.includes(caller)) throw new Error("Unauthorized: not a shipment party"); - validate(key, value); - if (!shipment.metadata.has(key) && shipment.metadata.size >= MAX_ENTRIES) - throw new Error("Exceeds max 10 metadata entries"); - shipment.metadata.set(key, value); -} - -export function getMetadata(shipment: ShipmentMetadata, key: string): string | undefined { - return shipment.metadata.get(key); -} - -export function getAllMetadata(shipment: ShipmentMetadata): Record { - return Object.fromEntries(shipment.metadata); -} diff --git a/contracts/shipment/shipment-storage.ts b/contracts/shipment/shipment-storage.ts deleted file mode 100644 index 7c688d418..000000000 --- a/contracts/shipment/shipment-storage.ts +++ /dev/null @@ -1,52 +0,0 @@ -// CT-27: Upgradeable storage pattern for the Shipment contract -// Versioned schema migration without full redeployment - -export interface ShipmentStorageV1 { - storageVersion: 1; - shipmentId: string; - carrier: string; - shipper: string; - status: string; -} - -export interface ShipmentStorageV2 extends Omit { - storageVersion: 2; - estimatedDelivery: number; // unix timestamp added in v2 - trackingEvents: string[]; -} - -export type ShipmentStorage = ShipmentStorageV1 | ShipmentStorageV2; - -export function createV1(shipmentId: string, carrier: string, shipper: string): ShipmentStorageV1 { - return { storageVersion: 1, shipmentId, carrier, shipper, status: "CREATED" }; -} - -export function migrateV1ToV2( - storage: ShipmentStorageV1, - caller: string, - admin: string -): ShipmentStorageV2 { - if (caller !== admin) throw new Error("Unauthorized: admin only"); - return { - ...storage, - storageVersion: 2, - estimatedDelivery: 0, - trackingEvents: [], - }; -} - -export function migrate( - storage: ShipmentStorage, - targetVersion: number, - caller: string, - admin: string -): ShipmentStorage { - if (storage.storageVersion === 1 && targetVersion === 2) { - return migrateV1ToV2(storage as ShipmentStorageV1, caller, admin); - } - throw new Error(`Unsupported migration: v${storage.storageVersion} -> v${targetVersion}`); -} - -export function getVersion(storage: ShipmentStorage): number { - return storage.storageVersion; -} diff --git a/frontend/app/track/[trackingNumber]/page.tsx b/frontend/app/track/[trackingNumber]/page.tsx index 3621d80b3..acf56bd54 100644 --- a/frontend/app/track/[trackingNumber]/page.tsx +++ b/frontend/app/track/[trackingNumber]/page.tsx @@ -1,11 +1,14 @@ 'use client'; -import { useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; import { useParams } from 'next/navigation'; import { shipmentApi } from '../../../lib/api/shipment.api'; import { PublicStatusTimeline } from '../../../components/shipment/status-timeline'; import { StatusBadge } from '../../../components/shipment/status-badge'; -import type { PublicShipmentTracking } from '../../../types/shipment.types'; +import { ShipmentStatus, type PublicShipmentTracking } from '../../../types/shipment.types'; + +const POLL_INTERVAL_MS = 60_000; +const TERMINAL_STATUSES = new Set([ShipmentStatus.COMPLETED, ShipmentStatus.CANCELLED]); export default function TrackingPage() { const { trackingNumber } = useParams<{ trackingNumber: string }>(); @@ -13,19 +16,62 @@ export default function TrackingPage() { const [loading, setLoading] = useState(true); const [notFound, setNotFound] = useState(false); const [error, setError] = useState(false); + const [lastUpdated, setLastUpdated] = useState(null); + const [refreshing, setRefreshing] = useState(false); + + // `silent` keeps background refreshes from swapping the page back to its + // full-screen spinner; manual refreshes use the same path. + const fetchStatus = useCallback( + async (silent = false) => { + if (!trackingNumber) return; + if (silent) setRefreshing(true); + else setLoading(true); + try { + const data = await shipmentApi.track(trackingNumber); + setShipment(data); + setLastUpdated(new Date()); + setNotFound(false); + setError(false); + } catch (err: unknown) { + const apiError = err as { statusCode?: number }; + if (apiError?.statusCode === 404) setNotFound(true); + else if (!silent) setError(true); + } finally { + setLoading(false); + setRefreshing(false); + } + }, + [trackingNumber], + ); useEffect(() => { - if (!trackingNumber) return; - setLoading(true); - shipmentApi - .track(trackingNumber) - .then(setShipment) - .catch((err: { statusCode?: number }) => { - if (err?.statusCode === 404) setNotFound(true); - else setError(true); - }) - .finally(() => setLoading(false)); - }, [trackingNumber]); + void fetchStatus(); + }, [fetchStatus]); + + const isTerminal = shipment + ? TERMINAL_STATUSES.has(shipment.status) + : false; + + // Public tracking has no socket, so poll while the shipment is live. The + // interval and the visibility handler never fire requests for hidden tabs, + // and stop entirely once the shipment reaches a terminal status (#1850). + useEffect(() => { + if (!shipment || isTerminal) return; + + const poll = () => { + if (!document.hidden) void fetchStatus(true); + }; + const onVisibilityChange = () => { + if (!document.hidden) void fetchStatus(true); + }; + + const interval = window.setInterval(poll, POLL_INTERVAL_MS); + document.addEventListener('visibilitychange', onVisibilityChange); + return () => { + window.clearInterval(interval); + document.removeEventListener('visibilitychange', onVisibilityChange); + }; + }, [shipment?.status, isTerminal, fetchStatus]); if (loading) { return ( @@ -78,6 +124,21 @@ export default function TrackingPage() { +
+ {lastUpdated && ( + + Last updated {lastUpdated.toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' })} + + )} + +
{/* Details */}