AgroX — Step‑by‑Step Build Guide (Web MVP →
Small‑Scale Prototype)
A practical, end‑to‑end blueprint to build AgroX, a stock‑market‑style platform where people directly buy/
sell shares of real farms and receive profit distributions (dividends). The plan moves from zero to a
working, small‑scale prototype web app, with clear deliverables, checklists, and technical details you can
hand to a team.
0) North‑Star & Scope Guardrails
• Mission: Make farm investing as simple and transparent as stock investing.
• Initial Scope: Web app first (desktop + responsive mobile). Later: native mobile.
• Pilot Scale Target: 3–5 farm listings, ≤1,000 users, ≤50 concurrent traders, ~50 tx/min peak, single
region and currency.
• Must‑Haves (MVP): 1) Farm listings (as tradable assets, fixed total shares). 2) User onboarding with
KYC/AML + wallets. 3) Order book trading (market/limit), price‑time priority matching. 4) Live market
data (ticker, last price, depth, trades stream). 5) Portfolio dashboard + transaction history. 6) Dividend
(profit) events and payouts to wallets. 7) Admin ops: farm vetting/approval, market halts, corporate
actions, audits.
• Nice‑to‑Haves (post‑MVP): Watchlists, alerts, advanced charts, APIs for third‑party apps, auctions
(opening/closing), maker/taker fees, referral program.
1) Compliance & Risk Framing (start in parallel)
Begin this before coding; it shapes data you must capture. - Choose Pilot Jurisdiction &
Model (examples): - Equity‑like fractional shares in farm SPVs; or - Revenue‑share securities
tied to farm output; or - Tokenized off‑chain representation (still usually regulated). - Engage
Counsel on: licensing (broker/portal), offering exemptions, advertising rules, investor limits,
disclosures, custody, tax docs, data privacy, sanctions screening. - Design KYC/KYB: individual
& business verification, PEP/sanctions screening, proof of address. - Cash Controls: escrow/
segregated accounts; flow of funds diagrams (user ↔ escrow ↔ issuer). - Risk Policies: listing
due‑diligence checklist, incident response (fraud, volatility, outages), market manipulation
monitoring, complaints & dispute handling. - Deliverables: Regulatory memo (2–5 pages),
Flow‑of‑Funds diagram, Draft Terms & Risk Disclosures.
2) Product Definition (MVP)
• User Roles: Investor, Farm Owner (Issuer), Admin.
• Key Flows: 1) Investor: sign‑up → KYC → deposit → browse → buy shares → receive dividends →
withdraw. 2) Issuer: sign‑up → KYB → submit farm → due diligence → approval → initial listing (IPO)
1
→ secondary trading → declare dividends → close. 3) Admin: review/approve farms, control market
states (open/halt/close), corporate actions, payouts, audits.
• Market Microstructure (MVP): continuous limit order book, price‑time priority, tick size per asset,
lot size=1 share, market hours (e.g., 09:00–17:00 local), circuit breaker (e.g., 10% move in 5 min halts
5 min).
• Fees: trading fee (bps of notional), withdrawal fee, issuer listing fee.
• Deliverables: PRD (≤10 pages), Wireflows of above journeys, Fee & Market Rules doc.
3) Architecture & Tech Stack (proven, simple first)
• Frontend: React + TypeScript + Next.js (SSR for SEO) + Tailwind; state via React Query/Zustand;
WebSocket client for market data.
• Backend: Node.js (NestJS/Express) + TypeScript; REST for CRUD; WebSockets for live data;
background workers (BullMQ) for matching & payouts.
• Data: PostgreSQL (primary), Redis (caching, pub/sub), optional Kafka/RabbitMQ (events) as scale
grows.
• Infra: Docker, CI/CD (GitHub Actions), deploy on AWS/GCP/Azure; Nginx or CloudFront; Terraform for
IaC (optional in MVP).
• Observability: OpenTelemetry + Prometheus/Grafana; Sentry for error tracking; structured logs.
• Security: HTTPS, TLS 1.2+, JWT (short‑lived) + refresh tokens, role‑based access control (RBAC),
secrets manager; OWASP ASVS checks.
• Deliverables: System Context diagram, Component diagram, API gateway spec, non‑functional
targets (latency, throughput).
4) Data Model (first cut)
Relational (PostgreSQL) — core tables
users(id, email, password_hash, role, kyc_status, created_at)
profiles(user_id, full_name, dob, address, country, phone)
kyc_cases(id, user_id, provider, status, result_blob, created_at)
issuers(id, user_id, business_name, kyb_status)
farms(id, issuer_id, title, type, location, description, total_shares,
free_float,
status[draft|approved|listed|halted|closed], tick_size, lot_size,
base_currency)
listings(id, farm_id, phase[primary|secondary], offer_price, open_at, close_at)
orders(id, user_id, farm_id, side[buy|sell], type[market|limit], qty,
limit_price,
status[new|partial|filled|canceled|expired], created_at)
order_book_snapshots(id, farm_id, ts, bids_json, asks_json)
trades(id, buy_order_id, sell_order_id, farm_id, price, qty, ts)
positions(user_id, farm_id, shares, avg_price)
2
wallets(id, user_id, currency, available, locked)
ledger(id, user_id, currency, delta, balance_after, ref_type, ref_id, ts)
deposits(id, user_id, currency, amount, status, provider_ref, ts)
withdrawals(id, user_id, currency, amount, status, provider_ref, ts)
dividends(id, farm_id, amount_per_share, declared_at, payable_at, status)
dividend_payments(id, dividend_id, user_id, shares_on_record, amount, paid_at)
admin_actions(id, admin_id, action, target_type, target_id, ts, notes)
Notes - ledger is double‑entry style (wallet available+locked); every money move has a ref (order fill, fee,
payout). - positions updated atomically on trade execution. - snapshots enable depth UI & recovery; trades
drive candles for charts.
5) Matching Engine (MVP)
• Policy: Price‑time priority matching; maintain two sorted books per farm (bids desc, asks asc).
• Order Types: Limit (MVP), Market (careful—reject if no liquidity), Cancel, Good‑For‑Day (auto‑expire
at close).
• Circuit Breakers: If last trade deviates >X% in Y minutes, halt asset.
• Pseudocode (core loop):
onNewOrder(o):
validate(o); reserveFundsOrShares(o)
if o.type == MARKET:
matchAgainst(oppositeBook, o) until o.qty==0 or book empty
else: // LIMIT
while o.qty>0 and bestOppositeMatches(o):
tradeQty = min(o.qty, best.qty)
price = best.price
executeTrade(buyOrder, sellOrder, price, tradeQty)
if o.qty>0: addToBook(o)
• executeTrade:
• Move funds: buyer locked → seller available; collect fee.
• Update positions (avg price, shares).
• Persist trade; publish to market‑data WS (ticker, depth, trades).
• Persistence & Recovery: write‑ahead queue; on restart, rebuild books from open orders.
6) Cash Flow & Custody (Wallets)
• Deposit: Payment gateway → webhook → credit wallets.available → ledger entry.
• Place Buy Order: move available → locked (notional + fee buffer).
• Fill: buyer pays notional; seller receives proceeds; release residual locks; fees to platform wallet.
• Withdraw: KYC complete + AML checks → initiate payout via gateway.
3
• Dividend: snapshot positions at record time → compute amount_per_share * shares → credit
wallets + ledger.
• Reconciliation: daily reports of ledger vs. bank/PG statements.
7) Farm Listing & Lifecycle
1) Issuer Onboarding: KYB + bank details; upload docs (land ownership/lease, historical yields, buyer
contracts, risk factors). 2) Due Diligence: admin checklist (identity, ownership, operations, financials,
insurance, environmental, biosecurity). 3) Create Listing: total shares, initial offer price, tick size, market
hours, disclosures. 4) Primary Offering (optional MVP): fixed‑price IPO; investors subscribe; after close,
allocate & list for secondary trading. 5) Secondary Trading: continuous LOB as above. 6) Corporate
Actions: dividends, halts, symbol changes, share increases (new issuance) — admin tools.
8) UX Maps (MVP Screens)
• Public: Home (top movers), Farm Explorer (filters), Farm Detail (about, docs, order book, trades,
chart), Auth.
• Investor: KYC flow, Wallet (deposit/withdraw), Place Order modal, Portfolio (positions, P&L), Orders/
Trades history, Settings.
• Issuer: Farm Editor, Document Uploader, Listing Status, Dividend Declare page, Updates to investors.
• Admin: Review queue, Farm approval, Market control (halt/open), Corporate actions, User & KYC
console, Logs.
9) APIs (sample endpoints)
POST /auth/register | /auth/login | /auth/refresh
GET /me | PUT /me
POST /kyc/submit | GET /kyc/status
GET /farms?filter=... | POST /farms (issuer)
GET /farms/:id | GET /farms/:id/orderbook | GET /farms/:id/trades
POST /orders | GET /orders?status=open | DELETE /orders/:id
GET /portfolio | GET /wallet | POST /wallet/deposit-intent | POST /wallet/
withdraw
POST /dividends (issuer/admin) | GET /dividends/:farmId
WS /marketdata (channels: ticker:{farmId}, depth:{farmId}, trades:{farmId})
ADMIN: POST /admin/approve-farm, POST /admin/halt, POST /admin/corporate-action
10) Security Checklist (MVP)
• Hash passwords (Argon2/bcrypt), rotate JWT signing keys, short TTLs + refresh.
4
• Validate all inputs; rate‑limit auth & order endpoints; CSRF protect mutations.
• Segregate duties: trading engine process isolated; least‑privilege DB roles.
• Encrypt PII at rest; store docs in private bucket; signed URLs.
• Webhooks: HMAC verify; idempotency keys for all money operations.
• Backups & disaster recovery tested; runbooks for incidents (DDoS, data breach, trading halt).
11) Analytics & Monitoring
• KPIs: DAU/MAU, deposit conversion, active traders, spread/volume per farm, failed orders, latency
percentiles, cash reconciliation status.
• Dashboards: user funnel, liquidity per farm, error budgets (SLOs), KYC pass rates.
12) Step‑by‑Step Build Plan (8 Sprints = ~16 Weeks)
Sprint 0 (Week 1–2): Foundations - Finalize PRD, market rules, data model. - Repo setup, CI/CD,
environments, coding standards. - Pick KYC & payments vendors; integrate sandbox keys. Exit: architecture
doc, empty Next.js+NestJS app deployed (Hello World), staging env live.
Sprint 1 (Week 3–4): Auth, KYC, Wallets (basic) - Auth (register/login/refresh, RBAC), profiles. - KYC flow
(upload + provider webhook), status gates. - Wallet model + deposits (mock PG), ledger entries, withdrawals
(manual approve). Exit: user can onboard, pass KYC, deposit test funds.
Sprint 2 (Week 5–6): Issuer & Farm Listings - Issuer KYB; farm create/edit; doc uploads; admin review &
approve. - Public Farm Explorer + Farm Detail (static info). Exit: approved farm appears in explorer.
Sprint 3 (Week 7–8): Order Book & Trades (backend) - Order schema, validation, locking funds/shares. Matching engine service (limit orders), trades persisted, positions/ledger updates. - Market data stream
topics (Redis pub/sub). Exit: unit tests prove matching & balances.
Sprint 4 (Week 9–10): Trading UI & Live Data - Depth/Trades widgets; place/cancel orders; portfolio &
history pages. - WebSockets wired; candles chart (1m/5m from trades). Exit: users can buy/sell in staging
with fake money.
Sprint 5 (Week 11–12): Dividends & Admin Ops - Dividend declaration → compute → payouts to wallets. Admin: halt/open farm, edit tick size, approve/cancel listings. Exit: issuer can pay dividends; admin can
control markets.
Sprint 6 (Week 13–14): Payments & Reconciliation - Real PG integration (test mode), webhook security. Reconciliation reports; withdrawal flows with maker checks. Exit: end‑to‑end money flows.
Sprint 7 (Week 15–16): Hardening & Pilot - Pen‑tests, perf tests (target p95 < 300ms for trading APIs). Observability dashboards; incident runbooks; legal docs live; risk disclaimers. - Pilot with 3–5 farms, 50–100
users. Exit: MVP ready for limited launch.
5
13) Test Plan (what to prove)
• Unit: matching edge cases (partial fills, crossing orders, cancellations), ledger math (fees, dividends),
KYC states.
• Integration: deposit→buy→sell→withdraw; IPO→allocation→secondary trading; dividend snapshot
correctness.
• Performance: sustained 50 orders/sec; recovery time < 60s after engine restart.
• Security: OWASP Top 10, webhook forgery, IDOR checks, RBAC bypass attempts.
• UAT: scripted scenarios for investor/issuer/admin; accessibility checks (WCAG AA).
14) Go‑Live Runbook (Pilot)
1) Freeze schemas, migrate DB, seed 3 farms. 2) Dry‑run trading session with staff users. 3) Enable deposits
(small limits), open market hours. 4) Monitor: error rate, latency, balances; daily reconciliation. 5)
Post‑mortems for any incidents; iterate quickly.
15) Post‑MVP Roadmap (high impact)
• Advanced order types (stop, stop‑limit), auctions (open/close), maker/taker fees.
• Watchlists, price alerts, email/SMS/push notifications.
• Mobile apps (React Native/Flutter, reuse APIs), offline portfolio view.
• APIs for partners; historical data download; tax statements.
• Risk/Surveillance tooling (spoofing detection, wash trading alerts).
16) Team & RACI (minimum viable team)
• Product/Founder (R): PRD, market rules, legal liaison.
• Tech Lead (A/R): architecture, code reviews, security.
• Backend Dev (R): services, matching, ledger.
• Frontend Dev (R): trading UI, dashboards.
• Full‑stack (C/R): bridges gaps.
• UX Designer (C/R): flows, components, design system.
• DevOps (R): CI/CD, cloud, monitoring.
• Compliance Ops (A/C): KYC/AML, audits, incident response.
17) Acceptance Criteria (MVP, demo‑able)
• A new investor can: sign up → pass KYC → deposit → buy shares of a farm → see position and P&L →
sell → withdraw.
6
• An issuer can: onboard → submit farm → get approved → list → see trading → declare a dividend →
investors receive payouts.
• Admin can: approve/reject farms, halt/unhalt trading, run reconciliation, view full audit trail.
• System can recover from engine restart without losing open orders or balances.
18) Deliverable Templates (quick starters)
• Docs: PRD template, Market Rules template, DD checklist, Incident runbook.
• Diagrams: C4 context + container, sequence for order lifecycle, flow‑of‑funds.
• Config: .env.example (separate secrets), docker-compose.yml for local dev.
Notes on Scaling Later
• Split services: auth, wallets/ledger, matching, market‑data, admin, API gateway.
• Introduce Kafka for event sourcing (orders, trades, ledger), snapshots for replay.
• Read replicas for Postgres; partition large tables (trades); cache hot reads (order book) in Redis.
Quick Checklist to Start This Week
• [ ] Pick pilot country & finalize legal memo.
• [ ] Lock stack (Next.js + NestJS + Postgres + Redis), scaffold repos.
• [ ] Draft PRD + Market Rules + Flow‑of‑Funds (v1).
• [ ] Build auth, KYC stub, wallets/ledger skeleton.
• [ ] Design Farm Explorer & Farm Detail screens.
• [ ] Start matching engine module tests.
With this guide, you have a concrete plan, schemas, endpoints, and sprint map to deliver a
working AgroX web prototype that behaves like a compact stock market for farms.
7
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )