Gas-Smart DeFi Bots: Execute Trades Only When Network Fees Hit Your Target Price
Gas conditional execution is the feature most trading bot builders overlook until it eats their profits — your bot spots a clean arbitrage, fires the transaction, and watches the gas cost flip the trade from green to red. If you're building automated trading strategies on EVM or Solana, you need wallet infrastructure that can gate execution on gas price thresholds, not just on market conditions.
The Real Cost of Ignoring Gas
Most trading bot tutorials show you how to spot opportunities. Few show you how to not get rekt by execution costs. Gas is a variable you can control — not by predicting it, but by refusing to trade when it's too expensive. A perpetual futures bot running on Hyperliquid might tolerate high gas for large positions. A small-cap arbitrage loop on Ethereum absolutely cannot.
The problem compounds fast. You're writing logic to monitor prices, manage positions, handle slippage, and now you also need to build gas monitoring, threshold checks, transaction signing, key management, and policy enforcement from scratch. That's months of infrastructure work before you write a single line of strategy logic.
WAIaaS gives you that infrastructure layer as a self-hosted service: gas conditional execution, 15 DeFi protocol integrations, a 21-type policy engine with 4 security tiers, and a 7-stage transaction pipeline — all exposed through a clean REST API or TypeScript/Python SDK.
Gas Conditional Execution: Only Trade When It's Cheap
WAIaaS's transaction pipeline includes a dedicated gas condition stage. You set the threshold in your transaction payload, and the daemon holds the transaction in queue until the network gas price meets your target — then executes automatically.
Here's what this looks like in practice using the SDK:
import { WAIaaSClient } from '@waiaas/sdk';
const client = new WAIaaSClient({
baseUrl: process.env['WAIAAS_BASE_URL'] ?? 'http://localhost:3100',
sessionToken: process.env['WAIAAS_SESSION_TOKEN'],
});
// Send token only when gas is within budget
const tx = await client.sendToken({
type: 'TRANSFER',
to: 'recipient-address',
amount: '0.1',
});
console.log(`Transaction submitted: ${tx.id} (status: ${tx.status})`);
// Poll until the pipeline clears gas condition and executes
const POLL_TIMEOUT_MS = 60_000;
const startTime = Date.now();
while (Date.now() - startTime < POLL_TIMEOUT_MS) {
const result = await client.getTransaction(tx.id);
if (result.status === 'COMPLETED') {
console.log(`Executed. Hash: ${result.txHash}`);
break;
}
if (result.status === 'FAILED') {
console.error(`Failed: ${result.error}`);
break;
}
await new Promise(resolve => setTimeout(resolve, 1000));
}
The 7-stage transaction pipeline — validate → auth → policy → wait → execute → confirm — means your transaction sits in the wait stage until the gas condition clears. You don't have to write retry logic, mempool monitoring, or cancellation handlers. The daemon owns that.
One Wallet, 15 DeFi Protocols
For a trading bot, protocol breadth directly maps to strategy optionality. WAIaaS integrates 15 DeFi protocol providers: aave-v3, across, dcent-swap, drift, erc8004, hyperliquid, jito-staking, jupiter-swap, kamino, lido-staking, lifi, pendle, polymarket, xrpl-dex, and zerox-swap.
That means a single wallet session can:
- Swap on Jupiter on Solana
- Hedge a position on Drift perpetuals
- Bridge proceeds via LI.FI or Across
- Earn yield on idle capital through Kamino or Aave v3
- Trade prediction markets on Polymarket
All through the same REST API endpoint pattern. Here's a Jupiter swap call:
curl -X POST http://127.0.0.1:3100/v1/actions/jupiter-swap/swap \
-H "Content-Type: application/json" \
-H "Authorization: Bearer wai_sess_<token>" \
-d '{
"inputMint": "So11111111111111111111111111111111111111112",
"outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"amount": "1000000000"
}'
The Hyperliquid integration covers perpetual futures, spot trading, and sub-accounts — useful if your strategy involves delta-neutral positioning across spot and perps. Drift is similarly available for Solana-native perpetuals exposure. Across and LI.FI give you two independent cross-chain bridging paths, so your bot can route capital to wherever the yield or arb exists.
Policy Engine as Risk Management Infrastructure
A trading bot without risk controls is a liability. WAIaaS ships a policy engine with 21 policy types and 4 security tiers (INSTANT, NOTIFY, DELAY, APPROVAL). For a trading bot, the most relevant are:
- SPENDING_LIMIT — 4-tier amount-based execution: small trades go instantly, large ones require human approval
- PERP_MAX_LEVERAGE — hard cap on futures leverage, enforced at the infrastructure layer not the strategy layer
- PERP_MAX_POSITION_USD — max position size in USD
- PERP_ALLOWED_MARKETS — whitelist of markets the bot is permitted to trade
- CONTRACT_WHITELIST — only interact with pre-approved contracts
- RATE_LIMIT — max transactions per period
- VENUE_WHITELIST — restrict which trading venues the bot can access
- ACTION_CATEGORY_LIMIT — DeFi action category limits
Policies follow default-deny: transactions are blocked unless explicitly allowed by a matching policy. This means your bot can't accidentally trade a token you haven't whitelisted, even if a bug in your strategy logic tries to.
Here's a policy setup for a trading bot with a $500 daily cap and a 15-minute delay on anything over $1,000:
curl -X POST http://127.0.0.1:3100/v1/policies \
-H "Content-Type: application/json" \
-H "X-Master-Password: my-secret-password" \
-d '{
"walletId": "<wallet-uuid>",
"type": "SPENDING_LIMIT",
"rules": {
"instant_max_usd": 100,
"notify_max_usd": 500,
"delay_max_usd": 2000,
"delay_seconds": 900,
"daily_limit_usd": 5000
}
}'
Anything above delay_max_usd requires explicit owner approval via WalletConnect or Telegram before it executes — which is exactly the behavior you want for a bot that might encounter unexpected market conditions and try to make an unusually large trade.
Dry-Run Before You Fire
Before your bot executes a real transaction, you can simulate it first. The dry-run API runs the transaction through the full pipeline — including policy checks — but stops before broadcasting. This is useful for testing strategy changes without risking capital:
curl -X POST http://127.0.0.1:3100/v1/transactions/send \
-H "Content-Type: application/json" \
-H "Authorization: Bearer wai_sess_<token>" \
-d '{
"type": "TRANSFER",
"to": "recipient-address",
"amount": "0.1",
"dryRun": true
}'
If your policy would block this transaction, the dry-run tells you exactly why — with a structured error response:
{
"error": {
"code": "POLICY_DENIED",
"message": "Transaction denied by SPENDING_LIMIT policy",
"domain": "POLICY",
"retryable": false
}
}
This is invaluable when you're tuning policy thresholds or testing new strategy logic. Run the simulation, check the policy response, adjust, repeat — without touching mainnet funds.
Batch Transactions for Complex Strategies
Arbitrage and multi-leg strategies often need atomic or near-atomic execution. WAIaaS supports batch transactions, letting you group multiple operations into a single submission. The 7 supported transaction types in the pipeline are: Transfer, TokenTransfer, ContractCall, Approve, Batch, NftTransfer, and ContractDeploy. The Batch type is what you want for multi-step strategies.
Three-Layer Security for Bot Wallets
WAIaaS uses three distinct authentication levels, which maps cleanly to how trading bots should be architected:
- masterAuth (Argon2id) — used by your admin/setup scripts to create wallets and configure policies. Never exposed to the bot process itself.
- sessionAuth (JWT HS256) — what your bot uses at runtime for all trading operations. Scoped to a specific wallet, with per-session TTL, maxRenewals, and absoluteLifetime.
- ownerAuth (SIWS/SIWE) — for human-in-the-loop approval of large transactions via WalletConnect.
This separation means even if your bot process is compromised, an attacker only gets access to a scoped session token — not the master password that controls wallet creation and policy changes. Sessions are time-limited and can be rotated without touching the underlying wallet keys.
Quick Start: Trading Bot Setup
Getting a trading bot wallet running takes about five minutes.
Step 1: Install the CLI and start the daemon
npm install -g @waiaas/cli
waiaas init
waiaas start
Step 2: Create a wallet and session
# Create an EVM or Solana wallet
curl -X POST http://127.0.0.1:3100/v1/wallets \
-H "Content-Type: application/json" \
-H "X-Master-Password: my-secret-password" \
-d '{"name": "trading-wallet", "chain": "solana", "environment": "mainnet"}'
# Create a session token for your bot process
curl -X POST http://127.0.0.1:3100/v1/sessions \
-H "Content-Type: application/json" \
-H "X-Master-Password: my-secret-password" \
-d '{"walletId": "<wallet-uuid>"}'
Step 3: Set risk policies
Apply SPENDING_LIMIT, PERP_MAX_LEVERAGE, CONTRACT_WHITELIST, and ALLOWED_TOKENS before funding the wallet. Default-deny means an unfunded policy config is safe — nothing trades until you explicitly whitelist it.
Step 4: Install the SDK and connect your bot
npm install @waiaas/sdk
Pass the session token as WAIAAS_SESSION_TOKEN in your bot's environment. Use client.getBalance() to verify the connection, then start building strategy logic against the 39 REST API route modules.
Step 5: Deploy with Docker for production
git clone https://github.com/waiaas/WAIaaS.git
cd WAIaaS
docker compose up -d
The Docker deployment runs non-root (UID 1001), includes a healthcheck, supports Docker Secrets for the master password, and works with Watchtower for auto-updates. Production secrets go through the secrets overlay:
mkdir -p secrets
echo "your-secure-password" > secrets/master_password.txt
chmod 600 secrets/master_password.txt
docker compose -f docker-compose.yml -f docker-compose.secrets.yml up -d
What's Next
The OpenAPI 3.0 spec is auto-generated at /doc and there's an interactive Scalar API reference UI at /reference — start there to explore all 39 route modules including the DeFi action endpoints for each of the 15 integrated protocols. The TypeScript SDK ships with 40+ methods and zero external dependencies, so it drops cleanly into any bot architecture.
If you're building on this, star the repo and open an issue with your use case — the project is actively maintained and protocol integrations are expanding.
- GitHub: https://github.com/waiaas/WAIaaS
- Official site: https://waiaas.ai
Top comments (0)