From dc3f34766d8f83c124f4a58fda16f45b3a997ceb Mon Sep 17 00:00:00 2001 From: Divyansh Date: Fri, 19 Jun 2026 17:23:13 +0530 Subject: [PATCH 1/4] chore: clean up repo, add Dockerfile, walkthrough script, and move images --- .dockerignore | 13 ++ BUGS.md | 73 ------- DEMO.md | 88 --------- Dockerfile | 45 +++++ NEXTSTEPS.md | 183 ------------------ README.md | 40 +++- envs_for_ayush.md | 18 -- .../happy_path_flowchart.png | Bin .../over_value_flowchart.png | Bin .../port_mismatch_flowchart.png | Bin .../trade_finance_architecture_flowchart.png | Bin keys.md | 2 - project_readme.md | 176 ----------------- scratch/check_db.ts | 13 -- scratch/create_account.js | 19 -- scratch/test_transfer.js | 17 -- videoscript.md | 62 ------ walkthrough.md | 90 +++++++++ 18 files changed, 181 insertions(+), 658 deletions(-) create mode 100644 .dockerignore delete mode 100644 BUGS.md delete mode 100644 DEMO.md create mode 100644 Dockerfile delete mode 100644 NEXTSTEPS.md delete mode 100644 envs_for_ayush.md rename happy_path_flowchart.png => images/happy_path_flowchart.png (100%) rename over_value_flowchart.png => images/over_value_flowchart.png (100%) rename port_mismatch_flowchart.png => images/port_mismatch_flowchart.png (100%) rename trade_finance_architecture_flowchart.png => images/trade_finance_architecture_flowchart.png (100%) delete mode 100644 keys.md delete mode 100644 project_readme.md delete mode 100644 scratch/check_db.ts delete mode 100644 scratch/create_account.js delete mode 100644 scratch/test_transfer.js delete mode 100644 videoscript.md create mode 100644 walkthrough.md diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..761f999 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +node_modules +.next +.git +.env +.env.local +.env*.local +*.db +*.db-journal +stripe_destinations_cache.json +Dockerfile +.dockerignore +README.md +walkthrough.md diff --git a/BUGS.md b/BUGS.md deleted file mode 100644 index ac96702..0000000 --- a/BUGS.md +++ /dev/null @@ -1,73 +0,0 @@ -# BUGS.md — Terminal 3 SDK / docs friction log - -Parallel bug-bounty track. Every claim-flow / SDK / docs friction encountered -while building gets logged here (severity, repro, expected vs actual). - -> TODO: email `devrel@terminal3.io` to confirm where bug submissions should go. - ---- - -## #1 — Spec says "API key", SDK has no API-key concept - -- **Severity:** Low (docs / onboarding friction) -- **Where:** Onboarding, `@terminal3/t3n-sdk@3.5.2` -- **Repro:** Following an "agent" mental model, you look for `T3N_API_KEY` to - authenticate the client. There is no such parameter. -- **Expected:** A documented API-key or token to identify the agent. -- **Actual:** The agent authenticates with an **Ethereum private key** (or OIDC). - The DID is *derived* from the key via `eth_get_address` → - `createEthAuthInput` → `client.authenticate`. There is no API key. -- **Resolution in this repo:** env var is `T3N_AGENT_PRIVATE_KEY`; the secret - never leaves the server and only the public DID/address is exposed. - -## #2 — No single end-to-end quickstart (API key -> first resolved DID) - -- **Severity:** Medium (docs gap, known) -- **Where:** `https://docs.terminal3.io` + package README -- **Repro:** As a newcomer, there is no one page that walks from - "I have credentials" to "I authenticated and resolved my first DID". -- **Expected:** A copy-paste quickstart that ends in a printed DID. -- **Actual:** You assemble it from the README snippets: - `setEnvironment` → `loadWasmComponent` → `eth_get_address` → - `new T3nClient({ handlers: { EthSign: metamask_sign(...) } })` → - `handshake()` → `authenticate(createEthAuthInput(address))` → `getDid()`. - Verified working against `testnet` (node `cn-api.sg.testnet.t3n.terminal3.io`). - -## #3 — `handshake()` returns `did: null` / `authenticated: false` - -- **Severity:** Low (mild surprise, not a blocker) -- **Where:** `T3nClient.handshake()` return value -- **Repro:** `const hr = await client.handshake()` → - `{ sessionId, expiry: 0, authenticated: false, did: null }`. -- **Expected (naively):** handshake yields the identity. -- **Actual:** Identity only appears after the separate `authenticate()` call. - This is correct (handshake = encrypted session; authenticate = identity), but - the `did?: Did` field on `HandshakeResult` invites the wrong assumption. - -## #4 — Delegation `agent_pubkey` format undocumented; no SDK pubkey helper - -- **Severity:** Medium (integration friction on the headline Agent-Auth path) -- **Where:** `buildDelegationCredential({ agent_pubkey })`, `@terminal3/t3n-sdk@3.5.2` -- **Repro:** Building a delegation credential needs `agent_pubkey: Uint8Array`, - but nothing documents the encoding, and the SDK exports `eth_get_address` - (20-byte address) — not a public key. There is no `eth_get_pubkey` helper. -- **Expected:** A documented format + an SDK helper to derive the agent pubkey - from the same secret used for `metamask_sign` / `signAgentInvocation`. -- **Actual:** Determined empirically that `AGENT_PUBKEY_LEN === 33`, i.e. the - **compressed secp256k1** public key. Derived it via ethers - `new SigningKey(pk).compressedPublicKey` (ethers is already an SDK dep). - Works, but newcomers must reverse-engineer the length constant. - -## #5 — Doc gap: no worked example for the delegate → invoke crypto flow - -- **Severity:** Medium (docs gap on the SDK's headline feature) -- **Where:** README / `https://docs.terminal3.io` -- **Repro:** The delegation primitives (`buildDelegationCredential`, - `canonicaliseCredential`, `signCredential`, `buildInvocationPreimage`, - `signAgentInvocation`) ship with good doc comments but no end-to-end example - tying "user signs credential" → "agent signs invocation" → contract submit. -- **Expected:** One worked snippet (the `tee:payroll` flow exists as - `buildPayrollInvocation`, but it's payroll-specific and assumes a deployed - contract). -- **Actual:** Assembled the generic flow from the type defs; captured working - offline + testnet runs in `tools/step3-smoke.ts` for reference. diff --git a/DEMO.md b/DEMO.md deleted file mode 100644 index 3dffbfc..0000000 --- a/DEMO.md +++ /dev/null @@ -1,88 +0,0 @@ -# DEMO.md - Judge Walkthrough - -This walkthrough shows the project in under five minutes. - -## Setup - -```bash -npm install -cp .env.example .env.local -npm run db:push -npm run db:seed -npm run dev -``` - -Open `http://localhost:3000`. - -Required local env values: - -- `DATABASE_URL="file:./dev.db"` -- `T3N_AGENT_PRIVATE_KEY=0x...` -- `T3N_DEMO_BUYER_PRIVATE_KEY=0x...` - -Stripe is optional: -- **Simulation Mode**: Without `STRIPE_SECRET_KEY`, the app automatically uses simulator escrow refs (`pi_sim_*` and `tr_sim_*`). -- **Zero-Configuration Live Test Mode**: If you provide `STRIPE_SECRET_KEY` but do not configure `STRIPE_DESTINATIONS`, the project automatically and dynamically provisions test-mode Custom Connect accounts on your Stripe dashboard on-the-fly and executes transfers to them. - -## Happy Path - -1. Open the dashboard. -2. Select the valid Rotterdam Letter of Credit. -3. Click `Authorize escrow`. -4. Watch the state move from `INITIATED` to `ESCROWED`. -5. Click `Simulate delivery`. -6. Watch the live agent log: - - buyer authorization minted - - escrow locked - - BoL parsed - - deterministic policy passed - - agent identity verified - - placeholder resolved inside TEE - - payout fired - - audit rows written -7. Confirm final state is `SETTLED`. -8. Confirm the audit ledger shows `EXECUTED -> SETTLED`. - -## Denied Case: Port Mismatch - -1. Select the LC whose target port is Rotterdam but terms require Hamburg. -2. Click `Authorize escrow`. -3. Click `Simulate delivery`. -4. The policy gate rejects release because the delivery port does not match the - contract terms. -5. Confirm no release transfer is created. -6. Confirm the audit ledger includes `VERIFIED -> DENIED`. - -## Denied Case: Over Value - -1. Select the Singapore LC whose value exceeds the contract cap. -2. Click `Authorize escrow`. -3. Click `Simulate delivery`. -4. The policy gate rejects release because value exceeds the max cap. -5. Confirm no release transfer is created. -6. Confirm the audit ledger includes `VERIFIED -> DENIED`. - -## API Checks - -```bash -curl -s http://localhost:3000/health -curl -s http://localhost:3000/api/lc -curl -s http://localhost:3000/api/ledger -curl -N http://localhost:3000/api/stream -``` - -## Smoke Test - -```bash -npm run smoke:step5 -``` - -This verifies: - -- valid LC settles end-to-end -- port mismatch denies with audit proof -- over-value denies with audit proof -- duplicate delivery after settlement does not double-release -- DID mismatch is rejected -- missing agent key fails before mutating LC state or escrow rows - diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d5a469f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +FROM node:20-alpine + +# Install openssl and curl (useful for health checks) +RUN apk add --no-cache openssl curl + +WORKDIR /app + +# Copy dependency configs +COPY package*.json ./ +COPY tsconfig.json ./ +COPY next.config.mjs ./ +COPY postcss.config.mjs ./ +COPY tailwind.config.ts ./ + +# Copy database schema +COPY prisma ./prisma/ + +# Install all dependencies (development & production) +RUN npm ci + +# Copy the rest of the application code +COPY app ./app/ +COPY lib ./lib/ +COPY tools ./tools/ +COPY images ./images/ + +# Generate Prisma Client & Build the application for production +RUN npx prisma generate +RUN npm run build + +# Create a directory to store the persistent SQLite database +RUN mkdir -p /app/data +ENV DATABASE_URL="file:/app/data/dev.db" + +# Expose Next.js port +EXPOSE 3000 +ENV PORT 3000 +ENV HOSTNAME "0.0.0.0" + +# Setup runtime entrypoint script to automatically push schema, seed, and run +RUN echo '#!/bin/sh' > /app/start.sh && \ + echo 'npx prisma db push --accept-data-loss && npx prisma db seed && npm run start' >> /app/start.sh && \ + chmod +x /app/start.sh + +CMD ["/app/start.sh"] diff --git a/NEXTSTEPS.md b/NEXTSTEPS.md deleted file mode 100644 index ef0ff46..0000000 --- a/NEXTSTEPS.md +++ /dev/null @@ -1,183 +0,0 @@ -# NEXTSTEPS.md - Project Completion Plan - -This file is the working checklist for finishing the Autonomous Trade Finance -Agent. After each completed task, update the relevant checkbox from `[ ]` to -`[x]` and add a short note if anything changed from the original plan. - -## Current Baseline - -- [x] Step 1: Next.js scaffold and `/health` route. -- [x] Step 2: Prisma domain model, SQLite seed data, placeholder-only storage. -- [x] Step 3: Terminal 3 SDK adapter for identity, delegation, invocation, audit receipt. -- [x] Step 4: Escrow layer with Stripe/simulator and payout idempotency. -- [x] Step 5 core: Agent loop, advisory BoL parser, deterministic policy gate. -- [x] Step 5 verification: Smoke test the full lifecycle from seeded LC to settlement/denial. -- [x] Step 6: API routes and SSE stream. -- [x] Step 7: Dashboard demo UI. -- [x] Step 8: Edge cases, docs, and final demo polish. - -## Chunk 1 - Align Docs With Code - -Goal: make the project docs reflect the real implementation state before adding -more surface area. - -- [x] Update `README.md` progress checklist to mark Step 5 core as implemented. -- [x] Add a short note that Step 5 still needs lifecycle/API verification. -- [x] Keep the "Where the SDK fires" section accurate after any line movement. -- [x] Decide whether `.agents/claude.md` should stay as original spec or receive a status note. - -Decision: `.agents/claude.md` stays as the original build spec. Live status now -lives here and in the README progress section. - -Remaining after this chunk: - -- Step 5 lifecycle verification. -- API routes and SSE. -- Dashboard. -- Edge cases and final docs/demo. - -## Chunk 2 - Full Lifecycle Smoke Test - -Goal: prove `lib/agent/run.ts` works end-to-end against seeded data. - -- [x] Add `tools/step5-smoke.ts`. -- [x] Exercise valid LC: authorize -> escrow -> delivery -> policy pass -> payout -> settled. -- [x] Exercise port mismatch LC: delivery -> policy fail -> denial audit row. -- [x] Exercise over-value LC: delivery -> policy fail -> denial audit row. -- [x] Confirm idempotency behavior or document the current duplicate-webhook limitation. -- [x] Add an npm script for the smoke test if useful. - -Verification: `npm run smoke:step5` passed with temporary local test keys and -simulator escrow. Duplicate delivery after settlement is rejected by state guard -and does not create a second release. - -Remaining after this chunk: - -- API routes and SSE. -- Dashboard. -- Edge cases and final docs/demo. - -## Chunk 3 - API Routes - -Goal: expose the agent workflow through clean, redacted HTTP endpoints. - -- [x] `GET /api/lc` - list Letters of Credit with terms and current state. -- [x] `POST /api/lc` - create a new Letter of Credit with contract terms. -- [x] `POST /api/lc/[id]/authorize` - call `authorizeAndEscrow`. -- [x] `POST /api/webhook/delivery` - call `onDeliveryWebhook`. -- [x] `GET /api/ledger` - return redacted audit entries. -- [x] Ensure every response passes the redaction guard. -- [x] Ensure route handlers run on Node.js runtime where needed. -- [x] Add basic error envelopes with safe messages and status codes. - -Verification: `npx tsc --noEmit` and `npm run build` passed after adding the -API route tree. - -Remaining after this chunk: - -- SSE stream. -- Dashboard. -- Edge cases and final docs/demo. - -## Chunk 4 - SSE Event Stream - -Goal: stream state transitions and secure-enclave events to the dashboard. - -- [x] Add `GET /api/stream`. -- [x] Subscribe to `onStep`. -- [x] Emit server-sent events in browser-friendly format. -- [x] Send keepalive comments or pings. -- [x] Clean up listeners on disconnect. -- [x] Verify no raw account-like values can stream. - -Verification: `npm run build` includes `/api/stream`; `npx tsc --noEmit` -passes after build-generated Next types are stable. - -Remaining after this chunk: - -- Dashboard. -- Edge cases and final docs/demo. - -## Chunk 5 - Dashboard - -Goal: build the judge-facing demo surface. - -- [x] Replace the current placeholder home page with a functional dashboard. -- [x] Show active LC contracts and state. -- [x] Add authorize/escrow action for an LC. -- [x] Add "Simulate Port Delivery" action. -- [x] Show live agent log from SSE. -- [x] Show a five-node state machine rail. -- [x] Show a Terminal 3 Secure Enclave view with placeholder -> resolve -> payout -> receipt flow. -- [x] Show audit ledger entries. -- [x] Make valid, port-mismatch, and over-value cases easy to demo. -- [x] Verify mobile and desktop layouts. - -Verification: `npm run build` and `npx tsc --noEmit` passed. Dev server -responded at `http://localhost:3000`, dashboard HTML contained the expected -console title, `/api/lc` and `/api/ledger` returned redacted data, and -`/api/stream` emitted the SSE `ready` event. `agent-browser` was not available -on PATH, so verification used responsive code review plus HTTP/build checks. - -Remaining after this chunk: - -- Edge cases and final docs/demo. - -## Chunk 6 - Edge Cases And Hardening - -Goal: make all required failure paths demoable and graceful. - -- [x] Duplicate delivery webhook is idempotent or cleanly rejected without double payout. -- [x] Port mismatch denies with audit proof. -- [x] Value over contract cap denies with audit proof. -- [x] Invalid or missing agent identity fails safely. -- [x] TEE resolution failure fails safely. -- [x] Stripe payout decline/failure fails safely. -- [x] Redaction guard is applied to all outward payloads. -- [x] Confirm no raw account/routing/card-like values are stored or returned. - -Verification: Step 5 smoke confirms duplicate post-settlement delivery does not -double-release, port mismatch denies, over-value denies, DID mismatch throws -`IdentityError`, and missing agent key fails before LC/escrow mutation. -Settlement failures after policy pass now transition to `FAILED` with an audit -row. A raw-value scan for card/account/routing/IBAN/Stripe-secret patterns -returned no matches. - -Remaining after this chunk: - -- Final docs/demo polish. - -## Chunk 7 - Final Docs And Demo Polish - -Goal: make the repo easy to judge, clone, run, and understand. - -- [x] Update `README.md` with current routes, scripts, and final status. -- [x] Add `DEMO.md` with a click-by-click judge walkthrough. -- [x] Add a short architecture diagram or text flow. -- [x] Update "Where the SDK fires" line references. -- [x] Update `BUGS.md` with any new SDK/docs friction. -- [x] Add a final clone-to-demo checklist. -- [x] Run lint/build/smoke tests and record results. - -Verification: `README.md`, `DEMO.md`, and `project_readme.md` are current. -No new Terminal 3 SDK/docs friction was found beyond existing `BUGS.md` entries. -`npm run lint`, `npx tsc --noEmit`, `npm run build`, and -`npm run smoke:step5` pass. Raw-value scan returned no matches. - -Remaining after this chunk: - -- Project ready for final review/submission. - -## Running Task Log - -Use this section to record completed work as we go. - -- [x] Chunk 1 complete: README now reflects Step 5 core implementation; `.agents/claude.md` remains the original spec. -- [x] Chunk 2 complete: added and ran `tools/step5-smoke.ts`; valid LC settled, port mismatch and over-value denied, duplicate post-settlement delivery did not double-release. -- [x] Chunk 3 complete: added LC, authorize, delivery webhook, and ledger API routes with guarded redacted responses; TypeScript and Next build passed. -- [x] Chunk 4 complete: added SSE stream route with redaction check, keepalive, and disconnect cleanup. -- [x] Chunk 5 complete: dashboard implemented and HTTP/build verified; `agent-browser` was unavailable on PATH, so visual verification used responsive code review plus route checks. -- [x] Chunk 6 complete: duplicate, policy denial, settlement failure, payout failure, redaction, DID mismatch, and missing-key safety are covered. -- [x] Chunk 7 complete: README updated, `DEMO.md` added, `project_readme.md` added, final verification recorded. -- [x] Chunk 8 complete: Stripe Connect zero-configuration dynamic custom account creation fallback added and verified. -- [x] Chunk 9 complete: Visual inspector side drawer enhanced with dynamic data-rich cards for every enclave and settlement lifecycle event. diff --git a/README.md b/README.md index 7c6431c..25142a7 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ This project fundamentally depends on Terminal 3's secure capabilities: Our architecture splits execution into three strict security zones to ensure no sensitive hot keys or bank details escape the isolated TEE boundary: -![Trade Finance Secure Architecture Flowchart](./trade_finance_architecture_flowchart.png) +![Trade Finance Secure Architecture Flowchart](./images/trade_finance_architecture_flowchart.png) 1. **Client Zone (Browser)**: The buyer uses their wallet to sign a contract delegation credential (EIP-191). This creates a secure, signed capability represented by an opaque placeholder. The agent never sees the buyer's private key. 2. **TEE Enclave (Private Execution)**: When a Bill of Lading delivery webhook is received, the agent operates in hardware-isolated memory. It uses Google Gemini to parse the unstructured logistics data, feeding it into a deterministic TypeScript policy engine. The LLM acts purely as an advisor; the code remains the sole gatekeeper for funds. @@ -90,19 +90,19 @@ The project ships pre-seeded with three validation scenarios so you can test all * **Config**: Rotterdam LC, $25,000 value, $50,000 maximum cap. * **Outcome**: Bill of lading matches the contract terms, Stripe captures the hold, and executes transfer to connected account (**SETTLED**). -![Happy Path Settlement Flowchart](./happy_path_flowchart.png) +![Happy Path Settlement Flowchart](./images/happy_path_flowchart.png) ### 2. Scenario 2: Port Mismatch Denial * **Config**: Rotterdam cargo delivery, but terms require Hamburg port. * **Outcome**: The deterministic policy gate flags mismatch and aborts settlement (**FAILED**). -![Port Mismatch Flowchart](./port_mismatch_flowchart.png) +![Port Mismatch Flowchart](./images/port_mismatch_flowchart.png) ### 3. Scenario 3: Over Value Cap * **Config**: Singapore cargo delivery, but LC value ($95,000) exceeds maximum cap ($50,000). * **Outcome**: Policy gate detects limit overrun and aborts settlement (**FAILED**). -![Over Value Flowchart](./over_value_flowchart.png) +![Over Value Flowchart](./images/over_value_flowchart.png) --- @@ -150,6 +150,32 @@ npm run audit:verify --- -## 📹 Video Presentation Kit -For video recording, slides, and case study data, check out: -* [videoscript.md](./videoscript.md) — Spoken word-for-word script, visual cues, and industry case studies. +## 🐳 Run with Docker + +You can package and run the application in a stateful Docker container with local SQLite database persistence. + +### 1. Build the Image +```bash +docker build -t trade-finance-agent . +``` + +### 2. Run the Container +Create a local `data` directory to mount inside the container. This preserves your SQLite database files across container restarts. + +**On Windows (PowerShell or Cmd):** +```bash +mkdir data +docker run -d -p 3000:3000 -v "%cd%/data:/app/data" --env-file .env.local trade-finance-agent +``` + +**On macOS / Linux / Bash:** +```bash +mkdir -p data +docker run -d -p 3000:3000 -v "$(pwd)/data:/app/data" --env-file .env.local trade-finance-agent +``` + +--- + +## 📹 Video Presentation & Walkthrough Kit +For video recording scripts, slides structure, and judge demo instructions, check out: +* [walkthrough.md](./walkthrough.md) — Step-by-step judge script, live Stripe dashboard verification checklist, and system walkthrough. diff --git a/envs_for_ayush.md b/envs_for_ayush.md deleted file mode 100644 index 090e12f..0000000 --- a/envs_for_ayush.md +++ /dev/null @@ -1,18 +0,0 @@ -# Environment Variables for Ayush - -Hey Ayush, here are all the environment variables we used to configure the Agent locally for the hackathon demo. - -**IMPORTANT SECURITY NOTE**: Make sure to remove these or swap them out for production keys when deploying. Do NOT leave these in the final production deployment. - -```env -T3N_AGENT_PRIVATE_KEY=0x54363dc0fc421addbfcbe438649866ed7bf43f8fdc629019a31aeb71aa68004b -T3N_DEMO_BUYER_PRIVATE_KEY=0x11223344556677889900aabbccddeeff11223344556677889900aabbccddeeff -DATABASE_URL="file:./dev.db" - -# Gemini LLM Integration (Replaced Anthropic) -GEMINI_API_KEY=AQ.Ab8RN6KYY6lv92R-cgAgdmg8oDj_P7JorknScZq9ofjK8PEpUQ - -# Stripe Connect Integration (Test Mode) -STRIPE_SECRET_KEY=sk_test_51TCzYR8iGRmogjncaXxCNpOVDqVZAPdr9FD1osFPfyyOLYjDiYrvxbpz4MOgCYLL4nb0uzwAz6ANaOfpxRTAaUFA00nWSQprmy -STRIPE_DESTINATIONS={"exporter-ref:acme-textiles-001":"acct_1TirxA8iGRP26vX8"} -``` diff --git a/happy_path_flowchart.png b/images/happy_path_flowchart.png similarity index 100% rename from happy_path_flowchart.png rename to images/happy_path_flowchart.png diff --git a/over_value_flowchart.png b/images/over_value_flowchart.png similarity index 100% rename from over_value_flowchart.png rename to images/over_value_flowchart.png diff --git a/port_mismatch_flowchart.png b/images/port_mismatch_flowchart.png similarity index 100% rename from port_mismatch_flowchart.png rename to images/port_mismatch_flowchart.png diff --git a/trade_finance_architecture_flowchart.png b/images/trade_finance_architecture_flowchart.png similarity index 100% rename from trade_finance_architecture_flowchart.png rename to images/trade_finance_architecture_flowchart.png diff --git a/keys.md b/keys.md deleted file mode 100644 index 2b259da..0000000 --- a/keys.md +++ /dev/null @@ -1,2 +0,0 @@ -apikey=0x54363dc0fc421addbfcbe438649866ed7bf43f8fdc629019a31aeb71aa68004b -did=did:t3n:c9f6b88a0751923e458e9b07cb74d7e809d985f3 \ No newline at end of file diff --git a/project_readme.md b/project_readme.md deleted file mode 100644 index 8c98fca..0000000 --- a/project_readme.md +++ /dev/null @@ -1,176 +0,0 @@ -# Autonomous Trade Finance Agent - Project Overview - -## What This Project Does - -This project is an autonomous Letter of Credit escrow agent for cross-border -trade finance. It models a buyer, exporter, contract terms, delivery proof, an -escrow hold, a secure payout boundary, and an immutable audit trail. - -The core flow: - -1. A Letter of Credit is created with buyer/exporter placeholders and contract - terms. -2. The buyer authorizes the agent through a Terminal 3 delegation credential. -3. The agent locks funds in escrow through Stripe test mode or a local simulator. -4. A mock Bill of Lading delivery webhook arrives. -5. An LLM or heuristic parser explains the delivery evidence. -6. Deterministic TypeScript policy code makes the binding payout decision. -7. If policy passes, the agent verifies its Terminal 3 identity and signs a TEE - invocation. -8. The TEE-style payout boundary resolves the exporter placeholder and fires the - transfer. -9. Every transition writes an audit row with a cryptographic receipt hash. - -The main safety invariant is that raw bank, card, routing, customer, or Stripe -secret values never enter the browser, database, logs, LLM prompt, or API -responses. The app stores and displays only opaque placeholders and masked refs. - -## Why It Is Interesting - -This uses the Terminal 3 Agent Auth SDK as the backbone of a non-trivial -institutional workflow. It is not just login. The SDK is used to: - -- resolve the agent DID -- mint buyer delegation credentials -- sign agent invocations -- prove the agent is authorized before privileged settlement -- produce public proof artifacts for the audit trail - -The LLM is deliberately not trusted with money movement. It can parse and -explain the Bill of Lading, but `verifyConditions` in deterministic TypeScript -is the only gate that can approve payout. - -## Main Features - -- Next.js 14 App Router dashboard. -- Prisma + SQLite persistence. -- Seeded demo Letters of Credit: - - valid shipment - - port mismatch denial - - over-value denial -- Terminal 3 SDK identity and agent-auth adapter. -- Buyer authorization placeholder minting. -- Stripe Connect test-mode escrow, with simulator fallback. -- Persistent idempotency ledger preventing duplicate locks/releases. -- Advisory LLM Bill-of-Lading parsing with deterministic fallback. -- Deterministic policy gate for payout approval. -- TEE-style placeholder resolution and payout boundary. -- Audit ledger with receipt hashes. -- Redaction guard for every public response/event boundary. -- Server-sent event stream for live agent logs. -- Dashboard with LC cards, state rails, secure enclave panel, live log, and - audit ledger. -- Full lifecycle smoke test. - -## Where the SDK Fires - -Every privileged identity, authorization, and payout-proof step routes through -`@terminal3/t3n-sdk`. These are the load-bearing SDK call sites: - -| Flow | SDK calls | File lines | -| --- | --- | --- | -| Agent session bootstrap | `setEnvironment`, `loadWasmComponent` | `lib/t3/client.ts:49`, `lib/t3/client.ts:50` | -| Agent address and DID auth | `eth_get_address`, `metamask_sign`, `new T3nClient`, `handshake`, `authenticate` | `lib/t3/client.ts:97`, `lib/t3/client.ts:102`, `lib/t3/client.ts:100`, `lib/t3/client.ts:105`, `lib/t3/client.ts:106` | -| Buyer authorization mint | `buildDelegationCredential`, `validateCredentialBody`, `canonicaliseCredential`, `signCredential`, `b64uEncodeBytes` | `lib/t3/adk.ts:125`, `lib/t3/adk.ts:136`, `lib/t3/adk.ts:138`, `lib/t3/adk.ts:139`, `lib/t3/adk.ts:141` | -| Agent identity check | `verifyAgentIdentity` calls authenticated T3 client session checks | `lib/t3/adk.ts:175` | -| TEE payout invocation proof | `b64uDecodeStrict`, `buildInvocationPreimage`, `signAgentInvocation`, `b64uEncodeBytes` | `lib/t3/adk.ts:272`, `lib/t3/adk.ts:278`, `lib/t3/adk.ts:279`, `lib/t3/adk.ts:280` | -| Audit receipt boundary | `writeAuditRow` persists the redacted proof and receipt hash | `lib/t3/adk.ts:350` | - -## Simulation Mode - -The project is designed to demo without paid or external financial accounts. -When Stripe credentials are absent, escrow and payout use deterministic simulator -references: - -- `pi_sim_*` for held PaymentIntent-style escrow locks. -- `tr_sim_*` for exporter release transfers. -- `acct_sim_*` for resolved exporter destinations. - -Terminal 3 credential minting, DID verification, and invocation signing still -use the real SDK path. The simulator only replaces the external money movement -boundary so the judge/demo flow is cloneable. - -## State Machine - -```text -INITIATED -> ESCROWED -> VERIFIED -> EXECUTED -> SETTLED -``` - -Failure/denial states: - -- `DENIED`: policy rejected release, such as port mismatch or value over cap. -- `FAILED`: identity, TEE resolution, or payout failed after policy passed. - -## Key Files - -| File | Purpose | -| --- | --- | -| `app/page.tsx` | Dashboard demo console. | -| `app/api/lc/route.ts` | List/create Letters of Credit. | -| `app/api/lc/[id]/authorize/route.ts` | Mint authorization and lock escrow. | -| `app/api/webhook/delivery/route.ts` | Mock delivery webhook. | -| `app/api/ledger/route.ts` | Redacted audit ledger API. | -| `app/api/stream/route.ts` | Server-sent event stream. | -| `lib/agent/run.ts` | State machine and settlement loop. | -| `lib/agent/policy.ts` | Deterministic payout policy gate. | -| `lib/agent/llm.ts` | Advisory BoL parser/explainer. | -| `lib/t3/client.ts` | Terminal 3 SDK client bootstrap. | -| `lib/t3/adk.ts` | Terminal 3 Agent Auth adapter. | -| `lib/t3/redact.ts` | Raw financial data leak guard. | -| `lib/escrow/index.ts` | Escrow lock/release and idempotency. | -| `prisma/schema.prisma` | Domain data model. | -| `tools/step5-smoke.ts` | End-to-end lifecycle smoke test. | - -## API Routes - -| Route | Method | Purpose | -| --- | --- | --- | -| `/health` | `GET` | Resolve Terminal 3 agent identity. | -| `/api/lc` | `GET` | List Letters of Credit. | -| `/api/lc` | `POST` | Create a Letter of Credit. | -| `/api/lc/[id]/authorize` | `POST` | Authorize buyer and lock escrow. | -| `/api/webhook/delivery` | `POST` | Simulate Bill-of-Lading delivery. | -| `/api/ledger` | `GET` | Read redacted audit entries. | -| `/api/stream` | `GET` | Stream live agent events via SSE. | - -## Run Locally - -```bash -npm install -cp .env.example .env.local -npm run db:push -npm run db:seed -npm run dev -``` - -Then open: - -```text -http://localhost:3000 -``` - -## Verification - -```bash -npm run smoke:step5 -npx tsc --noEmit -npm run build -``` - -The Step 5 smoke test verifies settlement, denial cases, duplicate protection, -identity mismatch handling, and missing-key safety. - -## Current Limitations - -- The deployed TEE contract submission is documented as `TODO: confirm` because - no deployed `tee:trade-finance` contract exists in this scaffold. -- The immutable Terminal 3 ledger write is represented by a local audit row and - receipt hash; a real tenant ledger contract can replace that boundary later. -- Stripe runs in simulator mode unless a test-mode `STRIPE_SECRET_KEY` and - destination map are configured. -- Browser visual verification was HTTP/build verified here; the `agent-browser` - CLI was not available on PATH in this environment. -- `npm audit` still reports framework/SDK dependency advisories that require - breaking upgrades or upstream fixes: Next major upgrade path, `ws` via - `ethers`/`@terminal3/t3n-sdk`, and Next-bundled PostCSS. The safe direct - updates (`tsx`, root `postcss`, ESLint, Anthropic SDK) have been applied. diff --git a/scratch/check_db.ts b/scratch/check_db.ts deleted file mode 100644 index f6a0255..0000000 --- a/scratch/check_db.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { PrismaClient } from "@prisma/client"; - -const prisma = new PrismaClient(); - -async function main() { - const lcs = await prisma.letterOfCredit.findMany(); - console.log("Current Letters of Credit in Database:"); - console.log(JSON.stringify(lcs, null, 2)); -} - -main() - .catch(console.error) - .finally(() => prisma.$disconnect()); diff --git a/scratch/create_account.js b/scratch/create_account.js deleted file mode 100644 index a5177a0..0000000 --- a/scratch/create_account.js +++ /dev/null @@ -1,19 +0,0 @@ -const Stripe = require('stripe'); -const stripe = Stripe('sk_test_51TCzXF7xB4vKGIWjTRboO0GAetn3i7cCGei0revMGqignupsm6lIvynlEifZA3yBINFJ2jsop6QlPu83bljP0pjl00yv11OQnk'); - -async function createAccount() { - try { - const account = await stripe.accounts.create({ - type: 'custom', - country: 'AU', - capabilities: { - transfers: { requested: true }, - }, - }); - console.log("SUCCESS_ACCOUNT_ID=" + account.id); - } catch (e) { - console.error(e); - } -} - -createAccount(); diff --git a/scratch/test_transfer.js b/scratch/test_transfer.js deleted file mode 100644 index f168f0b..0000000 --- a/scratch/test_transfer.js +++ /dev/null @@ -1,17 +0,0 @@ -const Stripe = require('stripe'); -const stripe = Stripe('sk_test_51TCzYR8iGRmogjncaXxCNpOVDqVZAPdr9FD1osFPfyyOLYjDiYrvxbpz4MOgCYLL4nb0uzwAz6ANaOfpxRTAaUFA00nWSQprmy'); - -async function testTransfer() { - try { - const transfer = await stripe.transfers.create({ - amount: 1000, - currency: 'aud', - destination: 'acct_1TirxA8iGRP26vX8' - }); - console.log("SUCCESS:", transfer.id); - } catch (e) { - console.error("ERROR:", e.message); - } -} - -testTransfer(); diff --git a/videoscript.md b/videoscript.md deleted file mode 100644 index e3468b4..0000000 --- a/videoscript.md +++ /dev/null @@ -1,62 +0,0 @@ -# Demo Video Script & Presentation Guide - -This document contains case study data, visual cues, a relative flowchart, and a word-for-word voiceover script for the Trade Finance Escrow Agent hackathon demo. - ---- - -## 1. Industry Context & Case Studies - -When presenting the problem statement, highlight these real-world statistics to show the significance of the project: - -* **Inefficient Processing**: Letters of Credit secure **$10 Trillion** in trade annually (*ICC*), yet manual audits take **10 to 14 days** to clear. -* **Documentation Errors**: Over **70% of physical transport documents** (Bills of Lading) contain discrepancies on first presentation, causing cargo demurrage fees at ports. -* **The TEE Advantage**: Standard Web2 software agents expose Stripe/banking API keys in standard database environments. Moving the signature verification, LLM parsing, and payment release logic into a **Trusted Execution Environment (TEE)** ensures that even if the host server is compromised, hot keys and financial execution remain fully isolated. - ---- - -## 2. Interactive Architecture Flowchart - -Below is the visual topology diagram of the secure transaction lifecycle: - -![Trade Finance Secure Architecture Flowchart](./trade_finance_architecture_flowchart.png) - -### Cryptographic Trust Boundaries (Mermaid Flowchart) - -```mermaid -graph TD - subgraph ClientZone ["1. Client Zone (Browser)"] - A[Buyer Wallet] -- Signs EIP-191 Delegation --> B[Opaque buyerPlaceholder ID] - end - - subgraph TeeBoundary ["2. TEE Enclave (Private Execution)"] - direction TB - C[Agent DID Authenticate] --> D[Gemini Webhook Bol Parser] - D --> E[Deterministic TS Policy Engine] - E -- Checks Port Match & Max Cap --> F[Signature Verification] - end - - subgraph SettlementZone ["3. Settlement & Ledger"] - G[Stripe Connect Payout] --> H[Immutable SHA-256 Audit Ledger] - end - - B -- Submits Credential --> C - F -- Authorized Release --> G -``` - ---- - -## 3. Word-for-Word Voiceover Script - -*Read this script at a steady, professional pace. Match the spoken lines to the corresponding UI interactions on screen.* - -### Introduction (0:00 - 0:40) -> *"Hello, everyone. Today, I'm excited to present our Autonomous Trade Finance Escrow Agent, powered by the Terminal 3 Agent Auth SDK. In global commerce, Letters of Credit secure over ten trillion dollars in trade, yet they remain slow, manual, and exposed to severe security risks. Standard software agents automate these workflows but require direct access to hot API keys and private bank details. If the host server is hacked, your funds are gone. Our solution moves the entire execution boundary into a hardware-isolated Trusted Execution Environment."* - -### Architecture & Trust Boundaries (0:40 - 1:20) -> *"Let's examine how we achieve this. Our architecture is split into three strict security zones. In the Client Zone, the buyer signs a contract delegation credential in their browser using their wallet. This creates a secure, EIP-191 signed capability represented by an opaque placeholder. The agent never sees the buyer's private key. In the TEE Enclave, the agent operates in complete isolation. When port cargo webhooks arrive, the agent uses Google Gemini to parse the unstructured Bill of Lading, feeding it into a deterministic TypeScript policy engine. The LLM acts purely as an advisor; the code remains the sole validator."* - -### Happy Path Demonstration (1:20 - 2:20) -> *"Let's demonstrate the happy path. We'll select our pre-seeded Rotterdam Letter of Credit. When I click 'Authorize Escrow', the agent intercepts the buyer's delegation and places a manual-capture Stripe hold on the buyer's card. Next, we simulate the port delivery. The webhook fires, the agent authenticates its registered DID, runs the policy checks, and inside the TEE boundary, resolves the payment to the exporter. As you can see, the transaction settles instantly. In the visual inspector side drawer, we can see the exact cryptographic proofs, including the verified buyer signatures and the Stripe Connect transfer receipt."* - -### Edge Cases & Zero-Configuration (2:20 - 3:30) -> *"Our project covers two key advanced edge cases. First is Zero-Configuration Connect: if a new exporter is introduced without a pre-mapped destination, the agent dynamically provisions a test-mode Custom Connect account on Stripe and executes the transfer seamlessly, caching the ID locally. Second is Policy Enforcement: if the cargo is delivered to the wrong port or exceeds the value cap, the policy gate immediately denies the release. In the drawer checklist, judges can inspect exactly which condition failed. Finally, every single state transition is compiled into a block, hashed via SHA-256, and written to our immutable audit ledger. This ensures total auditability for compliance officers. Thank you."* diff --git a/walkthrough.md b/walkthrough.md new file mode 100644 index 0000000..bef8c75 --- /dev/null +++ b/walkthrough.md @@ -0,0 +1,90 @@ +# 🏆 Judge Walkthrough & Demo Script + +Welcome to the **Autonomous TEE Trade Finance Agent** demo guide. This document serves as a step-by-step guide for hackathon judges to verify the project, and a recording script for your demo video. + +--- + +## ⚡ Setup Check (For Judges) +Make sure the server is running locally and the Stripe dashboard is open in Test Mode. +* **App Console**: `http://localhost:3000` +* **Stripe Payments**: `https://dashboard.stripe.com/test/payments` +* **Stripe Connected Accounts**: `https://dashboard.stripe.com/test/connect/accounts` + +--- + +## 🎙️ Demo Script & Storyboard + +This script aligns your screen recording with the security events happening under the hood. + +### **Step 1: Introduction & Dashboard Overview** +* **Visual**: Show the running dashboard at `http://localhost:3000`. Hover over the three sections: **Letters of Credit**, the **TEE Agent Logs**, and the **Cryptographic Audit Ledger**. +* **Voiceover / Script**: + > *"Welcome. This is our Autonomous Trade Finance Agent. It automates Letter of Credit (LC) escrows while guaranteeing that sensitive payment keys and destination accounts are shielded inside a Trusted Execution Environment (TEE). Let's walk through our 4-click happy path."* + +--- + +### **Step 2: Escrow Hold Authorization (Click 1 & 2)** +* **Visual**: Click on the first Letter of Credit card (Rotterdam, Acme Textiles). Click the emerald **Authorize Escrow** button. +* **Voiceover / Script**: + > *"First, we select the Rotterdam LC. Clicking 'Authorize Escrow' simulates the buyer signing a delegation credential in their browser. Under the hood, the Terminal 3 SDK mints an EIP-191 signed credential and places an authorization hold on the buyer's card."* + +* **Visual**: Switch tabs to the **Stripe Dashboard (Payments)**. Refresh to show the new **AUD $25,000.00** payment in **Uncaptured** state. +* **Voiceover / Script**: + > *"If we check our Stripe Test Dashboard, we see a new $25,000 AUD payment created. It is marked as 'Uncaptured'. The funds are locked in escrow, and have not yet been released to the exporter."* + +--- + +### **Step 3: Simulate Port Delivery & TEE Execution (Click 3)** +* **Visual**: Switch back to the app console. Click **Simulate Port Delivery**. Point to the streaming logs inside the TEE panel. +* **Voiceover / Script**: + > *"Next, we click 'Simulate Port Delivery' to fire a mock logistics webhook. Watch the live agent logs stream: first, the agent's DID identity is verified. Second, Google Gemini parses the unstructured logistics webhook. Third, the deterministic policy gate checks the delivery details against contract terms. Finally, the agent executes the payout."* + +* **Visual**: Switch to the **Stripe Dashboard (Payments)**. Show that the payment has transitioned to **Succeeded**. Then switch to the **Connected Accounts** tab and open `acct_1TirxA8iGRP26vX8` to show the transfer. +* **Voiceover / Script**: + > *"In our Stripe dashboard, refreshing the payment shows it has transitioned to 'Succeeded'. Looking at Connected Accounts, the payout has been successfully transferred directly to the exporter's connected account on-the-fly. The agent did this without exposing any secret API keys to the client or the database."* + +--- + +### **Step 4: Inspect Enclave Proof & Hash Chain (Click 4)** +* **Visual**: Scroll down to the **Audit Ledger** at the bottom of the app console. Click the **Inspect** button next to the `SETTLED` state transition. +* **Visual**: Toggle the drawer to the **Raw Cryptography Payload** tab, highlighting the JSON and signatures. +* **Voiceover / Script**: + > *"Finally, we click 'Inspect' on the ledger row. The Cryptographic Drawer displays the EIP-191 signatures, the parsed LLM advice, and the raw receipt hash generated inside the enclave. Every step is signed by the Agent DID, creating an immutable audit trail."* + +--- + +### **Step 5: CLI Verification (Optional / Extra)** +* **Visual**: Open the terminal window next to the browser and run the audit verification tool: + ```bash + npm run audit:verify + ``` +* **Voiceover / Script**: + > *"We can verify the integrity of this audit trail on the command line. Running our audit verification tool computes a rolling SHA-256 hash chain over the database rows, validating that no database tampering occurred outside the enclave."* + +--- + +### **Step 6: Policy Denials (Port Mismatch & Over Value)** +* **Visual**: Go back to the dashboard. Select the **Port Mismatch** LC (required port Hamburg, cargo targeted Rotterdam) or the **Over Value** LC (exceeds cap). Click **Authorize** and then **Simulate Port Delivery**. +* **Visual**: Point out the orange logs showing the policy gate rejecting the release and marking it as **DENIED**. +* **Voiceover / Script**: + > *"To show the safety of our policy gate, let's select the Port Mismatch LC. When we simulate delivery, the deterministic policy engine rejects the release because the target port does not match contract terms. No Stripe capture or transfer is executed, and a 'DENIED' receipt is written to the ledger."* + +--- + +### **Step 7: Conclusion** +* **Visual**: Show the full dashboard interface. +* **Voiceover / Script**: + > *"By combining the Terminal 3 Agent Auth SDK for secure key handling, Google Gemini for document parsing, and deterministic code for policy execution, we have built a secure, fully automated, and auditable trade finance pipeline. Thank you."* + +--- + +## 🛠️ Summary of Interactive Features to Highlight + +| Feature | What It Demonstrates | How to Show It | +| --- | --- | --- | +| **TEE Agent Logs** | Real-time enclave execution | Watch the logs stream in green when you click "Simulate Port Delivery". | +| **Live Stripe Hook** | Integration with production APIs | Show the PaymentIntent change from *Uncaptured* to *Succeeded* in Stripe. | +| **Stripe Connect** | Shielded destination routing | Show the Transfer reaching the Connected Account (`acct_...`). | +| **Cryptographic Drawer** | Zero-trust proofs and signatures | Click "Inspect" to show the raw JSON, agent signatures, and enclaves receipt hashes. | +| **Heuristics / Policy Split** | LLM parsing with code-level safety | Show the LLM's explanation in the drawer alongside the strict code rules. | +| **Audit CLI** | Git-style rolling block hash chain | Run `npm run audit:verify` in the terminal to show chain integrity validation. | From d674970a688c4c0dd30a72d1c60a8a464d2dafd7 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Fri, 19 Jun 2026 17:24:48 +0530 Subject: [PATCH 2/4] chore: change database provider to postgresql for Vercel + Neon --- prisma/schema.prisma | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 6ea7723..5ab7285 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -14,7 +14,7 @@ generator client { } datasource db { - provider = "sqlite" + provider = "postgresql" url = env("DATABASE_URL") } From 957bbbef9a594c904577d8dcdde821acdfc526b9 Mon Sep 17 00:00:00 2001 From: Divyansh Date: Fri, 19 Jun 2026 17:26:32 +0530 Subject: [PATCH 3/4] chore: update Dockerfile, README, and seed file for PostgreSQL/Neon migration --- Dockerfile | 4 ---- README.md | 17 +++++------------ prisma/seed.ts | 1 + 3 files changed, 6 insertions(+), 16 deletions(-) diff --git a/Dockerfile b/Dockerfile index d5a469f..ffac6e0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,10 +28,6 @@ COPY images ./images/ RUN npx prisma generate RUN npm run build -# Create a directory to store the persistent SQLite database -RUN mkdir -p /app/data -ENV DATABASE_URL="file:/app/data/dev.db" - # Expose Next.js port EXPOSE 3000 ENV PORT 3000 diff --git a/README.md b/README.md index 25142a7..105c2a2 100644 --- a/README.md +++ b/README.md @@ -118,10 +118,11 @@ Copy the example environment file: ```bash cp .env.example .env.local ``` +Configure your `DATABASE_URL` in `.env.local` to point to a PostgreSQL database (e.g., Neon or Supabase). *Your registered Agent DID (`did:t3n:c9f6b88a...`) and private keys are pre-configured for instant sandbox testing.* ### 3. Initialize Database -Push schema and seed initial Letters of Credit: +Push the schema and seed the initial Letters of Credit to your PostgreSQL database: ```bash npm run db:push ``` @@ -152,7 +153,7 @@ npm run audit:verify ## 🐳 Run with Docker -You can package and run the application in a stateful Docker container with local SQLite database persistence. +You can package and run the application in a Docker container, passing your PostgreSQL configuration. ### 1. Build the Image ```bash @@ -160,18 +161,10 @@ docker build -t trade-finance-agent . ``` ### 2. Run the Container -Create a local `data` directory to mount inside the container. This preserves your SQLite database files across container restarts. +Make sure your `.env.local` file contains the correct `DATABASE_URL` pointing to your Neon/PostgreSQL database. -**On Windows (PowerShell or Cmd):** ```bash -mkdir data -docker run -d -p 3000:3000 -v "%cd%/data:/app/data" --env-file .env.local trade-finance-agent -``` - -**On macOS / Linux / Bash:** -```bash -mkdir -p data -docker run -d -p 3000:3000 -v "$(pwd)/data:/app/data" --env-file .env.local trade-finance-agent +docker run -d -p 3000:3000 --env-file .env.local trade-finance-agent ``` --- diff --git a/prisma/seed.ts b/prisma/seed.ts index 7d97116..1282abf 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -23,6 +23,7 @@ async function main() { // Idempotent reseed: clear children first (FK order), then parents. await prisma.auditEntry.deleteMany(); await prisma.billOfLading.deleteMany(); + await prisma.escrowTransfer.deleteMany(); await prisma.contractTerms.deleteMany(); await prisma.letterOfCredit.deleteMany(); From c6cfab86933f38b05525bc4684f836264a586e1a Mon Sep 17 00:00:00 2001 From: Divyansh Date: Fri, 19 Jun 2026 17:52:50 +0530 Subject: [PATCH 4/4] ci: add postgres service container to GitHub Actions workflow --- .env.example | 5 ++--- .github/workflows/verify.yml | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index d97d556..68ca526 100644 --- a/.env.example +++ b/.env.example @@ -6,9 +6,8 @@ # Use any 32-byte hex key for testnet: `openssl rand -hex 32`, prefixed 0x. T3N_AGENT_PRIVATE_KEY=0x... -# Prisma + SQLite. Also add this to a root .env file so the Prisma CLI -# (db push / seed / studio) can read it. Path is relative to prisma/schema.prisma. -DATABASE_URL="file:./dev.db" +# Prisma + PostgreSQL. Copy to .env.local/root .env and replace with your Neon database URL. +DATABASE_URL="postgresql://neondb_owner:password@localhost:5432/neondb?sslmode=disable" # Demo BUYER signer (Step 3). In production the buyer signs the delegation # credential in their own wallet; this key stands in for the demo. SERVER-ONLY. diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 4cb3b33..a71369f 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -10,6 +10,24 @@ jobs: verify: runs-on: ubuntu-latest + services: + postgres: + image: postgres:15 + env: + POSTGRES_DB: neondb + POSTGRES_USER: neondb_owner + POSTGRES_PASSWORD: password + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + env: + DATABASE_URL: "postgresql://neondb_owner:password@localhost:5432/neondb?sslmode=disable" + steps: - uses: actions/checkout@v4