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.
- 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
tonnesvalues 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
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
// 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"));See the complete issuance, trading, and retirement workflow:
# Run bash demo
./examples/cli_example.sh
# Or run Rust example
cargo run --example cli_exampleSee docs/guides/DOCTOR_COMMAND.md for CLI environment diagnostics.
- 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
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);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
| 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 |
- Node.js 18+ and npm 9+
- Rust (stable toolchain) โ rustup.rs
- Soroban CLI โ
cargo install --locked [email protected] --features opt - Docker โ for local PostgreSQL
- Freighter browser extension โ freighter.app
- A Stellar testnet keypair โ laboratory.stellar.org
git clone [email protected]:legend-esc/carbonchain.git
cd carbonchaincp api/.env.example api/.env
# Fill in ADMIN_SECRET_KEY, JWT_SECRET, and contract IDs โ see Environment Variables belowThe 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 apicd api && npm run migration:runIf 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 serveOpen http://localhost:4200 and connect your Freighter wallet on Stellar testnet.
cd scripts
./deploy-testnet.shThis funds a testnet account, compiles all four Soroban contracts, deploys them, and writes the resulting contract IDs to scripts/contract-ids.testnet.json.
# 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:6379export const environment = {
production: false,
apiUrl: 'http://localhost:3000',
stellarNetwork: 'testnet',
horizonUrl: 'https://horizon-testnet.stellar.org',
};All contracts live in contracts/ and are written in Rust targeting the Soroban SDK.
cd contracts
cargo build --target wasm32-unknown-unknown --release| 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.
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 |
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 |
# 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 testLinux / macOS
./validate_all.sh
./pre_deploy_validate.shWindows
.\validate_all.ps1
.\pre_deploy_validate.ps1anchorkit doctorThe 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.
QUICK_START.mdโ Quick reference with examplesCONTRIBUTING.mdโ Contribution guidelines (Stellar Wave)CHANGELOG.mdโ Version history
docs/features/ERROR_CODES_REFERENCE.mdโ Stable API error codesdocs/features/SEP10_AUTH.mdโ SEP-10 Freighter authenticationdocs/features/ANCHOR_INFO_DISCOVERY.mdโ stellar.toml parsing and cachingdocs/features/METADATA_CACHE.mdโ TTL-based metadata cachingdocs/features/REQUEST_ID_PROPAGATION.mdโ UUID request tracingdocs/features/RETRY_BACKOFF.mdโ Retry and backoff strategiesdocs/features/WEBHOOK_MONITOR.mdโ MRV oracle webhook monitoringdocs/features/TRANSACTION_STATE_TRACKER.mdโ Credit lifecycle state machinedocs/features/STATUS_MONITOR.mdโ Verifier node health monitoringdocs/features/ROUTING_STRATEGY.mdโ DEX routing strategydocs/features/LOGGING.mdโ Logging systemdocs/features/DOMAIN_VALIDATION.mdโ Domain validation for anchors
docs/guides/DOCTOR_COMMAND.mdโ CLI diagnosticsdocs/guides/CONTRIBUTING.mdโ Contribution guidelinesdocs/guides/ERROR_IMPLEMENTATION_GUIDE.mdโ Error handling guidedocs/guides/RETRY_QUICK_REFERENCE.mdโ Retry patterns quick reference
See docs/README.md for the complete documentation index.
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.
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)
- Linux / macOS: see main setup instructions above
- Windows: see
WINDOWS_SETUP.mdfor detailed WSL2 configuration
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
.claudeignoreexcludesADMIN_SECRET_KEYand all secrets from Claude Code contextcargo auditruns in CI on every push/PR โ high-severity CVEs in Rust dependencies fail the build
All existing contract methods remain unchanged. Session features are opt-in, allowing gradual adoption without breaking existing integrations.
- 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
- Retirement certificate PDF generation (endpoint exists, CertificateService needs wiring)
- Retirement certificate viewer UI (
/certificates/:id) - Mobile-responsive frontend layout
- Mainnet deployment with production hardening
- 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
- Credit merging UI โ frontend flow for the existing
merge_creditscontract function - Credit expiry enforcement โ automated cron for
expire_creditpast 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
- 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
- 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
- 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
- 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: MIT Stellar โ see the LICENSE file for details.
For questions or issues:
- Check the
docs/documentation files - Review the API specification at
/api/docs - Examine the test cases in
contracts/*/src/lib.rs - Open a GitHub issue at [email protected]:legend-esc/carbonchain.git
Built on Stellar