Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AgroChain - Official Documentation

React TypeScript Tailwind CSS Express PostgreSQL Stellar Rust Vite License Built on Stellar Contributions Welcome

Decentralized supply-chain finance for smallholder farmers, built on Stellar Soroban.


Table of Contents


Introduction

AgroChain is a decentralized supply-chain finance platform that connects smallholder farmers directly with investors through the Stellar Network's Soroban smart contracts. Farmers tokenize a harvest as a digital asset, investors fund it, and milestone-based escrow releases capital as oracle-verified growth data confirms progress.

AgroChain is designed for the 500 million smallholder farms that feed over 2 billion people worldwide — yet remain chronically underfunded. Traditional agricultural finance is fragmented, opaque, and slow: farmers wait weeks for loans they may never receive, while investors have no transparent way to deploy capital into real agricultural production. AgroChain bridges this gap with on-chain transparency, milestone-based capital release, and oracle-verified accountability.


Problem Statement

Smallholder agriculture is a $5+ trillion annual market, yet the farmers who produce the world's food are the most underserved by financial infrastructure. Three core problems define the gap:

The Funding Gap - Smallholder farmers face a $170 billion annual financing gap. Traditional lenders view them as too risky, too small, and too unbanked to serve. The result: farmers rely on informal lenders charging predatory rates, or go without capital entirely.

Opaque Capital Deployment - When investors do fund agricultural projects, they have no visibility into how their money is used. Funds are disbursed upfront with no accountability, no milestone tracking, and no oracle-verified proof of progress. If a crop fails, investors discover it months later — after the money is gone.

Fragmented Trust - Agricultural supply chains are a web of intermediaries — aggregators, cooperatives, processors, and traders — each taking a cut and adding opacity. There is no single source of truth for what was planted, how it's growing, and when it's ready for market.

AgroChain addresses all three problems with a single, cohesive platform built on open, decentralized infrastructure.


Solution

AgroChain creates a three-pillar ecosystem:

1. Tokenize - Farmers mint a Harvest Token representing one crop batch. Each token encodes the crop type, expected yield, funding target, and lifecycle status (Draft → Funding → Growing → Harvested → Settled). The token becomes a tradeable, verifiable digital asset on the Stellar ledger.

2. Fund - Investors browse the marketplace, review tokenized harvests, and deploy capital directly to farmers. Funds are custodied in a Soroban escrow contract — never released upfront, never at risk of misappropriation.

3. Verify - A committee of oracle nodes independently reads growth data (soil sensors, satellite imagery, field reports) and reaches consensus on milestone completion. Only when consensus is achieved does the escrow release the next tranche of capital to the farmer.


Platform Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                     AGROCHAIN (React 19 + Vite)                     │
│                                                                     │
│   ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐     │
│   │  MINT    │───▶│ MARKET   │───▶│  FUND    │───▶│  TRACK   │     │
│   │          │    │          │    │          │    │          │     │
│   │ Harvest  │    │ Browse   │    │ Escrow   │    │ Oracle   │     │
│   │ Token    │    │ Batches  │    │ Deposit  │    │ Milestone│     │
│   │ Creation │    │ Compare  │    │ Invest   │    │ Progress │     │
│   │          │    │          │    │          │    │          │     │
│   └──────────┘    └──────────┘    └──────────┘    └──────────┘     │
│                                                                     │
│   ┌─────────────────────────────────────────────────────────┐       │
│   │              ROUTE PROTECTION (JWT AUTH)                 │       │
│   │   Farmer routes · Investor routes · Role-based access   │       │
│   └─────────────────────────────────────────────────────────┘       │
│                                                                     │
│   ┌─────────────────────────────────────────────────────────┐       │
│   │                    API ROUTES                            │       │
│   │   /auth · /harvest-tokens · /escrow · /milestones ·     │       │
│   │   /oracle · /transactions · /profile                     │       │
│   └─────────────────────────────────────────────────────────┘       │
└─────────────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
┌───────┴───────┐     ┌───────┴───────┐     ┌───────┴───────┐
│   Postgres    │     │   Stellar     │     │   Oracle      │
│   16          │     │   Soroban     │     │   Committee   │
│  (pg driver)  │     │   Contracts   │     │   (N-of-M)    │
│               │     │               │     │               │
│  Users        │     │  Harvest      │     │  Soil Sensors │
│  Batches      │     │  Token        │     │  Satellite    │
│  Investments  │     │  Escrow       │     │  Imagery      │
│  Milestones   │     │  Oracle       │     │  Field Reports│
│  Transactions │     │  Adapter      │     │  Consensus    │
└───────────────┘     └───────────────┘     └───────────────┘

Smart Contract System

AgroChain includes three Soroban smart contracts, deliberately kept loosely coupled to maintain clear trust boundaries between data, funds, and token lifecycle.

Contract Overview

Contract Purpose Status
harvest-token Mints a token representing one crop batch; tracks funding progress and lifecycle status (Draft → Funding → Growing → Harvested → Settled). 🚧 Scaffolded
escrow Custodies investor capital for a batch via the standard Soroban token interface (works with any Stellar Asset Contract) and releases milestone-sized payouts to the farmer. 🚧 Scaffolded
oracle-adapter Collects independent readings from a fixed committee of oracle node addresses and computes consensus for milestone completion using an N-of-M-within-tolerance rule. 🚧 Scaffolded

Key Design Decisions

Money as i128 cents - All monetary values are represented as i128 integer cents, matching the Postgres schema in backend/ exactly. No floating point anywhere in the value path, on-chain or off.

Loose Coupling - escrow and harvest-token are not cross-called on-chain. The backend (or any off-chain orchestrator) calls harvest-token::record_funding and escrow::invest in the same logical operation. This keeps the contracts independently deployable and auditable.

Explicit Trust Boundaries - oracle-adapter never moves funds, and escrow never evaluates oracle data directly. mark_milestone_ready on the escrow contract is a separate, explicit call gated by oracle_adapter.require_auth(), so the boundary between "data says X" and "funds move" stays explicit and auditable as two separate transactions.

⚠️ Build Status: The contract code and test suites are written carefully, but have not been compiled or run in the build environment (the sandbox's Rust 1.75 toolchain is too old for the current soroban-sdk). Run cargo test yourself before trusting this code — see contracts/README.md for exact steps.


User Roles

Farmer

  • Creates an account and verifies their identity
  • Mints a Harvest Token representing a crop batch
  • Sets the funding target, expected yield, and milestone schedule
  • Receives milestone-based capital releases as oracle-verified growth data confirms progress
  • Tracks funding progress and lifecycle status in real time

Investor

  • Creates an account and connects a Stellar wallet (Freighter)
  • Browses the marketplace of tokenized harvests
  • Reviews crop details, funding targets, and milestone schedules
  • Funds batches with confidence — capital is custodied in escrow, released only on verified progress
  • Tracks investments and receives returns as harvests settle

Oracle Node

  • Operates an independent data source (soil sensors, satellite imagery, field reports)
  • Submits readings to the oracle-adapter contract
  • Participates in N-of-M consensus for milestone verification
  • Never touches funds — only provides verified data

Developer / Contributor

  • Extends the platform via the documented API routes
  • Implements new crop types and funding models
  • Contributes to the Soroban smart contracts
  • Builds on the open-source codebase

The Funding Loop

AgroChain's flywheel is designed so that every funded harvest compounds the platform's value:

Farmer Mints Harvest Token
     │
     ▼
Investors Fund via Escrow
     │
     ▼
Oracle Committee Verifies Growth ──▶ Milestone Consensus
     │
     ▼
Escrow Releases Capital Tranche
     │
     ▼
Harvest Grows → Settles → Returns Distributed
     │
     ▼
Trust & Volume Grow ──▶ More Farmers ──▶ More Investors ──▶ Loop Continues

The more farmers tokenize their harvests, the more investors deploy capital, the more oracle data validates outcomes, and the more the platform's reputation compounds. The token is not the feature — the trust loop is.


Security & Compliance

AgroChain implements defense-in-depth security practices:

Layer Protection
Authentication bcrypt password hashing (cost 12), JWT sessions in httpOnly cookies
Bot Protection Cloudflare Turnstile on login, signup, and forgot-password
Route Protection Middleware-level JWT verification on all authenticated routes
Role-Based Access Farmer/investor separation enforced server-side (403 on unauthorized actions)
Input Validation Zod schema validation on every API route
SQL Injection 100% parameterized queries via pg — verified with real injection attempts
User Enumeration Identical responses for registered vs. unregistered emails
Rate Limiting General API limit, tight brute-force limit on /auth/login, separate write-action limit
Security Headers Helmet with explicit CSP, HSTS, X-Frame-Options, X-Content-Type-Options
Error Handling Full server-side logging, generic client-facing messages — no stack traces leak
Secret Management .env git-ignored; server refuses to boot with missing/weak JWT_SECRET
Logging Pino redacts Authorization/Cookie headers and password/token/secret fields
Network Safety Testnet by default — mainnet requires explicit opt-in after security audit

Tech Stack

Layer Technology
Blockchain Stellar Network (Soroban smart contracts)
Smart Contracts Rust (2024 edition, soroban-sdk)
Frontend React 19, TypeScript 6, Tailwind CSS 4, Vite 8
State & Data TanStack Query, React Router 7, Axios
Icons Lucide React
Wallet @stellar/freighter-api
Backend Express 5, TypeScript, Node.js
Database PostgreSQL 16 (pg driver)
Validation Zod 4
Authentication bcrypt + JWT (httpOnly cookies)
Bot Protection Cloudflare Turnstile
Security Helmet, express-rate-limit, Pino logging
Testing Vitest, Supertest, Rust cargo test
Linting ESLint (backend), Oxlint (frontend)

Roadmap

V1 - Foundation (Current Phase)

  • ✅ Full authentication flow (register, login, logout, forgot-password)
  • ✅ Role-based access control (farmer vs. investor, enforced server-side)
  • ✅ Cloudflare Turnstile bot protection
  • ✅ Zod validation on every API route
  • ✅ Rate limiting, security headers, SQL injection protection
  • ✅ Harvest token minting flow (frontend + backend)
  • ✅ Marketplace for investors to browse and fund batches
  • ✅ Milestone-based escrow service layer
  • ✅ Oracle verification service layer
  • ✅ Transaction history with CSV export
  • ✅ Freighter wallet integration
  • ✅ Terms of Service and Privacy Policy pages
  • ✅ Soroban contract scaffolds (harvest-token, escrow, oracle-adapter)

V2 - Growth

  • 🚧 Compile and test Soroban contracts (cargo test)
  • 🚧 Wire contracts to backend services (on-chain funding, escrow release)
  • 🚧 Live oracle committee with real sensor/satellite data
  • 🚧 KYC document upload and verification flow
  • 🚧 Real-time growth tracking dashboard
  • 🚧 Investment analytics and portfolio insights

V3 - Scale

  • 🎯 Mainnet deployment (after security audit)
  • 🎯 Additional crop types and regional corridors
  • 🎯 Mobile wallet integration (Freighter mobile)
  • 🎯 Cooperative and aggregator onboarding
  • 🎯 Cross-chain support (Stellar ↔ other networks)

Setup

Prerequisites

Requirement Version
Node.js ≥ 18
npm ≥ 9 (or pnpm / yarn)
PostgreSQL ≥ 14 (16 recommended)
Rust ≥ 1.81 (for contracts)
Cloudflare account For Turnstile (optional for dev)

Installation

# 1. Clone the repository
git clone https://github.com/Northgate-Systems/Agrochain.git
cd agrochain

# 2. Install all dependencies (root + backend + frontend)
npm run install:all

Database Setup

# 1. Configure the backend environment
cd backend
cp .env.example .env

# 2. Fill in DATABASE_URL and generate a JWT_SECRET
#    DATABASE_URL=postgres://user:password@localhost:5432/agrochain
#    JWT_SECRET=$(openssl rand -hex 32)

# 3. Run migrations and seed demo data
npm run migrate
npm run seed   # creates 2 demo users (password: DemoPass123!) and sample data

Cloudflare Turnstile (Bot Protection)

The .env.example files default to Cloudflare's published, always-pass test keypair, so everything works out of the box for local development. Before going anywhere near production:

  1. Create a Turnstile widget at https://dash.cloudflare.com/?to=/:account/turnstile
  2. Put the site key in frontend/.env as VITE_TURNSTILE_SITE_KEY
  3. Put the secret key in backend/.env as TURNSTILE_SECRET_KEY

The backend refuses to start with NODE_ENV=production while the secret key is still the test value — enforced in code, not just documented.

Running the Application

# From the project root — starts both backend and frontend
npm run dev
Service URL
Frontend http://localhost:5173 (proxies /api to backend)
Backend http://localhost:4000

Demo Logins

After seeding, use either:

Role Email Password
Farmer amara@greenvalley.coop DemoPass123!
Investor j.thorne@stellar-agro.com DemoPass123!

Or use the Sign Up page — every account created there works immediately, no manual DB step required.

Available Scripts

Command Description
npm run dev Start both backend and frontend concurrently
npm run dev:backend Start backend only (tsx watch)
npm run dev:frontend Start frontend only (Vite)
npm run build Build both backend and frontend for production
npm run lint Lint both backend (ESLint) and frontend (Oxlint)
npm run typecheck Type-check both backend and frontend
npm run test Run backend tests (Vitest)
npm run migrate Run database migrations
npm run seed Seed demo data

Running Tests

Backend Tests

cd backend
npm run test        # Vitest + Supertest
npm run lint        # ESLint (0 warnings allowed)
npm run typecheck   # TypeScript strict check

Frontend Checks

cd frontend
npm run lint        # Oxlint
npm run build       # tsc -b && vite build (verifies production build)

Soroban Contract Tests

# 1. Install Rust toolchain (if needed)
rustup toolchain install 1.81.0
rustup target add wasm32-unknown-unknown --toolchain 1.81.0
rustup component add rust-src --toolchain 1.81.0

# 2. Install the Soroban CLI (for deploying/invoking, not required for tests)
cargo install --locked soroban-cli

# 3. From the contracts/ directory:
cargo test              # runs all three contracts' unit tests natively
cargo build --release --target wasm32-unknown-unknown   # produces deployable .wasm files

Lint and Format Contracts

Before submitting a PR, ensure Rust contracts pass formatting and lint checks:

cargo fmt --all               # auto-format all contracts
cargo fmt --all -- --check    # check formatting without modifying files
cargo clippy --workspace -- -D warnings  # lint all contracts (warnings are errors)

Contributing

AgroChain is an open-source project and welcomes contributions from developers, designers, and community builders. If you believe in transparent, accountable agricultural finance and want to help build the infrastructure for the next generation of farming, we would love to have you.

Getting Started

  1. Fork the repository
  2. Clone your fork: git clone https://github.com/<your-username>/Agrochain.git
  3. Create a feature branch: git checkout -b feature/amazing-feature
  4. Commit your changes: git commit -m 'feat: add amazing feature'
  5. Push to the branch: git push origin feature/amazing-feature
  6. Open a Pull Request

Development Guidelines

  • Use TypeScript for all new code
  • Follow the existing component and file structure
  • Run npm run lint before committing
  • Validate all API inputs with Zod
  • Test on both desktop and mobile viewports
  • Keep environment variables documented in .env.example
  • Run cargo fmt and cargo clippy before submitting contract changes

Looking for a place to start?

  • Compile and test the Soroban contracts — the code is written but unverified; run cargo test and fix forward
  • Wire contracts to backend services — connect the escrow and harvest-token services to live on-chain calls
  • Implement KYC document upload — add identity verification for farmers and investors
  • Build the oracle committee — integrate real sensor/satellite data sources
  • Enhance the investment dashboard — add analytics and portfolio insights

Resources


Contact

For partnerships, sponsorships, or general questions about AgroChain, please reach out through our official channels.


AgroChain - Decentralized supply-chain finance for smallholder farmers. Built on the Stellar Network. 🌾

About

AgroChain is a supply chain finance platform for farmers on Stellar, enabling crop tokenization, escrow-based payments, investor funding rounds, and oracle-powered verification.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages