A comprehensive smart contract system for tracking agricultural products from farm to consumer, ensuring transparency, fair pricing, and fraud detection.
Agri-Trace is a decentralized application built on Ethereum that enables:
- End-to-end traceability of agricultural products through the supply chain
- QR code verification for consumers to verify product authenticity
- Fair pricing mechanisms to protect farmers with minimum support prices
- Fraud detection using statistical analysis and pattern recognition
- Payment escrow for secure transactions between supply chain participants
- Consumer-friendly interface for easy product verification
- Product Tracking: Track products through 9 distinct stages (Planted → Growing → Harvested → Processed → Packaged → In Transit → Distributed → Retail → Sold)
- Quality Monitoring: Record temperature, humidity, and quality scores at each stage
- IPFS Integration: Store product documentation and certificates on IPFS
- Role-Based Access Control: Secure access with farmer, distributor, retailer, and regulator roles
- QR Code Registry: Link physical QR codes to blockchain product records
- Fair Pricing: Enforce minimum support prices with farmer rating bonuses
- Fraud Detection: Detect price anomalies and timing violations using statistical methods
- Payment Escrow: Secure conditional payments with automatic execution
- Consumer Interface: Simplified verification for end consumers
The system consists of 6 main smart contracts:
┌─────────────────────┐
│ AgricultureSupplyChain │ (Core tracking)
└──────────┬──────────┘
│
┌──────┴──────┬──────────────┬──────────────┐
│ │ │ │
┌───▼───┐ ┌────▼────┐ ┌──────▼──────┐ ┌───▼──────┐
│Payment│ │QR Registry│ │Fair Pricing │ │ Fraud │
│Contract│ │ │ │ Contract │ │Detection │
└───────┘ └──────────┘ └─────────────┘ └──────────┘
│ │ │ │
└────────────┴──────────────┴──────────────┘
│
┌───────▼────────┐
│ConsumerInterface│
└─────────────────┘
Core contract for product tracking
- Manages product lifecycle through 9 stages
- Stores quality data and IPFS hashes
- Handles ownership transfers
- Role-based stage updates
QR code management
- Registers QR codes linked to products
- Validates QR code authenticity
- Tracks QR code status (active/inactive)
Escrow and payment handling
- Creates conditional payments
- Manages escrow balances
- Automatic payment execution
- Secure fund transfers
Price protection for farmers
- Enforces minimum support prices
- Farmer rating system
- Market price validation
- Volatility protection
Advanced fraud detection
- Price anomaly detection using statistical methods
- Timing violation detection
- Actor blacklisting
- Comprehensive risk scoring
Consumer-friendly verification
- Simple product verification by ID or QR code
- Farmer reputation display
- Product journey tracking
- Batch verification support
- Foundry (latest version)
- Node.js and pnpm (for package management)
- Git
- Clone the repository
git clone https://github.com/Chitrangath/Agri-Trace.git
cd Agri-Trace- Install dependencies
forge install OpenZeppelin/openzeppelin-contracts- Verify installation
forge buildRun all tests:
forge testRun tests with verbosity:
forge test -vvvRun specific test file:
forge test --match-path test/AgricultureSupplyChainTest.t.solDeploy to local Anvil node:
# Start Anvil
anvil
# In another terminal, deploy
forge script script/DeployAll.s.sol:DeployAll --rpc-url http://localhost:8545 --broadcast- Set up environment variables
Create a
.envfile:
PRIVATE_KEY=your_private_key_here
SEPOLIA_RPC_URL=https://sepolia.infura.io/v3/your_key
SEPOLIA_ETHERSCAN_API_KEY=your_etherscan_api_key- Deploy to Sepolia
forge script script/DeploySepolia.s.sol:DeploySepolia \
--rpc-url $SEPOLIA_RPC_URL \
--broadcast \
--verify \
-vvvv- Verify contracts on Etherscan
The
--verifyflag will automatically verify contracts. Alternatively:
forge verify-contract <CONTRACT_ADDRESS> <CONTRACT_NAME> \
--chain sepolia \
--etherscan-api-key $SEPOLIA_ETHERSCAN_API_KEYAfter deployment, addresses are saved to:
- Local:
deployments/all-contracts.env - Sepolia:
deployments/sepolia-contracts.env
- Register as a farmer (admin only initially):
supplyChain.grantFarmerRole(farmerAddress);
fairPricing.registerFarmer(farmerAddress);- Create a product:
uint256 productId = supplyChain.createProduct(
100, // quantity
500, // price (in wei)
locationHash, // location hash
ipfsHashes // array of IPFS hashes
);- Update product stage:
supplyChain.updateProductStage(productId, ProductStage.Harvested);- Add quality data:
supplyChain.addQualityData(
productId,
25, // temperature
50, // humidity
90, // quality score
certificationHash, // certification hash
ipfsHash // IPFS hash
);- Get roles:
supplyChain.grantDistributorRole(distributorAddress);
supplyChain.grantRetailerRole(retailerAddress);- Transfer ownership:
supplyChain.transferOwnership(productId, newOwner, newPrice);- Verify product by ID:
ProductSummary memory summary = consumerInterface.verifyProduct(productId);- Verify product by QR code:
VerificationResult memory result = consumerInterface.verifyByQRCode(qrHash);- Get farmer reputation:
FarmerReputation memory reputation = consumerInterface.getFarmerReputation(farmerAddress);- Configure contracts:
consumerInterface.configureContracts(
supplyChainAddress,
qrRegistryAddress,
fairPricingAddress
);- Set minimum prices:
fairPricing.updateGlobalMinimumPrice(1 ether);- Manage fraud detection:
fraudDetection.updateDetectionConfig(newConfig);- ✅ OpenZeppelin contracts (battle-tested)
- ✅ ReentrancyGuard protection
- ✅ Access control with roles
- ✅ Pausable contracts for emergencies
- ✅ Custom errors for gas efficiency
- ✅ Safe transfer functions (Address.sendValue)
⚠️ Price Oracle: Currently uses a simplified implementation. For production, integrate with Chainlink or similar oracle.⚠️ Admin Functions: Consider implementing timelock and multi-sig for production.⚠️ Upgradeability: Contracts are not upgradeable. Consider proxy pattern for production if needed.
The contracts are optimized for gas efficiency:
- Packed structs to minimize storage slots
- Custom errors instead of require strings
- Efficient storage patterns
- Calldata usage for arrays
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
MIT License - see LICENSE file for details
For questions or issues, please open an issue on GitHub.