This guide outlines security best practices for deploying and operating the GXQ STUDIO flash loan arbitrage system with profit distribution.
NEVER commit private keys to version control
✅ DO:
# Use environment variables
WALLET_PRIVATE_KEY=your_private_key_here
# Or use hardware wallets for production
# Ledger, Trezor, etc.❌ DON'T:
// Never hardcode private keys
const privateKey = "5J4k3L2m..."; // NEVER DO THISAll sensitive data must be in .env file (never committed)
Required variables:
# Wallet Configuration
SOLANA_RPC_URL=https://your-rpc-endpoint.com
WALLET_PRIVATE_KEY=your_base58_private_key
# QuickNode (Optional but recommended for production)
QUICKNODE_RPC_URL=https://your-quicknode-endpoint.solana-mainnet.quiknode.pro/
QUICKNODE_API_KEY=your_api_key
# Profit Distribution
RESERVE_WALLET_DOMAIN=monads.skr
DAO_WALLET_ADDRESS=DmtAdUSzFvcBymUmRFgPVawvoXbqdS2o18eZNpe5XcWWUse private RPC endpoints for production
✅ Recommended:
- QuickNode (paid, reliable, high performance)
- Helius (paid, MEV protection)
- Private self-hosted nodes
❌ Not Recommended for Production:
- Public free RPCs (rate limited, unreliable)
- Shared endpoints
Always validate before signing transactions
// Pre-flight checks
if (profitAmount <= 0) {
throw new Error('Invalid profit amount');
}
if (!recipientAddress.isValid()) {
throw new Error('Invalid recipient address');
}
// Check balance before transfer
const balance = await connection.getBalance(sourceWallet.publicKey);
if (balance < transferAmount) {
throw new Error('Insufficient balance');
}
// Simulate transaction first
const simulation = await connection.simulateTransaction(transaction);
if (simulation.value.err) {
throw new Error('Transaction simulation failed');
}Protect against front-running and sandwich attacks
// Use Jito bundles for MEV protection
const bundleId = await mevProtection.applyJitoBundle(transactions);
// Or use private RPC
const signature = await mevProtection.usePrivateRPC(transaction);
// Set appropriate priority fees
const priorityFee = await mevProtection.calculatePriorityFee('high');Encrypt wallet private keys at rest
# Use encrypted environment variables
# Tools like AWS Secrets Manager, HashiCorp Vault, etc.
# Or encrypt locally
openssl enc -aes-256-cbc -in wallet.key -out wallet.key.enc- All private keys stored securely (not in code)
- Environment variables configured
- RPC endpoint is production-grade (QuickNode, Helius, etc.)
- SNS domain resolution tested (
monads.skr) - Wallet addresses verified (reserve, DAO)
- Profit distribution percentages validated (sum to 1.0)
- Gas buffer configured appropriately
- Min profit threshold set conservatively
- Test on Solana devnet first
- Verify profit distribution with test amounts
- Test SNS domain resolution
- Verify transaction confirmations
- Test error handling and retry logic
- Monitor gas costs
- Test with small real amounts on testnet
- Set up transaction monitoring
- Configure alerts for failed transactions
- Monitor RPC health
- Track profit distribution success rate
- Monitor gas expenditure
- Set up analytics dashboard
- Configure logging (centralized if possible)
- Rate limiting configured
- Maximum transaction size limits
- Emergency stop mechanism
- Backup RPC endpoints configured
- Transaction confirmation timeouts set
- Error alerting configured
❌ Bad:
const slippage = 0.50; // 50% - Too high!✅ Good:
const slippage = 0.01; // 1% - Reasonable
const dynamicSlippage = await calculateDynamicSlippage(marketVolatility);❌ Bad:
await connection.sendTransaction(transaction);
// Assuming success without confirmation✅ Good:
const signature = await sendAndConfirmTransaction(
connection,
transaction,
[signer],
{ commitment: 'confirmed', maxRetries: 3 }
);❌ Bad:
const daoWallet = new PublicKey('DmtAdUSzF...');✅ Good:
const daoWallet = new PublicKey(process.env.DAO_WALLET_ADDRESS);
if (!daoWallet.isValid()) {
throw new Error('Invalid DAO wallet address');
}❌ Bad:
try {
await distributeProfits();
} catch (error) {
console.log('Failed'); // Lost transaction!
}✅ Good:
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
await distributeProfits();
break; // Success
} catch (error) {
if (attempt === maxRetries - 1) throw error;
await sleep(Math.pow(2, attempt) * 1000); // Exponential backoff
}
}-
Immediately stop all operations
# Kill all processes pkill -f "node dist/index.js"
-
Transfer all funds to new secure wallet
- Create new wallet with hardware device
- Transfer all SOL and tokens
- Update environment variables
-
Rotate all credentials
- RPC endpoints
- API keys
- Wallet addresses
-
Review transaction history
- Check for unauthorized transactions
- Document any losses
- Report to relevant parties
-
Check transaction signature
solana confirm <signature> -u mainnet-beta
-
Review logs for error details
tail -f logs/application.log | grep ERROR -
Verify balances
solana balance <wallet_address>
-
Retry with adjusted parameters
- Increase priority fee
- Adjust slippage
- Use different RPC endpoint
-
Use manual wallet mapping
resolver.registerManualMapping('monads.skr', actualWalletAddress);
-
Verify SNS registry
- Check Bonfida SNS documentation
- Verify domain ownership
- Check TLD configuration
-
Fallback to direct address
const reserveWallet = new PublicKey(process.env.RESERVE_WALLET_FALLBACK);
-
Code Audit
- Review all transaction signing code
- Verify profit distribution logic
- Check for potential exploits
- Review error handling
-
Security Audit
- Penetration testing
- Smart contract audit (if applicable)
- Infrastructure security review
- Access control review
-
Financial Audit
- Verify profit calculations
- Test distribution percentages
- Validate fee calculations
- Check for rounding errors
- Regulatory: Understand local cryptocurrency regulations
- Tax: Track all profits for tax reporting
- AML/KYC: Consider requirements for large transactions
- Liability: Understand smart contract risks
// Log all distributions for audit trail
const distributionLog = {
timestamp: Date.now(),
profitAmount: amount,
reserveShare: reserveAmount,
userShare: userAmount,
daoShare: daoAmount,
signature: txSignature,
reserveWallet: reserveAddress.toString(),
userWallet: userAddress.toString(),
daoWallet: daoAddress.toString(),
};
// Store in persistent storage
await logDistribution(distributionLog);Implement automatic shutoff for suspicious activity:
const DAILY_PROFIT_LIMIT = 100 * 1e9; // 100 SOL
const HOURLY_TRANSACTION_LIMIT = 50;
if (dailyProfit > DAILY_PROFIT_LIMIT) {
console.error('Daily profit limit exceeded - shutting down');
await emergencyShutdown();
}
if (hourlyTransactions > HOURLY_TRANSACTION_LIMIT) {
console.error('Transaction rate limit exceeded - pausing');
await pauseOperations(3600); // 1 hour pause
}Maintain a list of emergency contacts:
- Dev team lead
- Security team
- RPC provider support
- Exchange contacts (if needed)
Security is paramount when handling financial transactions. Always:
- Test thoroughly on devnet/testnet
- Start with small amounts
- Monitor continuously
- Have emergency procedures ready
- Keep private keys secure
- Use production-grade infrastructure
Remember: Once a transaction is confirmed on Solana, it cannot be reversed. Always double-check before signing.