for development setup check readme.md
This document provides a comprehensive technical overview of the order lifecycle in the NEDA "Stablenode" aggregator from initial order creation through final settlement or refund. The system implements a sophisticated EVM payment processing pipeline with ERC-4337 Account Abstraction integration and support for multiple blockchain service providers (Alchemy recommended, Thirdweb Engine legacy) for wallet management.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β COMPLETE ORDER LIFECYCLE β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. USER CREATES ORDER (via API)
β
βββ Aggregator validates request
βββ Creates PaymentOrder in database (status: order_initiated)
β
β
2. AGGREGATOR GENERATES RECEIVE ADDRESS
β
βββ Calls Blockchain Service Provider (Alchemy recommended, Thirdweb legacy)
βββ Creates ERC-4337 smart account: 0xRECEIVE_ADDRESS_123
βββ Stores ReceiveAddress in database
βββ Returns address to user
β
β
3. USER SENDS CRYPTO
β
βββ User transfers tokens to: 0xRECEIVE_ADDRESS_123
β
β
4. AGGREGATOR DETECTS DEPOSIT (via Blockchain Webhooks)
β
βββ Webhook receives Transfer event (Alchemy Notify or Thirdweb Insight)
βββ Validates: correct token, amount, receive address
βββ Updates order status: crypto_deposited
β
β
5. AGGREGATOR CREATES ORDER ON GATEWAY CONTRACT
β
βββ Prepares transaction:
β β’ FROM: AGGREGATOR_SMART_ACCOUNT (0x03Ff...)
β β’ TO: Gateway Contract
β β’ FUNCTION: createOrder(token, amount, rate, recipient, refundAddress)
β
βββ Sends via Blockchain Service Provider:
β β’ Signs with AGGREGATOR_PRIVATE_KEY (via Alchemy or Thirdweb)
β β’ Transfers funds: 0xRECEIVE_ADDRESS_123 β Gateway Contract
β
βββ Gateway Contract emits: OrderCreated event
βββ Updates database: order_created, records gateway_id
β
β
6. PROVIDER MATCHING
β
βββ Creates LockPaymentOrder (status: pending)
βββ Notifies available providers
βββ Provider claims order
β
β
7. PROVIDER FULFILLS ORDER (Off-chain)
β
βββ Provider sends fiat to recipient
βββ Provider submits proof of payment
βββ Aggregator validates fulfillment
β
β
8. AGGREGATOR SETTLES ORDER ON GATEWAY CONTRACT
β
βββ Prepares transaction:
β β’ FROM: AGGREGATOR_SMART_ACCOUNT (0x03Ff...)
β β’ TO: Gateway Contract
β β’ FUNCTION: settle(orderId, provider, settlePercent)
β
βββ Sends via Blockchain Service Provider:
β β’ Signs with AGGREGATOR_PRIVATE_KEY (via Alchemy or Thirdweb)
β
βββ Gateway Contract:
β β’ Releases funds to provider
β β’ Deducts protocol fees
β β’ Emits: OrderSettled event
β
βββ Updates database: order_fulfilled
β
β
9. ORDER COMPLETE β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ALTERNATIVE: REFUND PATH β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
REFUND TRIGGERS:
β’ Order timeout (no provider claims within ORDER_REFUND_TIMEOUT)
β’ Provider cancellation (exceeds REFUND_CANCELLATION_COUNT)
β’ Manual admin refund
β
β
AGGREGATOR REFUNDS ORDER
β
βββ Prepares transaction:
β β’ FROM: AGGREGATOR_SMART_ACCOUNT (0x03Ff...)
β β’ TO: Gateway Contract
β β’ FUNCTION: refund(fee, orderId)
β
βββ Sends via Blockchain Service Provider (Alchemy or Thirdweb)
β
βββ Gateway Contract:
β β’ Returns funds to user's refundAddress
β β’ Emits: OrderRefunded event
β
βββ Updates database: order_refunded
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ORDER INITIATION ARCHITECTURE β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CLIENT API DATABASE ALCHEMY/THIRDWEB
β β β β
β POST /v1/sender/ β β β
β orders β β β
ββββββββββββββββββββββ>β β β
β β β β
β β Validate sender β β
β β & token config β β
β ββββββββββββββββββββββ>β β
β β<ββββββββββββββββββββββ€ β
β β Sender & Token OK β β
β β β β
β β Calculate Fees: β β
β β β’ sender_fee = % β β
β β β’ network_fee β β
β β β’ protocol_fee = 0 β β
β β β’ total = amount+feesβ β
β β β β
β β β β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β IF USE_ALCHEMY_FOR_RECEIVE_ADDRESSES β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β β
β β CreateSmartAccount(owner, chainID, salt) β
β ββββββββββββββββββββββββββββββββββββββββββββββ>β
β β β β’ Generate unique β
β β β salt (timestamp) β
β β β β’ Compute CREATE2 β
β β β address β
β β<ββββββββββββββββββββββββββββββββββββββββββββββ€
β β Smart Account Addr β β
β β (0x9876737E...) β β
β β β β
β β β οΈ Webhook creation β β
β β SKIPPED β β
β β β β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β ELSE (Using Thirdweb Engine) β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β β
β β CreateServerWallet()β β
β ββββββββββββββββββββββββββββββββββββββββββββββ>β
β β<ββββββββββββββββββββββββββββββββββββββββββββββ€
β β Wallet Address β β
β β β β
β β CreateTransferWebhook(address, token) β
β ββββββββββββββββββββββββββββββββββββββββββββββ>β
β β<ββββββββββββββββββββββββββββββββββββββββββββββ€
β β Webhook ID & Secret β β
β β β β
β β β β
β β BEGIN TRANSACTION β β
β ββββββββββββββββββββββ>β β
β β β β
β β Create TransactionLog β
β β (status: initiated) β β
β ββββββββββββββββββββββ>β β
β β β β
β β Create PaymentOrder β β
β β β’ amount β β
β β β’ amount_paid = 0 β β
β β β’ sender_fee β β
β β β’ network_fee β β
β β β’ protocol_fee = 0 β β
β β β’ receive_address β β
β β β’ status = initiatedβ β
β ββββββββββββββββββββββ>β β
β β β β
β β Create ReceiveAddress β
β β β’ address β β
β β β’ valid_until β β
β β β’ label β β
β ββββββββββββββββββββββ>β β
β β β β
β β Create PaymentOrderRecipient β
β β β’ institution β β
β β β’ account_id β β
β β β’ account_name β β
β β β’ currency β β
β ββββββββββββββββββββββ>β β
β β β β
β β IF Thirdweb: β β
β β Create PaymentWebhook β
β β β’ webhook_id β β
β β β’ webhook_secret β β
β β β’ callback_url β β
β ββββββββββββββββββββββ>β β
β β β β
β β COMMIT TRANSACTION β β
β ββββββββββββββββββββββ>β β
β β<ββββββββββββββββββββββ€ β
β β Transaction OK β β
β β β β
β 201 Created β β β
β { β β β
β order_id, β β β
β receive_address, β β β
β amount + fees, β β β
β valid_until β β β
β } β β β
β<ββββββββββββββββββββββ€ β β
β β β β
β β β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PAYMENT DETECTION (POST-CREATION) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β β β
β User sends crypto β β β
β to receive_address β β β
β β β β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β IF Thirdweb Webhook Active β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β β
β β POST /v1/insight/webhook β
β β (Transfer event) β β
β β<ββββββββββββββββββββββββββββββββββββββββββββββ€
β β β β
β β Update amount_paid β β
β ββββββββββββββββββββββ>β β
β β β β
β β Check: β β
β β amount_paid >= β β
β β total_amount? β β
β ββββββββββββββββββββββ>β β
β β β DB Trigger: β
β β β check_payment_ β
β β β order_amount() β
β β β validates payment β
β β<ββββββββββββββββββββββ€ β
β β Status: validated β β
β β β β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β ELSE (Alchemy - No Webhook Yet) β
β β ββββββββββββββββββββββββββββββββββββββββββββ
β β β β
β β β οΈ PAYMENT DETECTION NOT IMPLEMENTED β
β β β β
β β Options: β β
β β 1. Alchemy Notify webhooks (recommended) β
β β 2. Polling mechanism β
β β 3. Blockchain indexer extension β
β β β β
-
Fee Calculation
sender_fee= Percentage of order amount (e.g., 1%)network_fee= Blockchain gas fee estimateprotocol_fee= Platform fee (currently 0)total_amount= amount + sender_fee + network_fee + protocol_fee
-
Receive Address Generation
- Alchemy: Deterministic CREATE2 address with unique salt (timestamp-based)
- Thirdweb: Server-managed wallet creation via Engine API
-
Webhook Management
- Thirdweb: Automatic webhook creation for transfer monitoring
- Alchemy: Webhook creation skipped (requires separate Alchemy Notify setup)
-
Database Trigger
check_payment_order_amount()validates thatamount_paid >= total_amount- Prevents order fulfillment with insufficient payment
- Runs automatically on order status updates
-
Payment Detection Gap (Alchemy)
β οΈ When using Alchemy receive addresses, payment detection is not yet implemented- Orders will be created but won't automatically update when crypto is deposited
- Critical: Requires implementation before production use
- Options:
- A. Alchemy Notify (recommended) - Set up webhooks in Alchemy Dashboard
- B. Polling - Background job to check address balances
- C. Indexer - Extend existing blockchain indexer to monitor Alchemy addresses
Note: The system currently focuses exclusively on EVM-compatible chains (Ethereum, Base, Arbitrum, Polygon, etc.). Tron support has been removed.
- Order Service: Handles order creation and smart contract interactions (
services/order/) - Indexer Service: Monitors blockchain events and updates database state (
services/indexer/) - Service Manager: Routes operations between Alchemy and Thirdweb services (
services/manager.go) - Alchemy Service: Manages smart accounts via Alchemy Account Abstraction APIs (
services/alchemy.go) - Engine Service: Manages wallet operations via Thirdweb Engine API (
services/engine.go) - Receive Address Service: Generates temporary deposit addresses for orders (
services/receive_address.go) - Priority Queue Service: Manages order processing queues (
services/priority_queue.go)
Alchemy (Recommended):
- Wallet Management: Creates and manages ERC-4337 smart accounts using deterministic deployment
- Transaction Signing: Direct cryptographic signing with self-managed keys
- Event Monitoring: Alchemy Notify API for webhook events
- Key Storage: Self-managed in environment variables
- Cost: $0-49/month (free tier sufficient)
Thirdweb Engine (Legacy):
- Wallet Management: Creates and manages ERC-4337 smart accounts via Engine API
- Transaction Signing: Signs all transactions using Engine vault
- Webhook System: Thirdweb Insight for blockchain events (Transfer, OrderCreated, OrderSettled, OrderRefunded)
- Key Storage: Securely stores keys in Thirdweb Engine vault
- Cost: $99-999/month subscription
- Ent ORM: Database schema and operations (
ent/) - PostgreSQL: Primary data store
- Redis: Caching and session management
- Gateway Contract: Main order processing contract
- EntryPoint Contract: ERC-4337 Account Abstraction entry point
- SimpleAccount: Smart wallet implementation
- ERC20 Tokens: Supported payment tokens
File: controllers/index.go
Function: Order creation endpoints
// Entry point for order creation requests
func (ctrl *Controller) CreateOrder(ctx *gin.Context) {
// Validates request payload
// Authenticates user
// Creates initial order record
}Database Operations:
- Creates
PaymentOrderentity with statusorder_initiated - Links to
Recipient,Token, andNetworkentities - Generates unique order ID and receive address
File: services/receive_address.go
// Creates ERC-4337 smart accounts via Alchemy or Thirdweb
func (s *ReceiveAddressService) CreateSmartAddress(ctx context.Context, label string) (string, error) {
// If USE_ALCHEMY_FOR_RECEIVE_ADDRESSES=true
if useAlchemy {
return s.alchemyService.CreateSmartAccount(ctx, owner, chainID, salt)
// Generates deterministic CREATE2 address with unique salt
}
// Legacy: Thirdweb Engine
return s.engineService.CreateServerWallet(ctx, label)
// Calls Thirdweb Engine API to create a new smart account
}Database Operations:
- Creates
ReceiveAddressentity - Sets expiration time based on
RECEIVE_ADDRESS_VALIDITY - Links to payment order
File: services/indexer/evm.go
// Monitors blockchain for incoming transfers on EVM chains
func (s *IndexerEVM) IndexReceiveAddress(ctx context.Context, token *ent.Token, address string, fromBlock int64, toBlock int64, txHash string) (*types.EventCounts, error) {
// Scans for ERC-20 Transfer events to receive address
// Validates transfer amount and token
// Triggers order processing
}Event Processing:
- Listens for ERC-20
Transferevents - Validates transfer amount meets order requirements
- Updates order status to
crypto_deposited
File: controllers/index.go
Function: handleTransferEvent
func (ctrl *Controller) handleTransferEvent(ctx *gin.Context, event types.ThirdwebWebhookEvent) error {
// Processes incoming transfer events
// Validates against pending orders
// Triggers order creation on blockchain
}Database Operations:
- Updates
PaymentOrderstatus - Creates
TransactionLogentries - Records transfer transaction hash
File: services/order/evm.go
// Prepares order for blockchain submission on EVM chains
func (s *OrderEVM) CreateOrder(order *ent.PaymentOrder) error {
// Encrypts recipient details
// Prepares smart contract call data
// Submits via Account Abstraction (ERC-4337)
}Smart Contract Interaction:
- Calls
Gateway.createOrder()function - Passes encrypted recipient data
- Uses ERC-4337 UserOperation for gas-less execution
Files:
services/alchemy.go- Alchemy service (recommended)services/engine.go- Thirdweb Engine (legacy)
// Alchemy: Direct transaction signing
func (s *AlchemyService) SendUserOperation(ctx context.Context, userOp UserOperation) (string, error) {
// Signs with self-managed AGGREGATOR_PRIVATE_KEY
// Submits via Alchemy Account Abstraction API
// Returns operation hash for tracking
}
// Thirdweb Engine: Vault-managed signing
func (s *EngineService) SendTransactionBatch(ctx context.Context, chainID int64, address string, txPayload []map[string]interface{}) (queueID string, err error) {
// Calls Thirdweb Engine API
// Engine signs transaction with AGGREGATOR_PRIVATE_KEY (stored in vault)
// Returns queue ID for tracking
}Process Flow:
- Aggregator prepares transaction payload (createOrder call data)
- Routes to appropriate service (Alchemy or Thirdweb) via Service Manager
- Service signs with
AGGREGATOR_PRIVATE_KEY - Transaction submitted to blockchain
- Funds transferred: receive address β Gateway contract
- Gateway contract validates and executes order creation
File: services/contracts/Gateway.go
Generated from: Gateway.sol
// Gateway contract createOrder function
function createOrder(
address _token,
uint256 _amount,
uint96 _rate,
address _senderFeeRecipient,
uint256 _senderFee,
address _refundAddress,
string memory messageHash
) external returns (bytes32 orderId)Contract Operations:
- Validates token and amount
- Calculates protocol fees
- Emits
OrderCreatedevent - Returns unique order ID
File: controllers/index.go
Function: handleOrderCreatedEvent
func (ctrl *Controller) handleOrderCreatedEvent(ctx *gin.Context, event types.ThirdwebWebhookEvent) error {
// Processes OrderCreated events from Gateway contract
// Updates order status in database
// Triggers provider notification
}Event Structure:
type OrderCreatedEvent struct {
BlockNumber int64
TxHash string
Token string
Amount decimal.Decimal
OrderId string
Rate decimal.Decimal
MessageHash string
}Database Operations:
- Updates
PaymentOrderstatus toorder_created - Records blockchain transaction hash
- Creates
LockPaymentOrderfor provider matching - Updates
TransactionLogwith event details
File: services/common/order.go
// Creates lock orders for provider matching
func CreateLockOrder(order *ent.PaymentOrder) error {
// Splits order into provider-sized chunks
// Creates LockPaymentOrder entities
// Notifies available providers
}Provider Matching Logic:
- Queries available providers by token and amount
- Considers provider rates and availability
- Creates lock orders with expiration times
Files:
controllers/provider/provider.go- Provider endpointsservices/order/evm.go- Settlement execution
// Processes provider settlement
func (s *OrderEVM) SettleOrder(lockOrder *ent.LockPaymentOrder, provider *ent.ProviderProfile) error {
// Validates provider settlement
// Calls Gateway.settle() function
// Updates order status
}Settlement Process:
- Provider claims lock order
- Provides off-chain payment proof
- System validates settlement
- Calls
Gateway.settle()with settlement details - Emits
OrderSettledevent
File: controllers/index.go
Function: handleOrderSettledEvent
func (ctrl *Controller) handleOrderSettledEvent(ctx *gin.Context, event types.ThirdwebWebhookEvent) error {
// Processes settlement events
// Updates order status to fulfilled
// Releases provider funds
}Database Operations:
- Updates
PaymentOrderstatus toorder_fulfilled - Updates
LockPaymentOrderstatus tosettled - Records final settlement transaction
- Calculates and records fees
Conditions for Refund:
- Order timeout (no provider settlement)
- Provider cancellation
- System error conditions
- Manual admin refund
File: services/order/evm.go
// Processes order refunds
func (s *OrderEVM) RefundOrder(order *ent.PaymentOrder) error {
// Validates refund conditions
// Calls Gateway.refund() function
// Returns funds to user
}Refund Process:
- System detects refund condition
- Calls
Gateway.refund()with order ID - Contract validates and processes refund
- Emits
OrderRefundedevent - Updates database status
controllers/
βββ index.go # Main API endpoints, webhook handlers
βββ provider/provider.go # Provider-specific endpoints
βββ sender/sender.go # Sender/user endpoints
services/
βββ order/
β βββ evm.go # EVM-based order processing
βββ indexer/
β βββ evm.go # EVM event indexing
βββ common/
β βββ order.go # Shared order logic
β βββ indexer.go # Shared indexing logic
βββ contracts/ # Generated contract bindings
βββ alchemy.go # Alchemy service (recommended)
βββ engine.go # Thirdweb Engine service (legacy)
βββ manager.go # Service manager (routes between providers)
βββ receive_address.go # Receive address generation
βββ priority_queue.go # Order queue management
ent/
βββ paymentorder/ # Main order entities
βββ lockpaymentorder/ # Provider lock orders
βββ transactionlog/ # Transaction history
βββ receiveaddress/ # Generated addresses
βββ network/ # Blockchain networks
utils/
βββ userop.go # Account Abstraction utilities
βββ rpc_events.go # Event decoding utilities
βββ crypto/ # Cryptographic utilities
# ============================================
# ALCHEMY SERVICE (Recommended)
# ============================================
ALCHEMY_API_KEY=your_alchemy_api_key
ALCHEMY_BASE_URL=https://api.g.alchemy.com/v2
ALCHEMY_GAS_POLICY_ID=your_gas_policy_id # Optional
# ============================================
# THIRDWEB ENGINE (Legacy)
# ============================================
ENGINE_BASE_URL=https://your-engine-instance.com
ENGINE_ACCESS_TOKEN=your-vault-access-token
THIRDWEB_SECRET_KEY=your-thirdweb-secret-key
# ============================================
# SERVICE SELECTION
# ============================================
USE_ALCHEMY_SERVICE=false # Set to true to use Alchemy
USE_ALCHEMY_FOR_RECEIVE_ADDRESSES=true # Use Alchemy for receive addresses
# ============================================
# AGGREGATOR ACCOUNT - Operational Wallet
# ============================================
# The main smart account that executes all order operations
AGGREGATOR_SMART_ACCOUNT=0x03Ff9504c7067980c1637BF9400E7b7e3655782c
# Keys controlling the aggregator account
AGGREGATOR_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----..."
AGGREGATOR_PUBLIC_KEY="-----BEGIN RSA PUBLIC KEY-----..."
# ============================================
# SMART CONTRACT ADDRESSES
# ============================================
ENTRY_POINT_CONTRACT_ADDRESS=0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789
# ============================================
# ORDER CONFIGURATION
# ============================================
ORDER_FULFILLMENT_VALIDITY=1 # minutes
ORDER_REFUND_TIMEOUT=5 # minutes
RECEIVE_ADDRESS_VALIDITY=30 # minutes
REFUND_CANCELLATION_COUNT=3 # max provider cancellations before refund- Create Alchemy Account: Sign up at https://alchemy.com
- Get API Key: Create app and copy API key
- Configure Environment: Set
ALCHEMY_API_KEYandUSE_ALCHEMY_FOR_RECEIVE_ADDRESSES=true - Set Up Webhooks (for payment detection):
- Go to Alchemy Dashboard β Notify
- Create Address Activity webhook
- Point to:
https://your-domain.com/v1/alchemy/webhook
- Optional Gas Manager: Configure gas sponsorship policies
Advantages:
- Free tier sufficient for most use cases ($0-49/month)
- Self-managed keys (no third-party vault)
- Direct API access
- Comprehensive documentation
- Deploy Engine: Self-hosted or cloud instance
- Configure: Set
ENGINE_BASE_URLandENGINE_ACCESS_TOKEN - Import Keys: Add
AGGREGATOR_PRIVATE_KEYto Engine vault - Webhooks: Automatic via Thirdweb Insight
Note: Thirdweb Engine costs $99-999/month. Migration to Alchemy recommended.
Each supported EVM network requires:
- RPC endpoint configuration
- Gateway contract address
- Supported token contracts
- Gas price and fee settings
- Webhook configuration (Alchemy Notify or Thirdweb Insight)
The Gateway contracts are already deployed on each supported network and their addresses are stored in the database. The system uses pre-deployed contracts rather than deploying them during runtime.
-- From scripts/db_data/dump.sql
INSERT INTO "public"."networks" (..., "gateway_contract_address", ...) VALUES
-- Ethereum Sepolia Testnet
('0xCAD53Ff499155Cc2fAA2082A85716322906886c2'),
-- Arbitrum Sepolia Testnet
('0x87B321fc77A0fDD0ca1fEe7Ab791131157B9841A'),
-- Base Sepolia Testnet
('0x...') -- Add your deployed contract addressEach network entity stores its Gateway contract address:
type Network struct {
ChainID int64
Identifier string
RPCEndpoint string
GatewayContractAddress string // Pre-deployed contract address
BundlerURL string
PaymasterURL string
}Orders are created using the pre-deployed Gateway address from the database:
func (s *OrderEVM) CreateOrder(order *ent.PaymentOrder) error {
gatewayAddress := order.Edges.Token.Edges.Network.GatewayContractAddress
// Calls createOrder() on the existing contract
}The Gateway contracts are deployed outside of the aggregator application:
- Contract Deployment - Gateway contracts deployed manually/via scripts per network
- Database Configuration - Contract addresses added to database via
scripts/db_data/dump.sql - Code Generation - Go bindings generated in
services/contracts/Gateway.go
Advantages:
- Stability: Contract addresses don't change between deployments
- Gas Efficiency: No deployment costs during runtime
- Security: Contracts can be audited and verified before use
- Multi-Network: Each network has its optimized Gateway instance
- Upgradability: Can deploy new versions and update database references
To support a new blockchain network:
- Deploy Gateway Contract on the new network
- Update Database with new network record including gateway address
- Configure RPC/Bundler endpoints for the network
- Test Integration with the aggregator
Related Files:
services/contracts/Gateway.go # Generated contract bindings
services/order/evm.go # EVM Gateway interactions
scripts/db_data/dump.sql # Network/Gateway configuration
ent/network/ # Database schema for networks
- Failed transactions are retried with exponential backoff
- Stuck orders are automatically refunded after timeout
- Provider failures trigger alternative provider selection
- Admin endpoints for order status override
- Manual refund processing capabilities
- Provider performance monitoring and adjustment
- Structured logging with correlation IDs
- Transaction-level tracing
- Performance metrics collection
- Real-time order status updates
- Provider performance metrics
- System health monitoring
- Aggregator private key controls all operations
- Hardware security module (HSM) recommended for production
- Key rotation procedures documented
- All contracts are audited implementations
- Multi-signature controls for critical functions
- Emergency pause mechanisms available
- Recipient information encrypted at rest
- PII handling compliant with regulations
- Secure communication channels required
- Indexed queries for order lookups
- Connection pooling for high throughput
- Read replicas for analytics queries
- Batch processing for multiple orders
- Gas price optimization strategies
- RPC endpoint failover mechanisms
- PostgreSQL database with replication
- Redis for caching and sessions
- Load balancers for API endpoints
- Monitoring and alerting systems
- Horizontal scaling of API services
- Database sharding by network/region
- Separate indexing services per blockchain
- Service provider horizontal scaling (Alchemy or Thirdweb)
The system uses three distinct wallet types (EVM-only):
-
Receive Addresses (Temporary, Many)
- Created via Alchemy (recommended) or Thirdweb Engine for each order
- ERC-4337 smart accounts with deterministic CREATE2 deployment
- Alchemy: Self-managed keys, deterministic address generation
- Thirdweb: Keys managed by Engine vault
- Purpose: Receive user deposits
-
Aggregator Smart Account (Permanent, One)
- Your operational identity:
AGGREGATOR_SMART_ACCOUNT - Controlled by
AGGREGATOR_PRIVATE_KEY - Executes all business logic transactions
- Purpose: Create, settle, and refund orders
- Your operational identity:
-
Gateway Contract (Escrow)
- Pre-deployed on each EVM network
- Holds funds during order processing
- Releases funds on settlement or refund
User Deposit β Receive Address (Alchemy/Thirdweb-managed)
β
Aggregator detects deposit (Webhook: Alchemy Notify or Thirdweb Insight)
β
Aggregator creates order β Gateway Contract (via Service Provider)
β
Funds: Receive Address β Gateway Contract
β
Provider fulfills order
β
Aggregator settles β Gateway releases funds to Provider
Alchemy (Recommended):
- Deterministic smart account creation via CREATE2
- Direct transaction signing with self-managed keys
- Alchemy Notify for webhook events
- Gas Manager for sponsored transactions (optional)
- Cost-effective ($0-49/month)
Thirdweb Engine (Legacy):
- Vault-managed wallet creation and signing
- Thirdweb Insight for webhook events
- Automatic gas management
- Higher cost ($99-999/month)
- Separation of Concerns: Receive addresses isolated from operational account
- Key Management:
- Alchemy: Self-managed in environment variables
- Thirdweb: Stored in Engine vault
- Transaction Control: Only
AGGREGATOR_SMART_ACCOUNTcan execute order operations - Escrow Protection: User funds held in Gateway contract until settlement/refund
- EVM-Only: Focused security model for EVM chains
This documentation provides a complete technical overview of the order lifecycle in the NEDA aggregator system. Each phase involves multiple components working together to provide a seamless EVM payment processing experience while maintaining security, reliability, and scalability through modern blockchain service providers (Alchemy recommended).