e, NetworkIdentifier } from '@waiaas/sdk';
interface AgentSecurityConfig {
walletId: string;
masterKey: string;
permittedNetworks: NetworkIdentifier[];
}
export class AgentSecurityManager {
private client: WaiaasClient;
constructor(config: AgentSecurityConfig) {
this.client = new WaiaasClient({ masterKey: config.masterKey });
}
/**
- Applies network isolation to a specific wallet.
- This operation is idempotent; re-applying updates the whitelist.
*/
async enforceNetworkBoundary(walletId: string, networks: NetworkIdentifier[]): Promise<void> {
const policyPayload = {
walletId,
type: PolicyType.ALLOWED_NETWORKS,
rules: {
networks: networks.map(net => ({ network: net }))
}
};
try {
const result = await this.client.policies.create(policyPayload);
console.log(`[SECURITY] Network policy applied to ${walletId}. Allowed: ${networks.join(', ')}`);
} catch (error) {
// Policy creation failures should halt deployment
throw new Error(`Failed to apply network policy: ${error.message}`);
}
}
/**
- Validates that a transaction request complies with network policies
- without executing on-chain.
*/
async validateTransactionDryRun(sessionToken: string, txPayload: any): Promise<boolean> {
const dryRunPayload = {
...txPayload,
dryRun: true
};
try {
await this.client.transactions.send(sessionToken, dryRunPayload);
return true;
} catch (error) {
if (error.code === 'POLICY_DENIED') {
console.warn(`[SECURITY] Transaction blocked: ${error.message}`);
return false;
}
throw error;
}
}
}
**Usage Example:**
```typescript
const securityManager = new AgentSecurityManager({
walletId: 'wallet_uuid_prod_trading_01',
masterKey: process.env.WAIaaS_MASTER_KEY,
permittedNetworks: ['ethereum-mainnet', 'polygon-mainnet']
});
// Lock the agent to Ethereum and Polygon only
await securityManager.enforceNetworkBoundary(
'wallet_uuid_prod_trading_01',
['ethereum-mainnet', 'polygon-mainnet']
);
Architecture Decisions
- Policy Layer Enforcement: The policy is evaluated at Stage 3 of the transaction pipeline. This ensures that network validation occurs after session authentication but before any gas estimation or blockchain interaction. This positioning minimizes resource waste and prevents agents from incurring costs on blocked transactions.
- Explicit Whitelisting: The policy uses a default-deny model. Only networks explicitly listed in the
rules.networks array are accessible. This aligns with the principle of least privilege.
- Network Identifiers: WAIaaS uses standardized string identifiers (e.g.,
ethereum-mainnet, solana-devnet) rather than numeric chain IDs. This reduces the risk of chain ID collisions and improves readability in policy definitions.
- Idempotent Updates: Policies can be updated by re-submitting the configuration. This allows for dynamic adjustments, such as adding a new L2 to a whitelist during a deployment window, without requiring wallet recreation.
Pitfall Guide
Production experience reveals recurring patterns of misconfiguration that undermine network isolation. Avoid these common mistakes to maintain a secure agent environment.
-
The Testnet Leakage Trap
- Explanation: Development agents are configured with broad access for convenience and accidentally deployed to production environments. This allows testnet agents to interact with mainnet contracts if the agent logic generates a mainnet address.
- Fix: Enforce strict environment separation. Development wallets must only whitelist testnets (e.g.,
ethereum-sepolia, solana-devnet). Use distinct master keys and wallet namespaces for dev vs. prod.
-
Implicit Allow-All Assumption
- Explanation: Teams assume that creating a wallet for a specific chain implicitly restricts the agent to that chain. In WAIaaS, wallets are chain-agnostic by default; network access is controlled solely by policies.
- Fix: Always apply an
ALLOWED_NETWORKS policy immediately after wallet creation. Treat policy application as a mandatory step in the provisioning script.
-
Policy Drift in CI/CD
- Explanation: Policies are applied manually via CLI and not tracked in version control. Over time, the live configuration diverges from the intended state, leading to unauthorized network access.
- Fix: Manage policies as code. Store policy definitions in your repository and apply them via automated pipelines. Use the
validateTransactionDryRun method in pre-deployment checks to verify policy enforcement.
-
Ignoring Layered Defense
- Explanation: Relying solely on network whitelisting leaves agents vulnerable to malicious contracts or excessive spending on allowed chains.
- Fix: Combine
ALLOWED_NETWORKS with ALLOWED_TOKENS and SPENDING_LIMIT policies. Network isolation is the first layer; token whitelisting and spending caps provide additional containment.
-
Silent Failures in Agent Logic
- Explanation: Agents do not handle
POLICY_DENIED errors gracefully, leading to retry loops or state corruption when a transaction is blocked.
- Fix: Implement robust error handling in the agent's execution loop. Detect
POLICY_DENIED codes and trigger alerting or fallback mechanisms rather than retrying the same blocked transaction.
-
Emergency Access Neglect
- Explanation: Policies are so restrictive that legitimate operations are blocked during emergencies, and no override mechanism is configured.
- Fix: Configure emergency overrides using WalletConnect signatures for fund owners and
masterAuth for system administrators. Ensure session management includes a kill switch to instantly revoke agent access.
-
Cross-Chain Bridge Exploits
- Explanation: Agents are allowed to interact with bridge contracts on whitelisted networks, but the bridge destination is not controlled. An attacker could manipulate the agent to bridge funds to an unwhitelisted chain.
- Fix: Restrict bridge interactions using
ALLOWED_TOKENS and contract-level policies. Monitor bridge transactions closely and consider disabling bridge functionality for high-risk agents.
Production Bundle
Action Checklist
Decision Matrix
| Scenario | Recommended Approach | Why | Cost Impact |
|---|
| High-frequency trading bot | Single-chain whitelist | Reduces latency by eliminating cross-chain checks; contains risk to one ecosystem | Low |
| Cross-chain arbitrage agent | Multi-chain whitelist | Requires access to liquidity pools across multiple chains; policy must reflect operational needs | Medium |
| Development sandbox | Testnet-only whitelist | Prevents accidental interaction with mainnet funds; allows safe experimentation | None |
| Institutional custody agent | Single-chain + Token whitelist | Maximizes security for high-value assets; restricts both network and asset exposure | Low |
| AI research prototype | Open access (temporary) | Facilitates rapid iteration during early development; must be locked before production | N/A |
Configuration Template
Use this JSON template as a baseline for your ALLOWED_NETWORKS policy. Customize the networks array to match your agent's requirements.
{
"walletId": "<your-wallet-uuid>",
"type": "ALLOWED_NETWORKS",
"rules": {
"networks": [
{ "network": "ethereum-mainnet" },
{ "network": "polygon-mainnet" },
{ "network": "solana-mainnet" }
]
},
"metadata": {
"version": "1.0.0",
"appliedBy": "ci-pipeline",
"timestamp": "2024-05-20T10:00:00Z"
}
}
Notes:
- Replace
<your-wallet-uuid> with the actual wallet identifier.
- The
metadata field is optional but recommended for audit trails.
- Ensure network identifiers match WAIaaS standards exactly.
Quick Start Guide
Follow these steps to deploy a network-isolated agent in under five minutes.
-
Initialize WAIaaS Environment
Install the CLI and initialize the daemon. This sets up the local policy engine.
npm install -g @waiaas/cli
waiaas init --environment production
waiaas start
-
Create a Restricted Wallet
Generate a new wallet for your agent. The wallet is created with default open access; we will restrict it in the next step.
curl -X POST http://127.0.0.1:3100/v1/wallets \
-H "Content-Type: application/json" \
-H "X-Master-Password: ${WAIaaS_MASTER_KEY}" \
-d '{
"name": "prod-trading-bot",
"chain": "ethereum",
"environment": "mainnet"
}'
Save the returned walletId.
-
Apply Network Policy
Lock the wallet to specific networks. This policy takes effect immediately.
curl -X POST http://127.0.0.1:3100/v1/policies \
-H "Content-Type: application/json" \
-H "X-Master-Password: ${WAIaaS_MASTER_KEY}" \
-d '{
"walletId": "<wallet-id-from-step-2>",
"type": "ALLOWED_NETWORKS",
"rules": {
"networks": [
{"network": "ethereum-mainnet"}
]
}
}'
-
Create Agent Session
Generate a session token for the agent. This token inherits the network restrictions.
curl -X POST http://127.0.0.1:3100/v1/sessions \
-H "Content-Type: application/json" \
-H "X-Master-Password: ${WAIaaS_MASTER_KEY}" \
-d '{
"walletId": "<wallet-id-from-step-2>"
}'
Save the sessionToken.
-
Verify Enforcement
Attempt a transaction on a blocked network to confirm the policy is active.
curl -X POST http://127.0.0.1:3100/v1/transactions/send \
-H "Authorization: Bearer <session-token>" \
-H "Content-Type: application/json" \
-d '{
"type": "TRANSFER",
"to": "0xRecipientAddress",
"amount": "0.01",
"network": "ethereum-sepolia",
"dryRun": true
}'
Expected Result: The response should contain {"error": {"code": "POLICY_DENIED", ...}}, confirming that the agent cannot access testnets.
Extended Insights
Chain ID Collision Risks:
When managing agents across multiple EVM chains, be aware of chain ID collisions. Some testnets and mainnets share identical numeric chain IDs. WAIaaS mitigates this by using string-based network identifiers, but your agent logic must also avoid relying solely on numeric chain IDs for routing. Always validate network names against the WAIaaS policy whitelist.
Policy Evaluation Latency:
The ALLOWED_NETWORKS policy is evaluated in-memory at Stage 3 of the pipeline. This adds negligible latency (<1ms) to transaction processing. However, if you apply multiple policies, the cumulative evaluation time may increase. Monitor pipeline metrics to ensure policy checks do not impact high-frequency trading operations.
Dynamic Policy Updates:
WAIaaS supports hot-reloading of policies. You can update the ALLOWED_NETWORKS policy without restarting the daemon or recreating sessions. This is useful for adding new chains during deployment windows or revoking access during security incidents. Ensure that policy updates are atomic to prevent race conditions.
Integration with Monitoring:
Integrate POLICY_DENIED events with your observability stack. A spike in denied transactions may indicate a compromised agent or a misconfigured prompt. Set up alerts for policy violations to enable rapid incident response.
By implementing strict network whitelisting, you transform your AI agent from a potentially dangerous autonomous entity into a controlled, predictable system. The ALLOWED_NETWORKS policy is the first line of defense, but its true power is realized when combined with layered security measures, robust error handling, and continuous monitoring.