This guide covers the default PAYMENT_PROVIDER=crypto architecture in the OFFER-HUB Orchestrator. Every workflow, controller, DTO, and database model described below is verified directly against the production implementation in apps/api and packages/database.
Overview
OFFER-HUB is built around a provider-agnostic core governed by the PaymentProvider interface (Strategy Pattern). While traditional fiat rails often demand complex underwriting or enterprise volume commitments, OFFER-HUB ships with as its default implemented payment rail.
The architecture combines (while exposing a familiar USD-denominated balance experience to users) with via Trustless Work (for non-custodial escrow settlement).
Provider Comparison: AirTM vs. Crypto-Native
OFFER-HUB abstracts payment provider mechanics through the PaymentProvider strategy interface. Below is an architectural comparison between the default crypto-native provider and the AirTM fiat integration:
is the currently implemented PaymentProvider strategy and the default when PAYMENT_PROVIDER is unset.
Invisible Stellar Wallets
A primary design challenge of decentralized marketplace payments is user experience. Traditional Web3 workflows often require users to install wallet software, manage recovery credentials, hold native gas tokens (XLM), and manually approve transaction signatures.
OFFER-HUB addresses this with managed server-side by WalletService.
Marketplace workflows require programmatic and asynchronous transaction signing that client-side browser wallets cannot accommodate:
- Marketplace workflows can require transaction signatures during server-side order, escrow, and dispute-resolution flows without an active browser session.
- The platform wallet acts as the
disputeResolver for refund and split-resolution operations.
- Server-side services process blockchain, reconciliation, and payment events independently of the user's browser session.
- Buyers and sellers interact with numerical USD balances, deposit addresses, and withdrawal buttons without having to understand blockchain mechanics.
It is important to distinguish between the two layers of the system:
- User keypairs are generated and held server-side by the marketplace Orchestrator. Private keys are encrypted at rest with AES-256-GCM. The platform acts as a custodian for these keys to sign on the user's behalf.
- Once funds are committed to an order, they leave the user's balance and are locked directly into a Soroban smart contract operated by Trustless Work. Neither the marketplace operator nor the buyer/seller can unilaterally drain escrowed funds outside contract rules.
POST /api/v1/users │ ▼UsersService.createUser() │ ▼WalletService.createWallet(userId) │ ├─► Generates Stellar Keypair (Keypair.random()) │ ├─ PublicKey: Stored plaintext (e.g., GCV24...) │ └─ SecretKey: Encrypted via AES-256-GCM (SXXXX...) │ ▼Wallet record saved to PostgreSQL (iv:authTag:ciphertext)
- When a user is created via
POST /api/v1/users (UsersController validating with CreateUserDto), UsersService.createUser() delegates to WalletService.createWallet().
- The service generates a fresh Stellar keypair using the official
stellar-sdk.
- The secret seed is encrypted immediately before hitting the database (
model Wallet in Prisma, stored in the secretEncrypted field).
- The user's public key becomes their permanent deposit address, queryable via
GET /api/v1/users/{userId}/wallet/deposit (WalletController).
Security Model & AES-256-GCM Encryption
The security of the crypto-native provider relies on strict separation between the persistent encrypted data in the database and the cryptographic encryption key stored in the runtime environment.
The encryption utility in apps/api/src/utils/crypto.ts implements:
- Advanced Encryption Standard in Galois/Counter Mode (), providing authenticated encryption with associated data (AEAD).
- 256 bits (32 bytes, represented as a 64-character hexadecimal string).
- A 16-byte (128-bit) cryptographically random IV generated via
crypto.randomBytes(16) for each encryption operation.
- A 16-byte (128-bit) GCM authentication tag that verifies the integrity and authenticity of the ciphertext.
- Serialized as three colon-separated hexadecimal strings:
iv:authTag:ciphertext.
Plaintext Stellar Secret Key (S...) +WALLET_ENCRYPTION_KEY (32-byte / 64-hex env var) +Random 16-byte IV (crypto.randomBytes(16)) │ ▼ [ AES-256-GCM Cipher ] │ ▼ IV (hex) : Auth Tag (hex) : Ciphertext (hex) │ ▼Database format: "iv:authTag:ciphertext"
WalletService is designed to prevent persistent exposure of secret material: decrypted private keys are not stored in persistent database tables, returned in API response bodies, or printed in standard application loggers:
- When an operation requires a signature,
WalletService.signTransaction() retrieves the encrypted record from the database.
- The service decrypts the secret key in memory using
WALLET_ENCRYPTION_KEY from the environment.
stellar-sdk's Keypair.fromSecret() signs the transaction envelope XDR.
- The decrypted secret is used in memory to construct a Stellar keypair for signing via
Keypair.fromSecret(). The current implementation does not explicitly zeroize sensitive key material in memory; it relies on standard runtime variable scoping and engine garbage collection.
To generate a cryptographically secure 32-byte hex key for your environment:
$ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Add the generated value to your environment configuration (each environment must generate its own unique key):
# Replace with your newly generated 64-character hex keyWALLET_ENCRYPTION_KEY=<your-64-character-hex-key>
Treat WALLET_ENCRYPTION_KEY with the highest sensitivity. If this key is lost, all user private keys in the database become cryptographically unrecoverable, preventing the Orchestrator from signing further transactions for those wallets. While smart contract escrow recovery depends on the specific contract rules, dispute resolver signers, and timeout clauses, available wallet balances become permanently inaccessible.
Horizon Monitoring & Deposit Detection
OFFER-HUB automatically tracks incoming deposits without asking users to submit transaction hashes or proofs of payment.
The orchestrator includes a background listener service (BlockchainMonitorService) that subscribes to Stellar's Horizon Server to detect incoming deposits and credit user balances:
- During module initialization (
onModuleInit), BlockchainMonitorService queries existing active wallets in the database and establishes a connection to the Horizon SSE payment stream endpoint (/accounts/:publicKey/payments?cursor=now) for each account.
- The stream processor verifies that:
- The incoming asset code matches the configured
STELLAR_USDC_ASSET_CODE (defaults to USDC).
- The asset issuer matches the configured
STELLAR_USDC_ISSUER.
- The recipient account matches the user's public key.
- Upon verification,
BlockchainMonitorService executes a prisma.$transaction that atomically credits the user's available balance and creates an immutable payment record containing the transaction hash.
- To prevent duplicate credits, the service maintains an in-memory set (
processedTxHashes) for immediate stream filtering and queries the database for existing payment records before initiating the transaction. A unique database constraint on the transaction hash acts as the definitive lock, automatically aborting concurrent duplicate attempts.
- Because the stream initializes with
cursor('now'), payments received while the monitoring service is offline, restarting, or disconnected are not replayed automatically by the Horizon stream. Furthermore, because streams are established on service startup, newly created user wallets are tracked upon service restart or monitor re-subscription rather than instant real-time registration.
Deposit deduplication currently operates at the transaction-hash level rather than the individual Stellar operation-ID level. Stellar transactions containing multiple relevant payment operations therefore require special operational handling to avoid incorrect accounting.
Because Horizon SSE streams with cursor('now') do not automatically ingest historical missed deposits after process downtime, discrepancies between the Stellar on-chain account balance and the internal PostgreSQL available balance can arise if deposits occur while the service is down. Operators should maintain high service availability and implement periodic off-chain reconciliation scripts (comparing Horizon balance queries against internal balances) to detect and credit unrecorded deposits.
USDC Asset & Network Settings
OFFER-HUB uses USDC issued on the Stellar network. Stellar uses specific account addresses to identify non-native asset issuers.
Before any Stellar account can hold a custom token like USDC, it must establish a trustline with the token's issuing account using the changeTrust operation.
- When a wallet is initialized or funded in testnet,
WalletService.createWallet() invokes Friendbot and calls setupTestTrustline() from testnet.utils.ts, executing a changeTrust operation targeting the configured STELLAR_USDC_ISSUER.
- In production mainnet,
WalletService.setupTrustline(userId) exists on WalletService as an independent helper containing the logic to sign and submit a changeTrust operation for an active user, but WalletController intentionally does not expose an unauthenticated public route for trustlines. On Mainnet, operators have two execution options:
- Invoke
WalletService.setupTrustline(userId) within an internal onboarding worker or provisioning script using the Orchestrator's internal service container.
- Submit a Stellar transaction envelope containing a
ChangeTrustOperation signed by the user's secret key (or funded via a sponsor account) using the stellar-sdk.
Testnet to Mainnet Migration Guide
Follow this step-by-step checklist when promoting your OFFER-HUB Orchestrator deployment from staging/testnet to production mainnet.
Switching from testnet to mainnet does not transfer testnet balances or automatically recreate accounts on the public ledger. Mainnet deployment should occur in an isolated production environment with a clean database and dedicated production keys.
Update your production .env or container orchestration secret manager:
# Provider SelectionPAYMENT_PROVIDER=crypto # Stellar Mainnet ConfigurationSTELLAR_NETWORK=mainnetSTELLAR_HORIZON_URL=https://horizon.stellar.orgSTELLAR_USDC_ASSET_CODE=USDCSTELLAR_USDC_ISSUER=GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN # Production Wallet Encryption Key (never reuse testnet keys! Generate a unique 64-hex key)WALLET_ENCRYPTION_KEY=<your-64-character-hex-key> # Trustless Work Mainnet APITRUSTLESS_API_URL=https://api.trustlesswork.com/v1TRUSTLESS_API_KEY=your_key_id.your_key_secretTRUSTLESS_WEBHOOK_SECRET=tw_whsec_your_actual_webhook_secret
Before the first API startup, run the Orchestrator bootstrap script:
The bootstrap process creates the platform user and its Stellar wallet, then outputs the PLATFORM_USER_ID value that must be added to the production environment:
PLATFORM_USER_ID=<generated-platform-user-id>
BootstrapValidatorService validates at application startup that the configured user exists in PostgreSQL and has an active Stellar wallet.
Fund the account with sufficient native XLM to satisfy the Stellar account reserve, trustline subentry reserve, and transaction fees.
In testnet, WalletService.createWallet() invokes Friendbot to automatically fund accounts and establish the USDC trustline. On Mainnet, Friendbot does not exist. createWallet() only generates the keypair and stores secretEncrypted in the database. Before any Mainnet account can receive USDC, it must first be activated on-chain with sufficient native XLM to satisfy the Stellar account reserve, trustline subentry reserve, and transaction fees.
Before onboarding live buyers:
- Generate a scoped API key using your master key:
curl -X POST https://api.yourmarketplace.com/api/v1/auth/api-keys \ -H "Authorization: Bearer $OFFERHUB_MASTER_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Mainnet Smoke Test", "scopes": ["read", "write"] }'
Save the returned key (e.g., ohk_live_...) to your shell environment:
export API_KEY="ohk_live_..."
- Register a test user via
POST /api/v1/users:
curl -X POST https://api.yourmarketplace.com/api/v1/users \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{ "externalUserId": "test-buyer-001", "email": "test-buyer@yourmarketplace.com", "type": "BUYER" }'
- Query
GET /api/v1/users/{userId}/wallet/deposit to get their Stellar public address:
curl https://api.yourmarketplace.com/api/v1/users/usr_test123/wallet/deposit \ -H "Authorization: Bearer $API_KEY"
-
- Transfer sufficient native XLM from your external funding wallet to the user's deposit address to satisfy the Stellar account reserve, trustline subentry reserve, and transaction fees.
- Establish a trustline for
STELLAR_USDC_ASSET_CODE with issuer STELLAR_USDC_ISSUER. Because WalletController does not expose an unauthenticated public route for trustlines, execute this operation using one of two approaches:
- Call
WalletService.setupTrustline(userId) inside an administrative script or internal onboarding pipeline.
- Submit a
ChangeTrustOperation targeting STELLAR_USDC_ISSUER signed with the account's keypair.
- Because
BlockchainMonitorService establishes Horizon SSE stream connections during module initialization (onModuleInit), restart the Orchestrator (or trigger monitor re-subscription) to ensure the newly provisioned test wallet is actively streamed. Then transfer (Mainnet) from an external exchange or wallet to the deposit address. If USDC is transferred before the trustline is confirmed on-chain, the Stellar network will reject the transaction with op_no_trust.
- Check that
BlockchainMonitorService detects the payment and credits the user's available balance:
curl https://api.yourmarketplace.com/api/v1/users/usr_test123/balance \ -H "Authorization: Bearer $API_KEY"
- Submit a test withdrawal of via
POST /api/v1/withdrawals (WithdrawalsController validating with CreateWithdrawalDto under ApiKeyGuard). Ensure that the destination wallet address (destinationRef) is also an active account on Stellar Mainnet with an established USDC trustline (STELLAR_USDC_ISSUER); otherwise, the outbound transfer will fail on-chain with op_no_trust:
curl -X POST https://api.yourmarketplace.com/api/v1/withdrawals \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "userId": "usr_test123", "amount": "0.50", "currency": "USD", "destinationType": "crypto", "destinationRef": "GDQP2KPQGKIHYJGXNUIYOMHARUARCA7DJT5FO2FFOOUJ3EQRQGPGAVRQ" }'
CreateWithdrawalDto requires destinationType: "crypto" and destinationRef containing the destination Stellar address. Unlike the AirTM flow, crypto-native withdrawals are executed synchronously and do not require a separate commit step. The service deducts the available balance, submits the Stellar payment through the configured provider, and returns WITHDRAWAL_COMPLETED on success. If submission fails, it attempts to restore the available balance and marks the withdrawal as failed.
Key Management, Backups & Disaster Recovery
Operating an invisible wallet infrastructure places custodial responsibility on the marketplace host. Adhere to these industry best practices:
- Back up the PostgreSQL database and the
WALLET_ENCRYPTION_KEY in completely separate security perimeters.
- Store encrypted PostgreSQL snapshots (containing the encrypted wallet ciphertext) on cloud storage with immutability/WORM policies.
- Store
WALLET_ENCRYPTION_KEY in dedicated secrets infrastructure (such as AWS Secrets Manager, Google Cloud Secret Manager, or HashiCorp Vault), never inside repository git tracking or application containers.
Because the cryptographic functions in crypto.ts read WALLET_ENCRYPTION_KEY directly from process.env, rotating the encryption key cannot be done via an in-app runtime call. Key rotation requires an operational migration procedure using a dedicated script:
- Take an encrypted snapshot of the PostgreSQL database and verify backup restoration in an isolated staging environment before proceeding.
- Temporarily place the Orchestrator into maintenance mode or pause inbound transaction handling to prevent concurrent writes.
- Run a dedicated offline migration script that loads both
OLD_WALLET_ENCRYPTION_KEY and NEW_WALLET_ENCRYPTION_KEY. The script iterates through wallet.secretEncrypted, decrypts each record with the old key, re-encrypts the secret seed with the new key (generating a fresh 16-byte IV and auth tag in iv:authTag:ciphertext format), and commits the updates in batches inside prisma.$transaction.
- Update the production environment variable to
WALLET_ENCRYPTION_KEY=new_key.
- Perform a smoke test decryption check, restart the Orchestrator, and securely archive or destroy the obsolete key only after verifying operational stability.
Next Steps
- Wallets Guide — User-facing invisible wallet integration and balance overview
- Deposits Guide — Flow of funds for incoming USDC transactions
- Withdrawals Guide — Outbound payout pipeline to external Stellar addresses
- Escrow Lifecycle — Detailed Soroban escrow states and Trustless Work contract execution
- Configuration Reference — Complete environment variables catalog