The AugustCredits system consists of three main smart contracts:
- AugustPayments (
payments.aug) - Handles deposits, withdrawals, and escrow functionality - AugustCreditsBilling (
billing.aug) - Manages usage tracking, billing calculations, and payment processing - AugustCreditsMetering (
metering.aug) - Handles API request monitoring, rate limiting, and usage metrics collection
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ AugustPayments │ │ AugustCredits │ │ AugustCredits │
│ │ │ Billing │ │ Metering │
│ • Deposits │◄──►│ │◄──►│ │
│ • Withdrawals │ │ • Usage Tracking│ │ • Rate Limiting │
│ • Escrow │ │ • Billing Calc │ │ • Analytics │
│ • Batch Payments│ │ • Payment Proc │ │ • Request Logs │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└───────────────────────┼───────────────────────┘
│
┌─────────────────┐
│ ERC20 Token │
│ (USDC/USDT) │
└─────────────────┘
Purpose: Core payment infrastructure with escrow capabilities
Key Features:
- Secure deposit and withdrawal system
- Escrow creation and management with timeout protection
- Batch payment processing for efficiency
- Emergency withdrawal capabilities
- Contract authorization system
Main Functions:
deposit(amount)- Deposit tokens to user balancewithdraw(amount)- Withdraw tokens from user balancecreateEscrow(id, payee, amount)- Create escrow paymentreleaseEscrow(id)- Release escrow to payeerefundEscrow(id)- Refund escrow to payerprocessPayment(payer, payee, amount)- Direct paymentbatchProcessPayments(payers, payees, amounts)- Batch payments
Purpose: Usage-based billing and payment processing
Key Features:
- User and API endpoint registration
- Dynamic pricing per endpoint
- Usage tracking and billing calculation
- Platform fee management
- Batch billing for multiple users
- Cost estimation and affordability checks
Main Functions:
registerUser(apiKey)- Register new userregisterApiEndpoint(name, price)- Register API endpointrecordUsage(apiKey, endpoint, requests)- Record API usageestimateCost(endpoint, requests)- Estimate usage costcanAffordUsage(user, endpoint, requests)- Check affordabilitybatchBilling(users, endpoints, requests)- Process multiple bills
Purpose: API monitoring, rate limiting, and analytics
Key Features:
- Configurable rate limiting per endpoint
- Real-time request logging
- Usage analytics and reporting
- Daily usage tracking
- Batch analytics retrieval
- Log cleanup and management
Main Functions:
setRateLimit(endpoint, requests, period)- Configure rate limitscheckRateLimit(user, endpoint)- Check if request allowedlogRequest(user, endpoint, requestId, ...)- Log API requestgetEndpointStats(endpoint)- Get endpoint analyticsgetUserStats(user)- Get user analyticsgetDailyUsage(endpoint, day)- Get daily usage stats
- Install August CLI:
curl -sSL https://get.august.dev | bash- Configure your network settings in
august.toml
august deploy --network localhostaugust deploy --network goerliaugust deploy --network mainnetaugust deploy --network polygonThe deploy.aug script provides automated deployment and configuration:
# Deploy to localhost with mock tokens
NETWORK=localhost august run deploy.aug
# Deploy to testnet
NETWORK=goerli august run deploy.aug
# Deploy to mainnet
NETWORK=mainnet august run deploy.augRun the comprehensive test suite:
# Run all tests
august test
# Run specific contract tests
august test tests/payments_test.aug
august test tests/billing_test.aug
august test tests/metering_test.augThe test suite covers:
- ✅ Payment deposits and withdrawals
- ✅ Escrow creation, release, and refunds
- ✅ User and endpoint registration
- ✅ Usage recording and billing
- ✅ Rate limiting and enforcement
- ✅ Analytics and reporting
- ✅ Batch operations
- ✅ Error handling and edge cases
- ✅ Access control and authorization
# Network configuration
NETWORK=localhost|goerli|mainnet|polygon
# Contract addresses (set after deployment)
PAYMENTS_CONTRACT=0x...
BILLING_CONTRACT=0x...
METERING_CONTRACT=0x...
# Token addresses
USDC_MAINNET=0xA0b86a33E6441E6C7C5c8b7b8b8b8b8b8b8b8b8b
USDC_GOERLI=0x07865c6E87B9F70255377e024ace6630C1Eaa37F
USDC_POLYGON=0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174# Platform fee (basis points)
platform_fee = 250 # 2.5%
# Rate limiting
default_rate_limit = 1000 # requests per hour
default_rate_period = 3600 # 1 hour
# Payments
minimum_deposit = "100000000000000000" # 0.1 tokens
escrow_timeout = 604800 # 7 days
# Gas settings
gas_limit = 3000000
gas_price = "20gwei"- All contracts use OpenZeppelin's
Ownablepattern - Critical functions are protected by
onlyOwnermodifier - Contract-to-contract calls are authorized via whitelist
- Prevents API abuse and DoS attacks
- Configurable per endpoint
- Automatic reset based on time windows
- Timeout mechanism prevents locked funds
- Only payer or contract owner can refund
- Atomic release operations
- Emergency withdrawal for user funds
- Contract pause functionality
- Upgrade mechanisms for future improvements
- API Gateway: Integrate rate limiting with
metering.checkRateLimit() - Usage Tracking: Log requests with
metering.logRequest() - Billing: Process usage with
billing.recordUsage() - Analytics: Retrieve stats with batch functions
// Backend: Check rate limit
const [allowed, remaining, resetTime] = await meteringContract.checkRateLimit(
userAddress,
"api-v1"
);
if (!allowed) {
return res.status(429).json({ error: "Rate limit exceeded" });
}
// Backend: Log request
await meteringContract.logRequest(
userAddress,
"api-v1",
requestId,
responseTime,
statusCode,
ipHash
);- Total requests per endpoint
- Unique users per endpoint
- Average response times
- Error rates
- Daily usage patterns
- Revenue tracking
// Get endpoint analytics
const stats = await meteringContract.getEndpointStats("api-v1");
// Get user usage
const userStats = await meteringContract.getUserStats(userAddress);
// Get daily usage
const today = Math.floor(Date.now() / 1000 / 86400) * 86400;
const dailyUsage = await meteringContract.getDailyUsage("api-v1", today);- Insufficient Balance: Ensure users have deposited enough tokens
- Rate Limit Exceeded: Check rate limit settings and user usage
- Unauthorized Access: Verify contract addresses are properly configured
- Gas Estimation Failed: Check for contract pauses or network issues
# Check contract deployment
august verify --network <network>
# View contract state
august call <contract> <function> --network <network>
# Monitor events
august events <contract> --network <network>- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
# Clone repository
git clone https://github.com/augustcredits/contracts.git
cd contracts
# Install dependencies
august install
# Run tests
august test
# Deploy locally
august deploy --network localhostMIT License - see LICENSE file for details.