Thank you for your interest in contributing to Aframp Backend! This guide will help you get started with contributing to our African crypto onramp/offramp payment infrastructure.
- Code of Conduct
- Getting Started
- Development Setup
- Project Architecture
- Development Workflow
- Coding Standards
- Testing Guidelines
- Database Changes
- Pull Request Process
- Blockchain Integration
- Security Considerations
- Common Tasks
- Getting Help
We are committed to providing a welcoming and inclusive environment. Please be respectful and professional in all interactions.
- Rust 1.75+: Install via rustup
- PostgreSQL 14+: Database for persistence
- Redis 6+: For caching and rate limiting
- Git: Version control
- Docker (optional): For containerized development
- Fork and clone the repository
git clone https://github.com/YOUR_USERNAME/aframp-backend.git
cd aframp-backend- Install dependencies
# Install Rust toolchain
rustup update
# Install development tools
rustup component add clippy rustfmt
cargo install cargo-watch cargo-audit sqlx-cli- Set up environment
cp .env.example .env
# Edit .env with your local configuration- Start services
# Using Docker Compose (recommended)
docker-compose up -d postgres redis
# Or install PostgreSQL and Redis locally- Run database migrations
sqlx migrate run- Build and test
cargo build --features database
cargo test --features databaseKey environment variables you need to configure:
# Stellar Network
STELLAR_NETWORK=testnet # or mainnet
STELLAR_REQUEST_TIMEOUT=10
STELLAR_MAX_RETRIES=3
# Logging
RUST_LOG=debug # Use debug for development, info for production
# Database (for database feature)
DATABASE_URL=postgresql://user:password@localhost/aframp
# Redis (for caching feature)
REDIS_URL=redis://localhost:6379# Development mode with auto-reload
cargo watch -x "run --features database"
# Standard run
cargo run --features database
# Production build
cargo build --release --features database
./target/release/Bitmesh-backendsrc/
├── chains/ # Blockchain integrations
│ └── stellar/ # Stellar blockchain (CNGN stablecoin)
│ ├── client.rs # Horizon API client
│ ├── config.rs # Network configuration
│ ├── errors.rs # Error types
│ ├── types.rs # Data structures
│ └── tests.rs # Unit tests
├── database/ # Data persistence layer
│ ├── *_repository.rs # Repository pattern implementations
│ ├── error.rs # Database error types
│ ├── transaction.rs # Transaction management
│ └── mod.rs # Module exports
├── middleware/ # HTTP middleware
│ ├── logging.rs # Request/response logging
│ └── error.rs # Error handling
├── error.rs # Global error types
├── lib.rs # Library exports (includes Soroban contract)
├── logging.rs # Logging configuration
└── main.rs # Application entry point
migrations/ # Database migrations
contracts/ # Soroban smart contracts
examples/ # Example code
- Stellar Integration: Primary blockchain for CNGN stablecoin
- Database Layer: Repository pattern with SQLx
- Soroban Contracts: Smart contracts for escrow functionality
- Middleware: Logging, error handling, rate limiting
git checkout -b feature/your-feature-name
# or
git checkout -b fix/bug-descriptionfeature/: New featuresfix/: Bug fixesrefactor/: Code refactoringdocs/: Documentation updatestest/: Test additions or updateschore/: Maintenance tasks
Follow the coding standards and write tests for your changes.
# Run all tests
cargo test --features database
# Run specific test
cargo test --features database test_name
# Run with output
cargo test --features database -- --nocapture
# Run clippy for linting
cargo clippy --features database -- -D warnings
# Format code
cargo fmtUse clear, descriptive commit messages:
git add .
git commit -m "feat: add CNGN balance checking endpoint
- Implement balance retrieval from Stellar
- Add input validation
- Include unit tests
- Update API documentation"Commit Message Format:
feat:New featurefix:Bug fixrefactor:Code refactoringdocs:Documentation changestest:Test additions/updateschore:Maintenance tasks
git push origin feature/your-feature-nameThen create a Pull Request on GitHub.
-
Follow Rust naming conventions
snake_casefor functions, variables, modulesPascalCasefor types, traits, enumsSCREAMING_SNAKE_CASEfor constants
-
Error handling
- Use
Result<T, E>for fallible operations - Create custom error types using
thiserror - Provide context in error messages
- Use
-
Async/await
- Use
async fnfor I/O operations - Avoid blocking operations in async context
- Use
tokio::spawnfor concurrent tasks
- Use
-
Documentation
- Document public APIs with
///comments - Include examples in doc comments
- Keep comments up-to-date
- Document public APIs with
// Good: Clear, documented function
/// Fetches account details from Stellar Horizon API
///
/// # Arguments
/// * `address` - Valid 56-character Stellar address
///
/// # Returns
/// Account information including balances and sequence number
///
/// # Errors
/// Returns error if account doesn't exist or network fails
pub async fn get_account(&self, address: &str) -> StellarResult<StellarAccountInfo> {
// Validate input
if !is_valid_stellar_address(address) {
return Err(StellarError::invalid_address(address));
}
// Implementation...
}
// Bad: No documentation, unclear purpose
pub async fn get_acc(&self, a: &str) -> Result<AccInfo, Error> {
// ...
}- Never commit secrets: Use environment variables
- Validate all inputs: Check addresses, amounts, etc.
- Use prepared statements: SQLx prevents SQL injection
- No private keys in code: Non-custodial design only
- Rate limit operations: Protect against abuse
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_stellar_address() {
let valid = "GXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
assert!(is_valid_stellar_address(valid));
}
#[tokio::test]
async fn test_account_fetch() {
let config = StellarConfig::default();
let client = StellarClient::new(config).unwrap();
// Test implementation
}
}- Unit tests: Test individual functions in isolation
- Integration tests: Test component interactions
- Edge cases: Test boundary conditions and error paths
- Documentation: Explain what each test validates
# All tests
cargo test --features database
# Specific module
cargo test --features database stellar::
# With logging
RUST_LOG=debug cargo test --features database -- --nocapture
# Integration tests (requires testnet)
cargo test --features database,integration# Create a new migration
sqlx migrate add descriptive_name
# Edit the generated SQL file in migrations/
# Format: YYYYMMDDHHMMSS_descriptive_name.sql- Idempotent: Use
IF NOT EXISTSwhere applicable - Reversible: Include rollback logic when possible
- Tested: Test migrations on a copy of production data
- Documented: Explain complex changes in comments
- Performance: Consider impact on large tables
-- Create trustlines table
CREATE TABLE IF NOT EXISTS trustlines (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
wallet_address VARCHAR(56) NOT NULL,
asset_code VARCHAR(12) NOT NULL,
asset_issuer VARCHAR(56) NOT NULL,
limit_amount TEXT,
balance TEXT NOT NULL DEFAULT '0',
is_authorized BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(wallet_address, asset_code, asset_issuer)
);
-- Add indexes
CREATE INDEX idx_trustlines_wallet ON trustlines(wallet_address);
CREATE INDEX idx_trustlines_asset ON trustlines(asset_code, asset_issuer);# Run all pending migrations
sqlx migrate run
# Revert last migration
sqlx migrate revert
# Check migration status
sqlx migrate info- Code compiles without warnings
- All tests pass
- New tests added for new functionality
- Code formatted with
cargo fmt - Clippy checks pass with no warnings
- Documentation updated
- Commit messages are clear
- Title: Clear, descriptive title summarizing the change
- Description: Explain what, why, and how
- References: Link related issues
- Screenshots: Include for UI changes
- Breaking changes: Clearly documented
## Description
Brief description of changes
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
Describe testing done
## Checklist
- [ ] Tests pass
- [ ] Code formatted
- [ ] Documentation updated
- [ ] No new warnings- Automated CI/CD runs tests and checks
- At least one maintainer reviews code
- Address feedback and update PR
- Maintainer approves and merges
- Create module in
src/chains/ - Implement common traits
- Add configuration
- Write comprehensive tests
- Update documentation
- Use testnet for development
- Validate addresses before API calls
- Handle rate limits gracefully
- Cache frequently accessed data
- Log all blockchain operations
When working with CNGN:
- Verify trustline exists before transfers
- Validate asset issuer address
- Use string types for amounts (avoid float precision issues)
- Handle XLM fee requirements
- No private keys: Never store or log private keys
- Input validation: Validate all user inputs
- Rate limiting: Implement for all public endpoints
- SQL injection: Use SQLx parameterized queries only
- Secrets management: Use environment variables
- Audit logs: Log sensitive operations
Do NOT open public issues for security vulnerabilities.
Email security concerns to: security@aframp.com
Include:
- Description of vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix (if any)
- Define handler in appropriate module
- Add route in router configuration
- Implement business logic
- Add input validation
- Write unit and integration tests
- Update API documentation
- Create file in
src/database/ - Define repository trait
- Implement with SQLx
- Add error handling
- Write tests with test database
- Update module exports
# Check for outdated dependencies
cargo outdated
# Update dependencies
cargo update
# Test after updating
cargo test --features database
cargo clippy --features database# Run security audit
cargo audit
# Fix vulnerabilities
cargo audit fix- Documentation: Check README.md and STELLAR_INTEGRATION.md
- API Docs: Run
cargo doc --open --features database - Issues: Search existing issues before creating new ones
- Discussions: Use GitHub Discussions for questions
- GitHub Issues: Bug reports and feature requests
- GitHub Discussions: Questions and general discussion
- Pull Requests: Code review and technical discussion
- Use
RUST_LOG=debugfor verbose logging - Run
cargo watchfor automatic rebuilds - Use
cargo clippyto catch common mistakes - Check
cargo docfor inline documentation - Review existing code for patterns and conventions
Contributors are recognized in:
- GitHub contributors page
- Release notes for significant contributions
- Special mentions for major features
Thank you for contributing to Aframp Backend!
Together, we're building the future of African crypto infrastructure powered by CNGN stablecoin and Rust.