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
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ RUN pnpm install --frozen-lockfile
COPY . .
ARG NEXT_PUBLIC_FABLE_API_URL=/fable-api
ARG FABLE_INTERNAL_API_URL=http://api
ARG NEXT_PUBLIC_FORGE_BANK_LABEL="Xtradot Bank"
ENV NEXT_PUBLIC_FABLE_API_URL=$NEXT_PUBLIC_FABLE_API_URL \
FABLE_INTERNAL_API_URL=$FABLE_INTERNAL_API_URL \
NEXT_PUBLIC_FORGE_BANK_LABEL=$NEXT_PUBLIC_FORGE_BANK_LABEL \
FABLE_STANDALONE=1 \
NEXT_TELEMETRY_DISABLED=1
RUN pnpm build
Expand Down
172 changes: 172 additions & 0 deletions api/scripts/mock_bank.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""A local stand-in for the Xtradot Bank sandbox, for running the demo off the cluster.

The real sandbox only answers from inside the Forge cluster. This follows the
platform guide's contract closely enough for the demo (section 5): the response
envelope, name enquiry before transfer, intrabank settling in the call and
interbank pending then settling after about 5 seconds, fees and VAT read from
the response, idempotency keys, and the guide's trigger amounts (.01 refused for
funds, .02 times out and is reversed after 30 seconds, .03 pending for 2
minutes). It is not the bank: anything shown from it must be called simulated.

python scripts/mock_bank.py # listens on 0.0.0.0:9000, base path /v1
"""
import json
import os
import sys
import time
import uuid

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import uvicorn # noqa: E402
from fastapi import FastAPI, Request # noqa: E402
from fastapi.responses import JSONResponse # noqa: E402

from services.forge_bridge import BANKS, BENEFICIARIES, TEAM_ACCOUNTS, XTRADOT_NIP # noqa: E402

app = FastAPI(title="Xtradot Bank (simulated)")
DORMANT, FROZEN, PND = "0987654399", "0123987098", "0123987099"
_transfers: dict[str, dict] = {}
_replies: dict[str, tuple[int, dict]] = {}
_enquiries: dict[str, dict] = {}


def ok(data, status=200):
return JSONResponse({"status": "success", "message": "OK", "data": data, "meta": None,
"request_id": f"req_{uuid.uuid4().hex[:8]}"}, status_code=status)


def err(status, code, message, field=None):
body = {"code": code, "message": message}
if field:
body["field"] = field
return JSONResponse({"status": "error", "error": body, "request_id": f"req_{uuid.uuid4().hex[:8]}"},
status_code=status)


def charges(amount: float, intra: bool) -> dict:
if intra:
return {"fee": 0.0, "vat": 0.0, "stamp_duty": 0.0, "total_debit": round(amount, 2)}
fee = 10.0 if amount <= 5_000 else 25.0 if amount <= 50_000 else 50.0
vat = round(fee * 0.075, 2)
return {"fee": fee, "vat": vat, "stamp_duty": 0.0, "total_debit": round(amount + fee + vat, 2)}


def cents(amount: float) -> int:
return round(amount * 100) % 100


def state(ref: str) -> dict | None:
t = _transfers.get(ref)
if not t:
return None
age = time.time() - t["at"]
if t["mode"] == "timeout":
status = "reversed" if age > 30 else "pending"
elif t["mode"] == "slow":
status = "successful" if age > 120 else "pending"
elif t["mode"] == "intra":
status = "successful"
else:
status = "successful" if age > 5 else "pending"
return {"reference": ref, "status": status, "amount": t["amount"], **charges(t["amount"], t["mode"] == "intra")}


@app.middleware("http")
async def key_required(request: Request, call_next):
if not request.headers.get("x-api-key"):
return err(401, "UNAUTHORIZED", "Missing x-api-key.")
return await call_next(request)


@app.get("/v1/accounts/{account}/balance")
def balance(account: str):
if account not in TEAM_ACCOUNTS:
return err(404, "ACCOUNT_NOT_FOUND", "No such account.")
return ok({"account_number": account, "balance": TEAM_ACCOUNTS[account][1], "currency": "NGN"})


def _enquire(account: str, intra: bool):
if account in (DORMANT,):
return err(422, "ACCOUNT_DORMANT", "The beneficiary account is dormant.")
if account in (FROZEN,):
return err(422, "BENEFICIARY_FROZEN", "The beneficiary account is frozen.")
holder = BENEFICIARIES.get(account)
if holder is None and account in TEAM_ACCOUNTS:
holder = (TEAM_ACCOUNTS[account][0], "Xtradot Bank")
if not holder:
return err(404, "ACCOUNT_NOT_FOUND", "No such account.", "account_number")
if intra != (BANKS.get(holder[1]) == XTRADOT_NIP):
return err(400, "INVALID_REQUEST", "Use /intra for Xtradot Bank accounts and /interbank for other banks.")
ref = f"ne_{uuid.uuid4().hex[:12]}"
_enquiries[ref] = {"account": account, "at": time.time(), "used": False}
return ok({"account_number": account, "account_name": holder[0], "bank_name": holder[1], "name_enquiry_ref": ref})


@app.post("/v1/transfers/intra/name-enquiry")
async def intra_enquiry(request: Request):
return _enquire(str((await request.json()).get("account_number", "")), True)


@app.post("/v1/transfers/interbank/name-enquiry")
async def interbank_enquiry(request: Request):
return _enquire(str((await request.json()).get("account_number", "")), False)


async def _transfer(request: Request, intra: bool):
key = request.headers.get("idempotency-key")
if not key:
return err(400, "INVALID_REQUEST", "Idempotency-Key is required.", "Idempotency-Key")
if key in _replies:
status, body = _replies[key]
reply = JSONResponse(body, status_code=status)
reply.headers["Idempotent-Replayed"] = "true"
return reply
body = await request.json()
ref, amount, enq = body.get("reference", ""), float(body.get("amount", 0)), _enquiries.get(body.get("name_enquiry_ref", ""))
if not enq or enq["account"] != body.get("destination_account"):
reply = err(409, "NAME_ENQUIRY_MISMATCH", "Name enquiry missing or for another account.")
elif enq["used"]:
reply = err(409, "DUPLICATE_REQUEST", "This name enquiry reference was already used.")
elif time.time() - enq["at"] > 600:
reply = err(409, "NAME_ENQUIRY_EXPIRED", "The name enquiry is older than 10 minutes.")
elif ref in _transfers:
reply = err(409, "DUPLICATE_REQUEST", "This reference was already used.")
elif cents(amount) == 1:
reply = err(402, "INSUFFICIENT_FUNDS", "Balance below amount plus charges.")
else:
enq["used"] = True
mode = "intra" if intra else "timeout" if cents(amount) == 2 else "slow" if cents(amount) == 3 else "normal"
_transfers[ref] = {"mode": mode, "at": time.time(), "amount": amount}
if mode == "timeout":
reply = err(504, "TIMEOUT", "Outcome unknown: requery, never resend.")
else:
reply = ok(state(ref), 201 if intra else 202)
_replies[key] = (reply.status_code, json.loads(reply.body))
return reply


@app.post("/v1/transfers/intra")
async def intra(request: Request):
return await _transfer(request, True)


@app.post("/v1/transfers/interbank")
async def interbank(request: Request):
return await _transfer(request, False)


@app.post("/v1/transfers/interbank/requery")
async def requery(request: Request):
found = state(str((await request.json()).get("reference", "")))
return ok(found) if found else err(404, "NOT_FOUND", "No such transfer.")


@app.get("/v1/transfers/{reference}")
def transfer_status(reference: str):
found = state(reference)
return ok(found) if found else err(404, "NOT_FOUND", "No such transfer.")


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("MOCK_BANK_PORT", "9000")), log_level="warning")
42 changes: 42 additions & 0 deletions deploy/local/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Fallback demo on one laptop, for when the team11 cluster cannot be reached.
# Same API, sandbox app, console and bank bridge as the cluster; the Xtradot
# Bank is replaced by a local stand-in (api/scripts/mock_bank.py) that follows
# the platform guide's rules. The bank panel is labelled "simulated".
#
# docker compose -f deploy/local/docker-compose.yml up --build
# open http://localhost:8080/dashboard/login (team11@fable.ng / see FORGE_CONSOLE_PASSWORD)
services:
mock-bank:
build: ../../api
command: ["python", "scripts/mock_bank.py"]
environment:
MOCK_BANK_PORT: "9000"
healthcheck:
disable: true # the image's check is for the API port

api:
build: ../../api
depends_on: [mock-bank]
environment:
PORT: "8010"
ENVIRONMENT: development
FABLE_SESSION_SECRET: local-demo-only-not-a-secret
FABLE_DB_PATH: /tmp/fable.db
FORGE_BANK_BASE_URL: http://mock-bank:9000/v1
GATEWAY_KEY: local
FORGE_BRIDGE_INSTITUTION: xtradot
FORGE_CONSOLE_EMAIL: team11@fable.ng
FORGE_CONSOLE_PASSWORD: ${FORGE_CONSOLE_PASSWORD:-fable-demo-2026}

web:
build:
context: ../..
args:
FABLE_INTERNAL_API_URL: http://api:8010
NEXT_PUBLIC_FORGE_BANK_LABEL: Xtradot Bank (simulated)
depends_on: [api]
environment:
FORGE_BRIDGE: "1"
FABLE_INTERNAL_API_URL: http://api:8010
ports:
- "8080:8080"
21 changes: 21 additions & 0 deletions docs/DEPLOY-FORGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,24 @@ kubectl rollout undo deployment/app
| The site loads but every call fails | `api` is not Ready, or the site was built for another API address | `kubectl get pods`; rebuild the web image |
| 502 or 404 on the public address | Service renamed, or the route is not open yet | The published Service must be `app`, port 80; ask the platform team to open the route |
| 429 from the bank | More than 60 requests a minute, shared with the model | Slow down and cache |

## Laptop fallback (cluster unreachable)

If the cluster can't be reached at demo time, run the same app, console and
bank bridge on one laptop. The Xtradot Bank is replaced by a local stand-in
(`api/scripts/mock_bank.py`) that follows the guide's rules: name enquiry,
fees and VAT in the response, interbank pending then paid, `.01` refused for
funds, `.02` times out and is queried (never resent), `.03` stays pending.
The bank panel reads **Xtradot Bank (simulated)**. Say so when presenting.

```bash
git pull
docker compose -f deploy/local/docker-compose.yml up --build
```

Open http://localhost:8080/dashboard/login and sign in as `team11@fable.ng`
with password `fable-demo-2026` (or set `FORGE_CONSOLE_PASSWORD` before `up`).
Then open the sandbox app at http://localhost:8080/demo/xtradot.

Data lives in the containers and is reseeded on every start. Stop with Ctrl+C,
then `docker compose -f deploy/local/docker-compose.yml down`.
5 changes: 4 additions & 1 deletion src/components/demo/BankSettlement.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import { Badge, Card, DetailRow, Eyebrow, Notice } from "@/components/app-kit";
import { API_BASE } from "@/lib/fable/base";
import { authHeaders } from "@/lib/fable/tenant";

// "Xtradot Bank (simulated)" when the local stand-in bank is used instead of the real sandbox.
const BANK_LABEL = process.env.NEXT_PUBLIC_FORGE_BANK_LABEL || "Xtradot Bank";

/**
* What the bank did with a transfer Fable let through.
*
Expand Down Expand Up @@ -94,7 +97,7 @@ export function BankSettlement({
<div className="mb-2 flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<Bank size={18} weight="fill" className="text-brand" />
<Eyebrow>Xtradot Bank</Eyebrow>
<Eyebrow>{BANK_LABEL}</Eyebrow>
</div>
<Badge tone={TONE[data.state] ?? "neutral"}>{LABEL[data.state] ?? data.state}</Badge>
</div>
Expand Down
Loading