docs: sync from backend 19f7eb9, frontend 60ee6fb — Task #10 AML screening
This commit is contained in:
@@ -44,17 +44,17 @@ created: 2026-05-23
|
||||
### Dispute
|
||||
|
||||
> [!info] Definition
|
||||
> A formal complaint opened by either party when a deal goes wrong. Would create a three-way chat (buyer, seller, admin) and a `Dispute` document with a structured `timeline[]`, `evidence[]`, and `resolution`. Categories: `product_quality | delivery_delay | wrong_item | payment_issue | seller_behavior | other`. Outcomes: `refund | replacement | compensation | warning_seller | ban_seller | no_action`. See `backend/src/models/Dispute.ts` *(planned, not yet implemented)*.
|
||||
> A formal complaint opened by either party when a deal goes wrong. Creates a three-way chat (buyer, seller, admin) and a `Dispute` document with a structured `timeline[]`, `evidence[]`, and `resolution`. Categories: `product_quality | delivery_delay | wrong_item | payment_issue | seller_behavior | other`. Outcomes in the current model: `refund | replacement | compensation | warning_seller | ban_seller | no_action`. See `backend/src/models/Dispute.ts` and [[Dispute Flow]].
|
||||
|
||||
### Escrow
|
||||
|
||||
> [!info] Definition
|
||||
> The custodial period during which buyer funds are held by the platform (SHKeeper or the smart contract layer) after payment but before release to the seller. Escrow guarantees the seller will be paid if they deliver, and guarantees the buyer can be refunded if they do not. The defining feature of Amn.
|
||||
> The custodial period during which buyer funds are held by platform-controlled custody infrastructure after payment but before release to the seller. The current primary path uses Request Network pay-in, per-payment derived destinations, transaction-safety checks, and an internal funds ledger. Future custody decentralization is tracked in [[PRD - Decentralized Custody and Smart-Contract Escrow Roadmap]].
|
||||
|
||||
### Idempotency
|
||||
|
||||
> [!info] Definition
|
||||
> The property that the same request (identified by an idempotency key) can safely be retried without performing the underlying operation more than once. Critical for payment webhooks — SHKeeper may deliver the same webhook several times if it does not receive a 200 quickly. Amn enforces idempotency in `PaymentCoordinator` and at the model level via unique constraints on transaction hashes.
|
||||
> The property that the same request (identified by an idempotency key) can safely be retried without performing the underlying operation more than once. Critical for payment webhooks and release/refund confirmations. Amn enforces idempotency in `PaymentCoordinator`, Request Network delivery handling, pending-intent indexes, and ledger idempotency keys.
|
||||
|
||||
### JWT (Access / Refresh)
|
||||
|
||||
@@ -89,12 +89,12 @@ created: 2026-05-23
|
||||
### Pay-in
|
||||
|
||||
> [!info] Definition
|
||||
> Money flowing **into** escrow from the buyer. Recorded as `Payment.direction: "in"`. The buyer's choice of pay-in surface (SHKeeper invoice vs. Web3 wallet) is independent of how the payout will be sent.
|
||||
> Money flowing **into** escrow from the buyer. Recorded as `Payment.direction: "in"`. The current primary path is Request Network in-house checkout, with payment safety verified by webhook/reconciliation plus on-chain transaction checks.
|
||||
|
||||
### Pay-in Intent
|
||||
|
||||
> [!info] Definition
|
||||
> The pre-authorisation record created when a buyer commits to paying but the funds have not yet arrived on-chain. Holds the chosen amount, currency, expected wallet address (SHKeeper) or counterparty (DePay), and an expiry. Becomes a confirmed `Payment` once the chain or webhook confirms settlement.
|
||||
> The pre-authorisation record created when a buyer commits to paying but the funds have not yet arrived on-chain. Holds amount, currency, Request Network IDs/payment reference, in-house checkout metadata, and expected destination. Becomes a confirmed `Payment` only after webhook/reconciliation and transaction-safety checks approve settlement.
|
||||
|
||||
### Payment
|
||||
|
||||
@@ -109,7 +109,7 @@ created: 2026-05-23
|
||||
### Payout
|
||||
|
||||
> [!info] Definition
|
||||
> Money flowing **out** of escrow to the seller's wallet. Recorded as `Payment.direction: "out"`. Triggered by admin action after delivery is confirmed; implemented via SHKeeper's payout API (`shkeeperPayoutService.ts`).
|
||||
> Money flowing **out** of escrow to the seller's wallet. Triggered by release/refund orchestration after delivery confirmation or dispute resolution. The roadmap moves execution authority to Safe multisig/hardware signers before any custom smart-contract escrow pilot.
|
||||
|
||||
### Points
|
||||
|
||||
@@ -174,7 +174,7 @@ created: 2026-05-23
|
||||
### SHKeeper
|
||||
|
||||
> [!info] Definition
|
||||
> A self-hosted crypto payment processor used as Amn's primary custodial pay-in / payout rail. Issues a fresh wallet address per invoice, watches the chain for incoming USDT, and emits a signed webhook on settlement. Lives at `https://pay.amn.gg` per `backend/TODO.md`. Integration code under `backend/src/services/payment/shkeeper/`.
|
||||
> A self-hosted crypto payment processor used by older Amanat payment designs. Its docs remain for migration and historical context, but the current backend payment tree has moved to Request Network as the primary provider.
|
||||
|
||||
### Socket Room
|
||||
|
||||
@@ -194,12 +194,12 @@ created: 2026-05-23
|
||||
### USDT / USDC
|
||||
|
||||
> [!info] Definition
|
||||
> The two stablecoins Amn supports out of the box for pay-in and payout. USDT is the default for SHKeeper invoices; both are supported in offer pricing (`SellerOffer.price.currency` enum: `USD | EUR | IRR | USDT | USDC`).
|
||||
> The two stablecoins Amn supports out of the box for pay-in and payout. Request Network token registry work covers USDC/USDT across supported EVM chains; both are also supported in offer pricing (`SellerOffer.price.currency` enum: `USD | EUR | IRR | USDT | USDC`).
|
||||
|
||||
### Webhook
|
||||
|
||||
> [!info] Definition
|
||||
> An inbound HTTP POST from an external service notifying Amn of an event. SHKeeper webhooks (`/api/payment/shkeeper/webhook`) are the most important — they confirm pay-ins. All webhooks are HMAC-signed; verification uses `SHKEEPER_WEBHOOK_SECRET`. Failed verifications are dropped.
|
||||
> An inbound HTTP POST from an external service notifying Amn of an event. The primary payment webhook is Request Network at `/api/payment/request-network/webhook`, signed with `x-request-network-signature`. Roadmap work puts durable ingress/replay in front of the backend while keeping backend signature verification and transaction-safety checks as the trust boundary.
|
||||
|
||||
### WalletConnect
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ created: 2026-05-23
|
||||
> - **Passkeys hardened** — challenge consumption is now single-use with immediate deletion, 5-minute expiry, and replay-attack protection.
|
||||
> - **Web3 verification real** — `BSCTransactionVerifier` performs on-chain `eth_getTransactionReceipt` validation with confirmation counting.
|
||||
> - **Socket.IO auth enforced** — all socket connections require a valid JWT; room joins enforce strict ownership/participation checks.
|
||||
> - **Dispute holds** documented as planned but not yet implemented; the `Dispute` model, service layer, and API routes do not exist in the current backend.
|
||||
> - **Dispute holds** now exist in the backend through the dispute/release-hold service; remaining work is canonical state-machine alignment and stronger release/refund policy enforcement.
|
||||
> - **Data model docs aligned** with actual Mongoose schemas (Payment provider/escrowState enums, User model omissions documented).
|
||||
|
||||
# Introduction
|
||||
@@ -34,7 +34,7 @@ Traditional marketplaces tend to live at one of two extremes:
|
||||
1. **Fully custodial platforms** (Amazon, eBay, Fiverr) take a large cut, dictate every term of the transaction, and freeze funds on a whim. They work, but they are expensive and opaque.
|
||||
2. **Free-form P2P channels** (Telegram groups, Discord servers, direct DMs) charge nothing but offer no protection at all. The first scam empties the wallet and there is no recourse.
|
||||
|
||||
Amn sits between the two. It charges a thin escrow margin, holds funds for only as long as it takes to confirm delivery, and supports both fiat-style stablecoin escrow (via [[SHKeeper]]) and direct on-chain settlement (via [[DePay]] and the user's own wallet) — meaning the buyer can keep custody of their crypto until the literal moment of release.
|
||||
Amn sits between the two. It charges a thin escrow margin, holds funds for only as long as it takes to confirm delivery, and now routes primary stablecoin pay-in through Request Network with an Amanat-rendered wallet checkout. The buyer keeps custody of their crypto until they sign the on-chain payment, while the platform keeps settlement, safety checks, and dispute resolution in one auditable flow.
|
||||
|
||||
> [!tip] Why "crypto-native"?
|
||||
> The escrow rails are built around stablecoins (USDT/USDC) on EVM chains rather than card networks. That means no chargebacks, no 3-day settlement, no geographic restrictions — and a transparent, auditable transaction trail for every step of the deal. See [[Tech Stack]] for the full Web3 surface.
|
||||
@@ -56,7 +56,7 @@ Beyond the four roles, two ambient audiences read the platform:
|
||||
|
||||
A handful of design choices set Amn apart from generic marketplace software:
|
||||
|
||||
1. **Dual payment rails.** Every order can be paid through SHKeeper (a self-hosted crypto payment processor that issues a fresh wallet per invoice) *or* through a Web3 wallet connect flow (DePay + Wagmi/Viem + MetaMask). The buyer picks; the escrow logic is identical downstream. See [[Payments Overview]].
|
||||
1. **Request Network in-house checkout.** Every order can be paid through an Amanat-rendered Web3 checkout that builds Request Network-compatible transactions directly in the buyer's wallet. The hosted Request Network page remains a fallback, while the app keeps Rabby/MetaMask UX, chain choice, transaction safety checks, and escrow state in-house.
|
||||
2. **Request-first marketplace.** Most platforms list *products*. Amn lists *needs*. Buyers describe what they want and let the market come to them — closer to a reverse auction than a catalogue. The unidirectional flow eliminates the "thousand-listings-with-no-stock" problem.
|
||||
3. **Request Templates.** Power buyers (and admins) can publish reusable purchase request templates that act like express checkouts — a buyer clicks "I want this" and the order is opened pre-filled. Templates are the bridge between Amn and conventional ecommerce.
|
||||
4. **First-class i18n with RTL.** The frontend ships with six locales out of the box (English, French, Vietnamese, Chinese, Arabic, Persian) and full right-to-left support — Persian is the default fallback. See `frontend/src/locales/locales-config.ts:36`.
|
||||
@@ -78,4 +78,4 @@ A handful of design choices set Amn apart from generic marketplace software:
|
||||
|
||||
## Project status at a glance
|
||||
|
||||
Amn is at version **2.6.x** across both repositories, on the `development` branch, and tagged "production-ready with minor enhancements" by the project leads. The core escrow loop, real-time chat, multi-language UI, dispute system, points programme, and blog are all live. Active work focuses on UX polish, admin analytics, and a more granular permissions matrix — see `backend/TODO.md` and `frontend/VERSION_0_PREPARATION_TODO.md` for the rolling task list, and [[Roadmap]] (forthcoming) for the strategic view.
|
||||
Amn is at version **2.6.x** across both repositories, on the `development` branch, and tagged "production-ready with minor enhancements" by the project leads. The core escrow loop, real-time chat, multi-language UI, dispute system, points programme, and blog are all live. Active work focuses on Request Network hardening, durable webhook ingress, derived-destination custody, admin signing, and a more granular permissions matrix. The custody/smart-contract strategy lives in [[PRD - Decentralized Custody and Smart-Contract Escrow Roadmap]].
|
||||
|
||||
@@ -37,7 +37,7 @@ flowchart LR
|
||||
- **Browse and search** the public marketplace and request templates.
|
||||
- **Create a [[Purchase Request]]** describing what they want — product type (physical / digital / service / consultation), budget, urgency, delivery info, attachments. See `backend/src/models/PurchaseRequest.ts`.
|
||||
- **Review incoming [[Seller Offer]]s**, negotiate over chat, accept the best one.
|
||||
- **Pay** via [[SHKeeper]] (custodial crypto invoice) or Web3 wallet ([[DePay]] + MetaMask through Wagmi).
|
||||
- **Pay** via the Request Network in-house checkout, using a supported EVM wallet through Wagmi/WalletConnect and the platform's payment request metadata.
|
||||
- **Track the order** through `processing → delivery → delivered → confirming → completed` states.
|
||||
- **Confirm receipt** (or let the SLA auto-confirm), leave a review, accrue points.
|
||||
- **Open a [[Dispute]]** if delivery never lands, item is wrong, or quality is poor.
|
||||
@@ -86,7 +86,7 @@ The buyer dashboard lives under `/dashboard` (`frontend/src/app/dashboard/`). No
|
||||
- **Negotiate** in the per-request chat — bilateral with the buyer until an offer is accepted.
|
||||
- **Fulfil** the order: ship physical goods (with optional tracking number), or upload/email digital deliverables.
|
||||
- **Use the [[delivery code]]** for physical handoffs: a six-digit one-time code the buyer reads to the courier to confirm receipt.
|
||||
- **Receive payout** automatically via SHKeeper to the configured wallet once the order is finalised (admin-triggered batch or per-order based on shop policy).
|
||||
- **Receive payout** to the configured wallet after ledger-gated release. Today this is an admin/custody-signer operation; the target path is Safe/hardware-backed approvals as described in [[PRD - Decentralized Custody and Smart-Contract Escrow Roadmap]].
|
||||
- **Manage [[Request Templates]]** scoped to their shop — publish "off-the-shelf" offerings buyers can purchase in one click.
|
||||
- **Engage with reviews and disputes**: respond to reviews, contest disputes, provide evidence.
|
||||
|
||||
@@ -125,12 +125,12 @@ Seller dashboard reuses the same `/dashboard` shell with extra modules:
|
||||
|
||||
- **Moderate users**: suspend / unsuspend accounts (`User.status: "active" | "suspended" | "deleted"`, see `backend/src/models/User.ts`), promote buyers to sellers, ban repeat offenders.
|
||||
- **Moderate marketplace content**: categories (`Category` model), request templates (the canonical platform-wide ones), blog posts.
|
||||
- **Resolve disputes**: get assigned to disputes, drive them to resolution, choose an outcome (`refund | replacement | compensation | warning_seller | ban_seller | no_action`). See `backend/src/services/dispute/DisputeService.ts` *(planned, not yet implemented)*.
|
||||
- **Operate payments**: trigger payouts, fetch on-chain transactions, manually confirm stuck payments (the manual transaction-hash flow described in `backend/TODO.md`), audit the SHKeeper webhook history (`services/payment/shkeeper/webhookStats.ts`).
|
||||
- **Resolve disputes**: get assigned to disputes, drive them to resolution, choose an outcome (`refund | replacement | compensation | warning_seller | ban_seller | no_action`). See `backend/src/services/dispute/DisputeService.ts` and [[Dispute Flow]].
|
||||
- **Operate payments**: trigger ledger-gated releases/refunds, review Request Network webhooks, inspect derived destination wallets, fetch on-chain transactions, and manually confirm stuck payments only after Transaction Safety Provider checks.
|
||||
- **Configure the platform**: levels (`LevelConfig`), points multipliers, blog seed content, default templates.
|
||||
- **Run data cleanup**: `/api/admin/cleanup` exposes destructive maintenance utilities (`services/admin/`).
|
||||
- **Author blog posts** via the TipTap rich-text editor.
|
||||
- **Monitor health**: SHKeeper status (background health monitor in `app.ts:433`), Redis, MongoDB.
|
||||
- **Monitor health**: Request Network webhook/reconciliation status, ledger enforcement, custody signer/Safe readiness, Redis, and MongoDB.
|
||||
|
||||
### Key permissions
|
||||
|
||||
@@ -149,7 +149,7 @@ Admins see the buyer/seller surfaces plus dedicated admin modules (typically und
|
||||
|
||||
- User management (search, suspend, role change)
|
||||
- Dispute queue with assignment and resolution
|
||||
- Payment console (manual confirmation, payout dispatch, webhook log)
|
||||
- Payment console (manual confirmation, release/refund dispatch, Request Network webhook and ledger log)
|
||||
- Category and template management
|
||||
- Blog editor (publish / unpublish / featured)
|
||||
- Platform analytics (TODO — see `backend/TODO.md`)
|
||||
|
||||
@@ -16,7 +16,7 @@ Amn is a **two-repo system**:
|
||||
- **Frontend** (`/Users/mojtabaheidari/code/frontend`) — a Next.js 16 App Router application that serves the marketplace UI, the admin dashboard, the public blog, and the user-facing Web3 wallet flow.
|
||||
- **Backend** (`/Users/mojtabaheidari/code/backend`) — an Express 5 + TypeScript API server that owns all business logic, persists to MongoDB, caches in Redis, and brokers all external integrations.
|
||||
|
||||
The two repos are deployable independently. They communicate over **HTTPS (REST)** for stateful actions and over **WebSocket (Socket.IO)** for live updates. The frontend never talks directly to MongoDB, Redis, SHKeeper, or OpenAI — every external interaction is mediated by the backend so that secrets stay on the server.
|
||||
The two repos are deployable independently. They communicate over **HTTPS (REST)** for stateful actions and over **WebSocket (Socket.IO)** for live updates. The frontend never talks directly to MongoDB, Redis, Request Network API keys, OpenAI, or admin custody secrets -- every sensitive external interaction is mediated by the backend so that secrets stay on the server.
|
||||
|
||||
## System map
|
||||
|
||||
@@ -41,7 +41,7 @@ flowchart TB
|
||||
Auth["Auth service<br/>JWT + Passkey + Google + Telegram"]
|
||||
Market["Marketplace service<br/>Requests, Offers, Templates"]
|
||||
ChatSvc["Chat service"]
|
||||
PaySvc["Payment service<br/>SHKeeper + Request Network + ledger"]
|
||||
PaySvc["Payment service<br/>Request Network + ledger + custody controls"]
|
||||
TelegramSvc["Telegram service<br/>bot + Mini App + notifications"]
|
||||
Disp["Dispute service"]
|
||||
Points["Points / Referrals"]
|
||||
@@ -58,8 +58,6 @@ flowchart TB
|
||||
end
|
||||
|
||||
subgraph External["External services"]
|
||||
SHK["SHKeeper<br/>crypto invoicing"]
|
||||
DePay["DePay widget"]
|
||||
Chain["EVM chains<br/>BSC / ETH / Polygon"]
|
||||
SMTP["SMTP<br/>(nodemailer)"]
|
||||
OpenAI["OpenAI API"]
|
||||
@@ -68,6 +66,7 @@ flowchart TB
|
||||
Alchemy["Alchemy RPC"]
|
||||
TelegramAPI["Telegram Bot API<br/>+ Mini App"]
|
||||
ReqNet["Request Network<br/>pay-in / webhooks"]
|
||||
CFWorker["Durable webhook ingress<br/>(roadmap)"]
|
||||
end
|
||||
|
||||
Browser --> SSR
|
||||
@@ -88,13 +87,10 @@ flowchart TB
|
||||
Auth & PaySvc & Notif --> RedisDB
|
||||
Files --> Disk
|
||||
|
||||
PaySvc <--> SHK
|
||||
SHK -.webhook.-> PaySvc
|
||||
PaySvc <--> ReqNet
|
||||
ReqNet -.webhook.-> PaySvc
|
||||
ReqNet -.webhook.-> CFWorker
|
||||
CFWorker -.forward/replay.-> PaySvc
|
||||
PaySvc --> Chain
|
||||
Wagmi --> DePay
|
||||
DePay --> Chain
|
||||
PaySvc -.tx fetch.-> Alchemy
|
||||
|
||||
TelegramSvc <--> TelegramAPI
|
||||
@@ -130,16 +126,17 @@ The heart of the platform. Three first-class models drive it:
|
||||
|
||||
Services live in `backend/src/services/marketplace/` and are exposed through `/api/marketplace/*`. The frontend uses a mix of React Query (`@tanstack/react-query`) and SWR for data fetching, with mutations gated through the actions layer in `frontend/src/actions/`.
|
||||
|
||||
### Payments — [[Payments Overview]] / [[SHKeeper Integration]]
|
||||
### Payments -- Request Network, Ledger, And Custody Controls
|
||||
|
||||
Payments are where Amn is most distinctive. The backend supports **four payment surfaces** routed through a common `Payment` model (`backend/src/models/Payment.ts`) via a provider-neutral adapter layer (`backend/src/services/payment/adapters/`):
|
||||
Payments are where Amn is most distinctive. The live backend has converged on **Request Network** as the primary provider through a common `Payment` model (`backend/src/models/Payment.ts`) and provider-neutral adapter layer (`backend/src/services/payment/adapters/`):
|
||||
|
||||
- **SHKeeper** — `/api/payment/shkeeper`. Issues a fresh wallet address per invoice, polls / webhooks for payment confirmation, and runs through `PaymentCoordinator` to avoid race conditions. Health is monitored in the background (`shkeeperHealthCheck.ts`).
|
||||
- **Request Network** — `/api/payment/request-network`. Creates on-chain payment requests via the Request Network protocol, generates Secure Payment Page URLs for the buyer, and receives real-time payment status via signed webhooks (`x-request-network-signature`). Pay-in service: `requestNetworkPayInService.ts`; reconciliation: `requestNetworkReconciliationService.ts`.
|
||||
- **Decentralized (Wagmi + DePay)** — `/api/payment/decentralized`. The user signs and sends the transfer from their own wallet; the backend verifies on-chain via `blockchainTxFetcher.ts` and the Alchemy SDK.
|
||||
- **Payout** — `/api/payment/shkeeper/payout`. Admin-triggered release of escrow funds to the seller's wallet once delivery is confirmed.
|
||||
- **Request Network pay-in** -- `/api/payment/request-network`. Creates requests, exposes the Amanat in-house checkout block, and receives signed webhooks (`x-request-network-signature`). Pay-in service: `requestNetworkPayInService.ts`; reconciliation: `requestNetworkReconciliationService.ts`.
|
||||
- **In-house wallet checkout** -- buyer signs the RN-compatible `approve` + `transferFromWithReferenceAndFee` flow from their own wallet, so Rabby/MetaMask wallet UX stays inside Amanat.
|
||||
- **Derived destination wallets** -- `/api/payment/derived-destinations` admin endpoints manage per-`(buyer, sellerOffer, chainId)` receiving addresses, sweep status, and config health.
|
||||
- **Funds ledger** -- `backend/src/services/payment/ledger/` tracks payment detection, holds, releases, refunds, fees, and adjustments independently of provider metadata.
|
||||
- **Release/refund orchestration** -- `/api/payment/:id/(release|refund)` builds instructions; `/confirm` records confirmed transaction hashes. Optional Trezor enforcement gates confirmation when `TREZOR_SAFEKEEPING_REQUIRED=true`.
|
||||
|
||||
All surfaces converge on the same `Payment` record (with `direction: 'in' | 'out' | 'refund'`) and share the internal **funds ledger** (`backend/src/services/payment/ledger/`) which tracks available / held / releasable amounts independently of the provider. **Pending payments are auto-cleaned** by a background timer started in `app.ts`.
|
||||
Historical SHKeeper and DePay docs remain in the vault for migration context, but the current backend tree no longer has `backend/src/services/payment/shkeeper/`. The current strategic path is in [[PRD - Decentralized Custody and Smart-Contract Escrow Roadmap]].
|
||||
|
||||
### Real-time chat — [[Chat System]]
|
||||
|
||||
@@ -164,9 +161,10 @@ Push and SMS are tracked as **planned** in `backend/TODO.md`.
|
||||
|
||||
### Disputes — [[Dispute System]]
|
||||
|
||||
When a deal goes wrong (see [[Glossary#Dispute]]), either party can open a dispute. The backend would create a **three-way chat** between buyer, seller, and admin, open a `Dispute` document with a structured `timeline[]` and `evidence[]`, and assign the dispute to an admin via `assignAdmin()`. Resolution can be `refund | replacement | compensation | warning_seller | ban_seller | no_action` and is recorded on the dispute itself.
|
||||
> [!warning] Not implemented
|
||||
> `backend/src/services/dispute/DisputeService.ts` does not exist as of 2026-05-24.
|
||||
When a deal goes wrong (see [[Glossary#Dispute]]), either party can open a dispute. The backend creates a **three-way chat** between buyer, seller, and admin, opens a `Dispute` document with a structured `timeline[]` and `evidence[]`, and can assign the dispute to an admin via `assignAdmin()`. Resolution can be `refund | replacement | compensation | warning_seller | ban_seller | no_action` in the current Mongoose model.
|
||||
|
||||
> [!note] State alignment gap
|
||||
> The dispute module exists now, but its model still uses the legacy `pending | in_progress | resolved | ...` enum. [[Funds Ledger and Escrow State Machine Specification]] defines the canonical future enum and financial side effects.
|
||||
|
||||
### Points & referrals — [[Points System]]
|
||||
|
||||
@@ -191,9 +189,10 @@ OpenAI (model configurable per call) is exposed through `/api/ai/*`. The current
|
||||
- locks used by `PaymentCoordinator` to serialise status transitions
|
||||
- rate-limit counters (currently disabled in code but plumbed in)
|
||||
|
||||
**Background workers** run inside the Express process for now — no separate worker tier. Notable timers:
|
||||
**Background workers** run inside the Express process for now -- no separate worker tier. Notable timers:
|
||||
- `startPendingPaymentsCleanup()` — sweeps stale unpaid invoices
|
||||
- `startShkeeperHealthMonitor()` — pings the SHKeeper instance and surfaces alerts
|
||||
- optional derived-destination sweep cron — sweeps eligible per-payment receiving addresses when configured
|
||||
- Request Network reconciliation — enabled via provider config when the rollout requires fallback status repair
|
||||
- Auto-seed logic on startup (gated by `NODE_ENV` and `AUTO_SEED_ON_START`)
|
||||
|
||||
## Request lifecycle (the happy path)
|
||||
@@ -203,9 +202,10 @@ OpenAI (model configurable per call) is exposed through `/api/ai/*`. The current
|
||||
> 2. Buyer creates a [[Purchase Request]] → `POST /api/marketplace/requests`. The request lands in `pending`/`active`. Sellers in the matching category receive a Socket.IO notification.
|
||||
> 3. Seller views the request, opens [[Seller Offer]] modal, submits price + delivery time → `POST /api/marketplace/offers`. Buyer sees the offer arrive live.
|
||||
> 4. Buyer accepts an offer → request moves to `payment`. UI opens the payment selector.
|
||||
> 5. Buyer picks **SHKeeper** → backend creates a SHKeeper invoice, returns a wallet address + QR code. Buyer pays. SHKeeper webhook hits `/api/payment/shkeeper/webhook`; `PaymentCoordinator` flips `Payment.status = paid` and `PurchaseRequest.status = processing`.
|
||||
> 6. Seller ships. Buyer confirms delivery (or it auto-confirms after the SLA window). Admin triggers (or schedules) a **payout** → SHKeeper releases USDT to the seller's wallet.
|
||||
> 7. Both parties leave reviews. Points are awarded. The deal is closed.
|
||||
> 5. Buyer picks **Request Network** -> backend creates a Payment and RN intent, returns an in-house checkout block, and the buyer signs the on-chain payment from their wallet.
|
||||
> 6. Request Network webhook/reconciliation plus the Transaction Safety Provider confirm tx hash, recipient, token, amount, and confirmations before the backend marks escrow funded.
|
||||
> 7. Seller ships. Buyer confirms delivery (or an admin resolves the order/dispute). Admin/custody owners execute release/refund through the release/refund instruction flow.
|
||||
> 8. Both parties leave reviews. Points are awarded. The deal is closed.
|
||||
>
|
||||
> If the buyer disputes the delivery, jump to step 7 of the [[Dispute Flow]] instead.
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ The frontend is a Next.js 16 App Router application written in TypeScript. The b
|
||||
|
||||
## Backend stack
|
||||
|
||||
The backend is `amn-backend@2.6.3-beta`, an Express 5 server in TypeScript backed by MongoDB (Mongoose), Redis, and Socket.IO. It owns all integrations with SHKeeper, the EVM chains, OpenAI, Google OAuth, and SMTP.
|
||||
The backend is `amn-backend@2.6.3-beta`, an Express 5 server in TypeScript backed by MongoDB (Mongoose), Redis, and Socket.IO. It owns all integrations with Request Network, EVM chains, OpenAI, Google OAuth, Telegram, SMTP, and custody/signing controls.
|
||||
|
||||
### Core runtime & framework
|
||||
|
||||
@@ -135,7 +135,7 @@ The backend is `amn-backend@2.6.3-beta`, an Express 5 server in TypeScript backe
|
||||
| sharp | ^0.34.3 | Image resizing / format conversion | Upload pipeline |
|
||||
| dotenv | ^17.2.0 | Env var loader | Bootstrap |
|
||||
| uuid | ^11.1.0 | ID generation | Tokens, ephemeral IDs |
|
||||
| axios | ^1.11.0 | Outbound HTTP (SHKeeper, blockchain) | Integration calls |
|
||||
| axios | ^1.11.0 | Outbound HTTP (Request Network, blockchain/RPC helpers) | Integration calls |
|
||||
| @babel/runtime | ^7.27.6 | Babel runtime helpers | Compiled output |
|
||||
|
||||
> [!warning] React in backend dependencies
|
||||
@@ -210,9 +210,12 @@ The backend is `amn-backend@2.6.3-beta`, an Express 5 server in TypeScript backe
|
||||
|
||||
| Service | Purpose | Touchpoint in code |
|
||||
|---|---|---|
|
||||
| **SHKeeper** | Self-hosted crypto payment processor — issues wallets, watches for incoming USDT, pays out | `backend/src/services/payment/shkeeper/` |
|
||||
| **Request Network** | On-chain payment request protocol — creates invoices, generates Secure Payment Pages, signs webhooks | `backend/src/services/payment/requestNetwork/` + adapters |
|
||||
| **DePay** | Drop-in Web3 widget for wallet-to-wallet payment | `@depay/widgets` on frontend |
|
||||
| **Request Network** | On-chain payment request protocol -- creates payment requests, supports in-house checkout metadata, signs webhooks | `backend/src/services/payment/requestNetwork/` + adapters |
|
||||
| **Derived destination wallets** | Per-`(buyer, sellerOffer, chainId)` receiving addresses plus sweep orchestration | `backend/src/services/payment/wallets/` |
|
||||
| **Transaction Safety Provider** | Confirms tx hash, recipient, token, amount, confirmation depth, and future AML result before escrow credit | `backend/src/services/payment/safety/` |
|
||||
| **Trezor / future Safe multisig** | Hardware-backed admin signing today; Safe multisig target in custody roadmap | `backend/src/services/trezor/`, [[PRD - Decentralized Custody and Smart-Contract Escrow Roadmap]] |
|
||||
| **SHKeeper** | Historical payment rail retained in documentation for migration context | legacy docs only |
|
||||
| **DePay** | Historical/drop-in Web3 widget docs retained for context | frontend historical docs |
|
||||
| **EVM chains** (BSC, Ethereum mainnet, Sepolia, Polygon) | Settlement layer for stablecoin transfers | `frontend/src/web3/config.ts`, backend `blockchain/` |
|
||||
| **Alchemy RPC** | Hosted EVM RPC + transaction lookup | Frontend `alchemy-sdk`, backend `blockchainTxFetcher.ts` |
|
||||
| **MetaMask / WalletConnect** | Wallet connectors via Wagmi | `web3/config.ts` (WalletConnect commented out pending SSR fix) |
|
||||
|
||||
Reference in New Issue
Block a user