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
4 changes: 4 additions & 0 deletions api/agents/ghost/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,10 @@ def _debit_if_sandbox(container: dict, user_id: str) -> None:
transaction_id=container.get("transaction_id") or container["ghost_id"],
reference=f"ghost-release:{container['ghost_id']}",
)
if container.get("transaction_id"):
from services import forge_bridge

forge_bridge.mirror_later(container["transaction_id"])


def release_ghost(ghost_id: str, user_id: str, stepup_token: str | None = None) -> dict:
Expand Down
4 changes: 4 additions & 0 deletions api/routers/shield.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,10 @@ def _replayed():
payload.user_id, transaction["amount"], institution_id,
transaction_id=transaction_id, reference=f"txn:{transaction_id}",
)
# A bank connected to the Xtradot sandbox also gets the transfer itself.
from services import forge_bridge

forge_bridge.mirror_later(transaction_id, recipient_bank_code=transaction.get("recipient_bank_code"))

return ShieldAnalyzeResponse(
risk_score=result["risk_score"],
Expand Down
3 changes: 3 additions & 0 deletions api/routers/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ def approve(txid: str, payload: ApproveRequest, request: Request):
)

debit(payload.user_id, row["amount"], institution_id, transaction_id=txid, reference=f"txn-approve:{txid}")
from services import forge_bridge

forge_bridge.mirror_later(txid)

# Verified and sent: the customer proved it was them, so this transfer now
# teaches the baseline (recipient, device, amount, hour) for next time.
Expand Down
146 changes: 146 additions & 0 deletions api/services/forge_bridge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""The bank bridge: the sandbox demo, connected to the Xtradot Bank sandbox.

The sandbox app (the demo bank customers use) works on Fable's own simulated
ledger. For one institution, named in FORGE_BRIDGE_INSTITUTION, every transfer
that money actually moves on (a pass, a verified flag, a released hold) is also
sent to the Xtradot Bank sandbox, from the customer's own account there. The
app is unchanged; the bank's answer (reference, fee, VAT, stamp duty, status)
is then read from /v1/forge/transfers/{transaction id}.

Sending happens off the request path, once per transfer, through the same
claim-then-send state machine as the rest of the Forge integration
(services/forge_transfers.py): a lost answer is only ever queried, never resent.
"""
import logging
import os
from concurrent.futures import ThreadPoolExecutor

from core.db import cursor, row_to_dict
from services import forge_transfers

logger = logging.getLogger("fable.forge")

XTRADOT_NIP = "000014"

# The sandbox's banks (platform guide, section 5.4): name -> NIP code.
BANKS = {
"Xtradot Bank": "000014",
"GTBank": "000013",
"Zenith Bank": "000015",
"First Bank of Nigeria": "000016",
"UBA": "000004",
"Wema Bank": "000017",
"OPay": "100004",
"Moniepoint MFB": "090405",
"Kuda MFB": "090267",
"PalmPay": "100033",
}

# The team's own accounts at Xtradot Bank. The demo's customers use the account
# number as their reference, so a customer maps straight to their account.
TEAM_ACCOUNTS = {
"0123456789": ("Adaeze Chiamaka Okonkwo", 1_500_000),
"0123456790": ("Babatunde Olumide Adeyemi", 5_000_000),
"0123456791": ("Musa Ibrahim Abdullahi", 250_000),
"0123456792": ("Efosa Godwin Osagie", 40_000),
"0123456793": ("Mama Nkechi Provisions Ltd", 12_000_000),
}

# The sandbox's beneficiaries: account -> (holder, bank name).
BENEFICIARIES = {
"0987654321": ("Ngozi Adaobi Eze", "Xtradot Bank"),
"0987654322": ("Aisha Hauwa Bello", "Xtradot Bank"),
"0987654399": ("Obinna Kelechi Okafor", "Xtradot Bank"),
"0123987001": ("Chukwuemeka Ifeanyi Nwosu", "GTBank"),
"0123987099": ("Garba Sani Danjuma", "GTBank"),
"0123987002": ("Funmilayo Abiola Ogunleye", "Zenith Bank"),
"0123987003": ("Zainab Halima Yusuf", "First Bank of Nigeria"),
"0123987004": ("Tamunotonye Briggs", "UBA"),
"0123987098": ("Blessing Oghenekaro Edeh", "Wema Bank"),
"8031234506": ("Ifeoluwa Grace Adebayo", "OPay"),
"8051234507": ("Iya Bisi Foods Enterprises", "Moniepoint MFB"),
}

_pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="fable-bridge")


def institution() -> str:
return os.getenv("FORGE_BRIDGE_INSTITUTION", "").strip()


def enabled_for(institution_id: str | None) -> bool:
target = institution()
return bool(target) and institution_id == target


def bank_code(account: str | None, bank: str | None, code: str | None = None) -> str | None:
"""The NIP code for a recipient: as sent, else from the bank's name, else
from the sandbox's own beneficiary list."""
if code and code in BANKS.values():
return code
if bank and bank in BANKS:
return BANKS[bank]
if account in BENEFICIARIES:
return BANKS[BENEFICIARIES[account][1]]
if account in TEAM_ACCOUNTS:
return XTRADOT_NIP
return None


def _source_account(user_id: str) -> str | None:
with cursor() as cur:
cur.execute("SELECT external_ref FROM customers WHERE id = ?", (user_id,))
row = cur.fetchone()
ref = row["external_ref"] if row else None
return ref if ref in TEAM_ACCOUNTS else None


def mirror(transaction_id: str, *, recipient_bank_code: str | None = None) -> dict | None:
"""Send one decided, money-moving transfer to the bank, once. Returns the
transfer's row, or None when this institution is not bridged."""
with cursor() as cur:
cur.execute("""SELECT id, user_id, institution_id, amount, recipient_account, recipient_bank,
recipient_name, narration, action_taken FROM transactions WHERE id = ?""",
(transaction_id,))
txn = row_to_dict(cur.fetchone())
if not txn or not enabled_for(txn["institution_id"]):
return None
existing = forge_transfers.get(transaction_id)
if existing:
return existing

source = _source_account(txn["user_id"])
code = bank_code(txn["recipient_account"], txn["recipient_bank"], recipient_bank_code)
row = forge_transfers.record(
transfer_id=transaction_id, institution_id=txn["institution_id"], user_id=txn["user_id"],
source_account=source or "unknown", destination_account=txn["recipient_account"] or "unknown",
destination_bank_code=code, intra=code == XTRADOT_NIP, recipient_name=txn["recipient_name"],
amount=float(txn["amount"]), narration=(txn["narration"] or "Fable sandbox")[:100],
name_enquiry_ref=None, action="PASS")
if not source or not code or not txn["recipient_account"]:
reason = ("This customer has no account at Xtradot Bank." if not source
else "The recipient's bank is not one of the sandbox's banks.")
forge_transfers._set(transaction_id, state="failed", last_error=reason) # noqa: SLF001
return forge_transfers.get(transaction_id)
return forge_transfers.execute(row["id"], poll_attempts=6, poll_wait=2.0)


def mirror_later(transaction_id: str, *, recipient_bank_code: str | None = None) -> None:
"""Queue the send off the request path. The decision has already been
returned; the bank's answer is read later by the app."""
try:
with cursor() as cur:
cur.execute("SELECT institution_id FROM transactions WHERE id = ?", (transaction_id,))
row = cur.fetchone()
if not row or not enabled_for(row["institution_id"]):
return
except Exception: # noqa: BLE001 - the bridge must never affect a decision
return

def run():
try:
mirror(transaction_id, recipient_bank_code=recipient_bank_code)
except Exception as exc: # noqa: BLE001
logger.warning("Sending %s to the bank failed: %s", transaction_id, type(exc).__name__)

_pool.submit(run)
49 changes: 49 additions & 0 deletions api/services/forge_history.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Sixty days of believable history for the bank sandbox's five customers.

Fed through the same import the console uses (services/imports.py), so each
customer starts with real habits: who they pay, how much, at what hours. The
payees are the sandbox's own beneficiaries, so a saved recipient in the app is
an account the bank will accept. Deterministic: the same rows every time, with
dates counted back from today.
"""
import random
from datetime import datetime, timedelta, timezone

from services.forge_bridge import BENEFICIARIES, TEAM_ACCOUNTS

LAGOS = timezone(timedelta(hours=1))

# account -> (segment, usual payees, amount range, transfers in 60 days, usual hours)
HABITS = {
"0123456789": ("Salaried", ["0987654321", "0123987001", "8031234506"], (2_000, 30_000), 34, [8, 12, 18, 19, 20, 21]),
"0123456790": ("Trader", ["0123987002", "0123987004", "8051234507"], (50_000, 400_000), 46, [9, 10, 11, 13, 14, 15, 16]),
"0123456791": ("Salaried", ["0987654322", "0123987003"], (5_000, 40_000), 24, [7, 12, 17, 19, 20]),
"0123456792": ("Student", ["8031234506", "0987654321"], (1_000, 6_000), 30, [10, 13, 16, 20, 22, 23]),
"0123456793": ("Trader", ["8051234507", "0123987001", "0123987002"], (100_000, 1_500_000), 40, [8, 9, 10, 11, 14, 15]),
}


def customer_rows() -> list[dict]:
return [{"reference": account, "name": name, "segment": HABITS[account][0], "kind": "test",
"opening_balance": balance} for account, (name, balance) in TEAM_ACCOUNTS.items()]


def transaction_rows(now: datetime | None = None) -> list[dict]:
now = (now or datetime.now(timezone.utc)).astimezone(LAGOS)
rows = []
for account, (_segment, payees, (low, high), count, hours) in HABITS.items():
rng = random.Random(f"fable-forge-{account}")
for i in range(count):
day = rng.randint(1, 60)
when = (now - timedelta(days=day)).replace(hour=rng.choice(hours), minute=rng.randint(0, 59),
second=0, microsecond=0)
payee = rng.choice(payees)
name, bank = BENEFICIARIES[payee]
amount = round(rng.uniform(low, high) / 100) * 100
rows.append({
"customer_reference": account, "reference": f"HIST-{account}-{i:03d}", "amount": amount,
"occurred_at": when.isoformat(), "recipient_account": payee, "recipient_bank": bank,
"recipient_name": name, "channel": "mobile_app", "outcome": "completed", "city": "Lagos",
"country": "Nigeria",
})
return rows
55 changes: 48 additions & 7 deletions api/services/forge_seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,53 @@ def ensure_demo(raw_key: str | None = None, *, new_key: bool = False) -> dict:
return {"customers": made, "issued_key": issued}


def ensure_bank(institution_id: str, email: str, password: str) -> dict:
"""The bank connected to the Xtradot sandbox, set up as a bank would be:
a sandbox institution with an owner who signs in to the console, and its
customers and their past transfers brought in through the console's own
import. Safe to run again: the import skips what it already has."""
from core.utils import hash_password
from services import forge_history, imports

if not email or "@" not in email or len(password) < 12:
raise ValueError("The console login needs an email and a password of at least 12 characters.")
register_institution(institution_id, "Xtradot Bank", email)
with cursor() as cur:
cur.execute("UPDATE institutions SET mode = 'sandbox' WHERE institution_id = ?", (institution_id,))
cur.execute("SELECT 1 FROM admins WHERE email = ?", (email.lower(),))
if cur.fetchone() is None:
cur.execute("INSERT INTO admins (email, institution_id, hashed_password, role, name, active) "
"VALUES (?, ?, ?, 'owner', 'Team Fable', 1)",
(email.lower(), institution_id, hash_password(password)))
made = imports.import_batch(institution_id, "customers", forge_history.customer_rows(),
sandbox=True, actor="forge-seed")
history = forge_history.transaction_rows()
inserted = 0
for start in range(0, len(history), imports.MAX_ROWS_PER_BATCH):
inserted += imports.import_batch(institution_id, "transactions", history[start:start + imports.MAX_ROWS_PER_BATCH],
sandbox=True, actor="forge-seed")["inserted"]
for account in forge_history.HABITS:
customer = customers.get(institution_id, account)
if customer and not security.status(customer["id"]).get("pin_set"):
security.set_pin(customer["id"], DEMO_PIN, institution_id=institution_id)
return {"customers": made["inserted"], "history": inserted}


def ensure_from_env() -> bool:
"""At startup: set the demo up when its key is configured. Does nothing
otherwise, so only the Forge deployment ever creates this institution."""
"""At startup: set the demo up when it is configured. Does nothing
otherwise, so only the Forge deployment ever creates these institutions."""
did = False
raw = os.getenv("FORGE_DEMO_API_KEY", "").strip()
if not raw:
return False
ensure_demo(raw)
logger.info("The Forge demo institution is ready.")
return True
if raw:
ensure_demo(raw)
logger.info("The Forge demo institution is ready.")
did = True
bank = os.getenv("FORGE_BRIDGE_INSTITUTION", "").strip()
email = os.getenv("FORGE_CONSOLE_EMAIL", "").strip()
password = os.getenv("FORGE_CONSOLE_PASSWORD", "")
if bank and email and password:
result = ensure_bank(bank, email, password)
logger.info("The bank connected to the Xtradot sandbox is ready: %s customers and %s past transfers "
"imported.", result["customers"], result["history"])
did = True
return did
Loading
Loading