legend-esc/carbonchain

CarbonChain is a Soroban-native platform for issuing, trading, and retiring tokenized carbon credits. It uses smart contracts to enforce real-world climate accountability through verifier approval, MRV (Monitoring, Reporting, and Verification) oracle integration, and permanent on-chain retirement records.

โ˜… 9Forks 98TypeScriptGitHub โ†—Compare

README

CarbonChain ๐ŸŒฟ

Transparent, tamper-proof carbon credit registry and marketplace built on the Stellar network.

CarbonChain is a Soroban-native platform for issuing, trading, and retiring tokenized carbon credits. It enables smart contracts to enforce real-world climate accountability โ€” verifier multi-sig, MRV oracle integration, and permanent on-chain retirement receipts โ€” in a trust-minimized way.


Features

  • Credit issuance with verifier multi-sig approval
  • Permanent on-chain retirement with tamper-proof certificates
  • On-chain offer-book marketplace for secondary market trading (Stellar DEX AMM integration is a Phase 3 roadmap item)
  • MRV oracle interface for real-time carbon sequestration monitoring
  • IPFS-anchored project documentation (methodology, satellite imagery, audits)
  • Session-based audit trail for all credit lifecycle operations
  • Replay attack protection on all contract state transitions
  • Fractional credits (0.1 tonne resolution via i128 storage)
    • Unit convention: 1 tonne = 1,000,000 units, minimum unit = 100,000 (= 0.1 tonne)
    • All tonnes values must be a positive multiple of 100,000; non-multiples are rejected
  • Anchor info discovery for SEP-10 authenticated interactions
  • Health monitoring for registered verifier nodes
  • Event emission for all state changes
  • Comprehensive error handling with stable error codes

Supported Credit Types

Projects can register credits across the following methodologies:

  • REDD+ โ€” Reduced Emissions from Deforestation and Degradation
  • VCS โ€” Verified Carbon Standard (Verra)
  • Gold Standard โ€” Gold Standard for the Global Goals
  • CDM โ€” Clean Development Mechanism
  • Plan Vivo โ€” Community and ecosystem-based projects
  • Custom โ€” Configurable methodology string for emerging standards

Usage Example

// Initialize the registry contract
contract.initialize(&admin);

// Register a verifier
contract.register_verifier(&verifier);

// Verifier self-configures their own service capabilities
// (verifier signs with their own key โ€” this is NOT an admin operation)
let nonce = contract.get_nonce(&verifier);
let mut capabilities = Vec::new(&env);
capabilities.push_back(ServiceType::CreditApproval);
capabilities.push_back(ServiceType::MRVReview);
contract.configure_verifier_services(&verifier, &capabilities, nonce);

// Submit a credit for approval
let credit_id = contract.submit_credit(
    &issuer,
    &CreditMetadata {
        project_id: String::from_str(&env, "PROJ-001"),
        vintage_year: 2024,
        methodology: String::from_str(&env, "VCS"),
        geography: String::from_str(&env, "NG"),
        tonnes: 1_000_000,   // 1 tonne (1 tonne = 1_000_000 units, i.e. TONNES_SCALE)
        ipfs_hash: String::from_str(&env, "bafybei..."),
    },
);

// Verifier approves and triggers mint
// (requires ServiceType::CreditApproval in configured services,
//  or no services configured โ€” open-capability assumption)
contract.approve_and_mint(&verifier, &credit_id);

// Retire a credit
contract.retire(&buyer, &credit_id, &String::from_str(&env, "2024 Scope 3 offset"));

CLI Example

See the complete issuance, trading, and retirement workflow:

# Run bash demo
./examples/cli_example.sh

# Or run Rust example
cargo run --example cli_example

See docs/guides/DOCTOR_COMMAND.md for CLI environment diagnostics.


Key Features

  • Credit Registry: Register projects, submit credits, enforce verifier approval before minting
  • Retirement Engine: Permanently burn tokens with an immutable on-chain retirement record
  • Marketplace: On-chain offer-book listings with fractional credit support (Stellar DEX AMM integration is a Phase 3 roadmap item)
  • MRV Oracle: Authenticated data ingestion from IoT/satellite feeds with anomaly flagging
  • Session Traceability: Group operations into auditable sessions for compliance
  • Audit Trail: Immutable record of all lifecycle events
  • Replay Protection: Nonce-based multi-level protection on all contract operations
  • Credential Security: Admin keypair never exposed to frontend โ€” all user ops signed via Freighter

Session Traceability & Audit

CarbonChain includes comprehensive session management and operation tracing to ensure all credit interactions are reproducible and auditable.

What this means:

  • Every operation is logged with complete context (who, what, when, result)
  • Sessions group related operations for logical organization
  • Audit trail is immutable for compliance and verification
  • Operations can be replayed deterministically for dispute resolution
  • Replay attacks are prevented through nonce-based protection

Quick example:

// Create a session
const sessionId = await contract.create_session(userAddress);

// Submit attestation within session
const creditId = await contract.submit_credit_with_session(
    sessionId,
    issuer,
    metadata,
    ipfsHash,
    signature
);

// Verify session completeness
const opCount = await contract.get_session_operation_count(sessionId);

// Retrieve full audit log
const auditLog = await contract.get_audit_log(0);

Project Structure

carbonchain/
โ”œโ”€โ”€ contracts/                  # Soroban smart contracts (Rust)
โ”‚   โ”œโ”€โ”€ credit_registry/        # Minting, metadata, verifier multi-sig
โ”‚   โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ lib.rs          # Contract entry points
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ storage.rs      # Persistent data management
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ events.rs       # Event definitions
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ types.rs        # Data structures
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ errors.rs       # Stable error codes
โ”‚   โ”‚   โ””โ”€โ”€ Cargo.toml
โ”‚   โ”œโ”€โ”€ retirement/             # Burn + retirement certificate logic
โ”‚   โ”œโ”€โ”€ marketplace/            # Offer creation, on-chain offer book (DEX AMM is Phase 3)
โ”‚   โ””โ”€โ”€ mrv_oracle/             # Oracle interface for MRV data updates
โ”‚
โ”œโ”€โ”€ api/                        # NestJS backend
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ stellar/            # Stellar SDK service layer
โ”‚   โ”‚   โ”œโ”€โ”€ credits/            # Credit CRUD, issuance flow
โ”‚   โ”‚   โ”œโ”€โ”€ retirement/         # Retirement endpoint + certificate gen
โ”‚   โ”‚   โ”œโ”€โ”€ marketplace/        # Order book, DEX bridge (AMM is Phase 3)
โ”‚   โ”‚   โ”œโ”€โ”€ projects/           # Project profiles, IPFS uploads
โ”‚   โ”‚   โ”œโ”€โ”€ verifiers/          # Verifier registry, co-sign requests
โ”‚   โ”‚   โ””โ”€โ”€ oracle/             # MRV data ingestion webhooks
โ”‚   โ”œโ”€โ”€ test/
โ”‚   โ””โ”€โ”€ package.json
โ”‚
โ”œโ”€โ”€ frontend/                   # Angular 17+ SPA
โ”‚   โ”œโ”€โ”€ src/app/
โ”‚   โ”‚   โ”œโ”€โ”€ core/               # Auth, wallet, HTTP services
โ”‚   โ”‚   โ”œโ”€โ”€ shared/             # Reusable components and pipes
โ”‚   โ”‚   โ”œโ”€โ”€ dashboard/          # Portfolio overview
โ”‚   โ”‚   โ”œโ”€โ”€ marketplace/        # Browse & buy credits
โ”‚   โ”‚   โ”œโ”€โ”€ projects/           # Project detail pages
โ”‚   โ”‚   โ”œโ”€โ”€ retire/             # Retirement wizard
โ”‚   โ”‚   โ”œโ”€โ”€ certificates/       # Retirement certificate viewer
โ”‚   โ”‚   โ””โ”€โ”€ admin/              # Verifier & maintainer panel
โ”‚   โ””โ”€โ”€ package.json
โ”‚
โ”œโ”€โ”€ shared/                     # Shared TypeScript types & constants
โ”œโ”€โ”€ scripts/                    # Deployment & testnet setup scripts
โ”œโ”€โ”€ docs/
โ”‚   โ”œโ”€โ”€ README.md               # Full documentation index
โ”‚   โ”œโ”€โ”€ architecture.md         # System architecture (this repo)
โ”‚   โ”œโ”€โ”€ features/               # Feature-specific documentation
โ”‚   โ””โ”€โ”€ guides/                 # Developer guides
โ”œโ”€โ”€ CLAUDE.md                   # Claude Code context file
โ”œโ”€โ”€ CONTRIBUTING.md             # Contribution guide (Stellar Wave)
โ””โ”€โ”€ README.md

Tech Stack

Layer Technology Purpose
Smart contracts Rust + Soroban SDK Credit registry, retirement, marketplace, oracle
Blockchain Stellar (testnet / mainnet) Asset issuance, native DEX, claimable balances
Backend NestJS (Node.js 18+) REST API, Stellar SDK integration, business logic
Frontend Angular 17+ Marketplace UI, retirement flow, certificate viewer
Storage (off-chain) IPFS / Filecoin via Pinata Project docs, satellite imagery, audit reports
Database PostgreSQL Off-chain indexing, user sessions, event cache
Auth Freighter Wallet + JWT (SEP-10) Stellar wallet-based authentication
Testing (contracts) Soroban test SDK Unit & integration tests
Testing (api) Jest + Supertest API endpoint tests
Testing (frontend) Jasmine + Karma Angular component & E2E tests
CI/CD GitHub Actions Automated test, lint, testnet deploy

Prerequisites


Getting Started

1. Clone the repository

git clone [email protected]:legend-esc/carbonchain.git
cd carbonchain

2. Configure environment variables

cp api/.env.example api/.env
# Fill in ADMIN_SECRET_KEY, JWT_SECRET, and contract IDs โ€” see Environment Variables below

3. Start the full stack with Docker Compose

The docker-compose.yml starts all four services (PostgreSQL, Redis, API, Frontend) in the correct dependency order with health checks:

docker compose up -d
Service URL Description
Frontend http://localhost:4200 Angular SPA (nginx)
API http://localhost:3000 NestJS REST API
Postgres localhost:5432 PostgreSQL 16
Redis localhost:6379 Redis 7 (cache + rate limit)

Check service health:

docker compose ps
docker compose logs -f api

4. Run database migrations

cd api && npm run migration:run

5. (Optional) Local development without Docker

If you prefer to run services individually:

# Start only the backing services
docker compose up -d postgres redis

# Install dependencies
cd api && npm install
cd ../frontend && npm install

# Terminal 1 โ€” NestJS API (port 3000)
cd api && npm run start:dev

# Terminal 2 โ€” Angular frontend (port 4200)
cd frontend && ng serve

Open http://localhost:4200 and connect your Freighter wallet on Stellar testnet.

6. Deploy contracts to testnet

cd scripts
./deploy-testnet.sh

This funds a testnet account, compiles all four Soroban contracts, deploys them, and writes the resulting contract IDs to scripts/contract-ids.testnet.json.


Environment Variables

api/.env

# Stellar
STELLAR_NETWORK=testnet
STELLAR_HORIZON_URL=https://horizon-testnet.stellar.org
STELLAR_SOROBAN_RPC=https://soroban-testnet.stellar.org
ADMIN_SECRET_KEY=S...

# Contract IDs (populated after deploy-testnet.sh)
CREDIT_REGISTRY_CONTRACT_ID=C...
RETIREMENT_CONTRACT_ID=C...
MARKETPLACE_CONTRACT_ID=C...
MRV_ORACLE_CONTRACT_ID=C...

# Database
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/carbonchain

# Auth
JWT_SECRET=your-jwt-secret-here
JWT_EXPIRES_IN=7d

# IPFS
IPFS_API_URL=https://api.pinata.cloud
IPFS_API_KEY=your-pinata-api-key
IPFS_SECRET_KEY=your-pinata-secret

# Redis (#975 โ€” password required; matches REDIS_PASSWORD in docker-compose.yml)
# Generate a strong secret for production: openssl rand -hex 32
REDIS_PASSWORD=changeme-local-dev
REDIS_URL=redis://:changeme-local-dev@localhost:6379

frontend/src/environments/environment.ts

export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000',
  stellarNetwork: 'testnet',
  horizonUrl: 'https://horizon-testnet.stellar.org',
};

Smart Contracts

All contracts live in contracts/ and are written in Rust targeting the Soroban SDK.

Build all contracts

cd contracts
cargo build --target wasm32-unknown-unknown --release

Contracts overview

Contract Stable Error Codes Description
credit_registry 100โ€“126 Mint CCR tokens, store metadata, enforce verifier multi-sig
retirement 200โ€“209 Burn tokens on retirement, write immutable retirement records
marketplace 300โ€“309 Manage offer listings via on-chain offer book (Stellar DEX AMM is Phase 3)
mrv_oracle 400โ€“409 Accept MRV data updates, flag anomalies for re-verification

See docs/features/ERROR_CODES_REFERENCE.md for the full error code reference.


API Reference

Base URL: http://localhost:3000/api/v1

Swagger UI available at http://localhost:3000/api/docs in development.

Method Endpoint Description
GET /credits List credits (filter by type, vintage, geography)
GET /credits/:id Credit detail with full provenance chain
POST /credits/issue Submit a new credit issuance request
POST /credits/:id/retire Retire a credit, generate certificate
GET /projects List registered projects
POST /projects Register a project (uploads docs to IPFS)
GET /certificates/:id Fetch retirement certificate by ID
GET /marketplace/listings Active marketplace listings
POST /marketplace/offer Create a sell offer
GET /verifiers List registered verifiers
POST /auth/challenge Request SEP-10 auth challenge
POST /auth/verify Verify signed challenge, receive JWT

New API Methods

Session Management

Method Description
create_session(initiator) Create new audit session
get_session(session_id) Get session details
get_session_operation_count(session_id) Get operation count in session
get_audit_log(log_id) Get audit log entry

Session-Aware Operations

Method Description
submit_credit_with_session(...) Submit credit with audit logging
approve_and_mint_with_session(...) Approve credit with audit logging
retire_with_session(...) Retire credit with audit logging

Running Tests

# Smart contract tests
cd contracts && cargo test

# Cross-platform path tests
cd contracts && cargo test cross_platform

# API unit + integration tests
cd api && npm run test
cd api && npm run test:e2e

# Frontend tests
cd frontend && ng test

Configuration Validation

Linux / macOS

./validate_all.sh
./pre_deploy_validate.sh

Windows

.\validate_all.ps1
.\pre_deploy_validate.ps1

Environment Diagnostics

anchorkit doctor

The doctor command checks:

  • โœ… Rust toolchain installation
  • โœ… WASM target availability
  • โœ… Wallet configuration
  • โœ… Soroban RPC connectivity
  • โœ… Config file validity
  • โœ… Network connectivity

See docs/guides/DOCTOR_COMMAND.md for complete documentation.


Documentation

Getting Started

  • QUICK_START.md โ€” Quick reference with examples
  • CONTRIBUTING.md โ€” Contribution guidelines (Stellar Wave)
  • CHANGELOG.md โ€” Version history

Feature Documentation

  • docs/features/ERROR_CODES_REFERENCE.md โ€” Stable API error codes
  • docs/features/SEP10_AUTH.md โ€” SEP-10 Freighter authentication
  • docs/features/ANCHOR_INFO_DISCOVERY.md โ€” stellar.toml parsing and caching
  • docs/features/METADATA_CACHE.md โ€” TTL-based metadata caching
  • docs/features/REQUEST_ID_PROPAGATION.md โ€” UUID request tracing
  • docs/features/RETRY_BACKOFF.md โ€” Retry and backoff strategies
  • docs/features/WEBHOOK_MONITOR.md โ€” MRV oracle webhook monitoring
  • docs/features/TRANSACTION_STATE_TRACKER.md โ€” Credit lifecycle state machine
  • docs/features/STATUS_MONITOR.md โ€” Verifier node health monitoring
  • docs/features/ROUTING_STRATEGY.md โ€” DEX routing strategy
  • docs/features/LOGGING.md โ€” Logging system
  • docs/features/DOMAIN_VALIDATION.md โ€” Domain validation for anchors

Guides

  • docs/guides/DOCTOR_COMMAND.md โ€” CLI diagnostics
  • docs/guides/CONTRIBUTING.md โ€” Contribution guidelines
  • docs/guides/ERROR_IMPLEMENTATION_GUIDE.md โ€” Error handling guide
  • docs/guides/RETRY_QUICK_REFERENCE.md โ€” Retry patterns quick reference

See docs/README.md for the complete documentation index.


Contributing

Read CONTRIBUTING.md before submitting a PR for code style, commit conventions, and the PR checklist.

Contributions generated entirely by LLMs without review or understanding are prohibited under Drips Wave terms.


Platform Support

CarbonChain is designed to work seamlessly across all major platforms:

  • โœ… Linux (Ubuntu, Debian, Fedora, etc.)
  • โœ… macOS (Intel and Apple Silicon)
  • โœ… Windows (10/11 with PowerShell + WSL2)

Platform-specific setup

  • Linux / macOS: see main setup instructions above
  • Windows: see WINDOWS_SETUP.md for detailed WSL2 configuration

Security

See SECURITY.md for the vulnerability reporting and responsible disclosure process.

  • No private keys in the API โ€” all user-facing transactions signed client-side via Freighter
  • Stable error codes (100โ€“126) for API compatibility across contract upgrades
  • Replay protection at multiple contract levels with nonce-based verification
  • Immutable audit logs โ€” no delete functions on retirement or session records
  • Authorization checks on all state-mutating operations
  • .claudeignore excludes ADMIN_SECRET_KEY and all secrets from Claude Code context
  • cargo audit runs in CI on every push/PR โ€” high-severity CVEs in Rust dependencies fail the build

Backward Compatibility

All existing contract methods remain unchanged. Session features are opt-in, allowing gradual adoption without breaking existing integrations.


Roadmap

Phase 1 โ€” Foundation โœ…

  • Project architecture & documentation
  • Soroban credit registry contract (v1)
  • Soroban retirement contract
  • Soroban marketplace contract
  • Soroban MRV oracle contract
  • NestJS API scaffold with Stellar SDK integration
  • Angular marketplace frontend
  • Verifier multi-sig flow with reputation scoring
  • IPFS project document upload
  • MRV oracle integration
  • Credit transfer (OTC), splitting, merging, and batch retirement
  • Session traceability & immutable audit trail
  • Nonce-based replay protection on all contract operations
  • SEP-10 Freighter wallet authentication (JWT)
  • Docker Compose full-stack setup
  • CI/CD pipeline (GitHub Actions) with cargo audit
  • Load testing scripts

Phase 2 โ€” Complete & Polish

  • Retirement certificate PDF generation (endpoint exists, CertificateService needs wiring)
  • Retirement certificate viewer UI (/certificates/:id)
  • Mobile-responsive frontend layout
  • Mainnet deployment with production hardening

Phase 3 โ€” Marketplace & Trading

  • Limit order book โ€” price/quantity matching beyond single-offer DEX listings
  • Credit bundling โ€” package multiple credits into a basket offer
  • Automated market maker (AMM) pool for continuous liquidity
  • Price history charts and market analytics dashboard
  • Watchlist & price alerts for specific project credits
  • Secondary market fee distribution to original project issuers

Phase 4 โ€” Credit Lifecycle Extensions

  • Credit merging UI โ€” frontend flow for the existing merge_credits contract function
  • Credit expiry enforcement โ€” automated cron for expire_credit past vintage cutoff
  • Credit dispute resolution UI โ€” verifier/admin panel for dispute workflow
  • Fractional credit splitting wizard โ€” step-by-step UI for split_credit
  • Credit portfolio analytics โ€” COโ‚‚e exposure, vintage spread, methodology breakdown

Phase 5 โ€” Verifier & MRV Ecosystem

  • Verifier onboarding flow โ€” self-service registration with document upload to IPFS
  • Verifier reputation leaderboard โ€” public ranking by approval count vs. dispute ratio
  • MRV data dashboard โ€” real-time satellite/IoT feed visualisation per project
  • Anomaly alert notifications โ€” push/email when MRV oracle flags a project
  • Multi-oracle consensus โ€” require N-of-M oracles to agree before flagging anomaly
  • Automated re-verification triggers โ€” disputed credits auto-queue for re-review

Phase 6 โ€” Compliance & Reporting

  • Corporate buyer dashboard โ€” aggregate retirement receipts grouped by scope (1/2/3)
  • Exportable compliance reports โ€” PDF/CSV for annual ESG disclosures
  • API webhooks for retirement events โ€” push notifications to buyer systems
  • CORSIA / Article 6 labelling โ€” compliance framework tags on credits
  • Double-counting prevention registry โ€” cross-check against national registries via API

Phase 7 โ€” Ecosystem & Integrations

  • Freighter deep-link flows โ€” one-click retirement from external dApps
  • Public embeddable retirement widget โ€” iframe badge for corporate sustainability pages
  • REST API public developer portal โ€” rate-limited open API with API key management
  • Stellar federation address support โ€” human-readable identifiers (e.g. company*carbonchain.io)
  • Cross-chain bridge (EVM) โ€” mirror retirement proofs on Ethereum/Polygon for DeFi integrations

Phase 8 โ€” Operations & Scale

  • PostgreSQL read replica โ€” geographic redundancy for high-read workloads
  • Multi-region deployment โ€” geographic redundancy for API and IPFS pinning
  • On-chain governance โ€” token-weighted voting on methodology standards and fee parameters
  • Contract upgrade governance โ€” time-locked multi-sig for WASM upgrades
  • Public audit dashboard โ€” real-time contract state explorer for transparency

License

License: MIT Stellar โ€” see the LICENSE file for details.


Support

For questions or issues:


Built on Stellar

Contributors

legend-escdependabot[bot]jhayniffymartinzhamesobedebuka41-dotcomakindoyinabraham0-collabdevoclanmaugauwi-hashjanipauwels-sysMJigahicentedward76-sketchmarvs8devOgazielvissamuel834-dotcomlolandriley-wqunrealtim-techwillowgray071-cpuChuks-coderrodunfemisamuel-makercyberdocs120Kingsman-99Eromosele0110henrypetersYoung850marvelousufelixEscelitthelux134edwarddavid929-pnghaisha-hubke747

Issues