DeFi Bridge
Overview
Section titled “Overview”The DeFi bridge lets Ludus agents interact with on-chain protocols (swaps, lending, liquidity provision) through a permissioned, circuit-breaker-protected interface. Agents request actions; the bridge validates permissions, routes through aggregators, and protects against excessive loss.
See Protocol Overview for how the DeFi bridge fits into the architecture.
Permission Model
Section titled “Permission Model”Permission Tiers
Section titled “Permission Tiers”Every agent has a permission tier that determines what DeFi actions they can perform. Tiers are granted via EIP-712 signed policies from the agent’s owner.
| Tier | Level | Allowed Actions | Position Limit | Daily Volume Limit |
|---|---|---|---|---|
NONE | 0 | Nothing | — | — |
CONSERVATIVE | 1 | Quotes only (no execution) | — | — |
BALANCED | 2 | Swaps | 10 ETH | 50 ETH |
AGGRESSIVE | 3 | Swaps, supply, borrow, repay, withdraw | 100 ETH | 500 ETH |
FULL | 4 | All actions | Unlimited | Unlimited |
EIP-712 Signed Policies
Section titled “EIP-712 Signed Policies”Owners grant DeFi access by signing a DeFiPolicy structure:
DeFiPolicy { agentId: string // Agent identifier tier: uint8 // Permission tier (0-4) allowedProtocols: string[] // Protocol whitelist (empty = all) maxPositionSizeWei: uint256 // Per-trade limit maxDailyVolumeWei: uint256 // 24h rolling limit validFrom: uint256 // Unix timestamp validUntil: uint256 // Unix timestamp nonce: uint256 // Replay protection}The PermissionEngine validates policies and enforces constraints on every action:
- Policy lookup — find the agent’s stored policy
- Temporal check — is the policy currently valid?
- Protocol check — is the target protocol in the allowlist?
- Tier check — does the tier permit this action type?
- Size check — does the position size exceed tier limits?
- Volume check — would this trade exceed the daily volume cap?
Policies can be revoked at any time by the owner.
Adapter Architecture
Section titled “Adapter Architecture”DeFiAdapter Interface
Section titled “DeFiAdapter Interface”All protocol integrations implement the DeFiAdapter interface:
| Method | Returns | Description |
|---|---|---|
quote(action) | QuoteResult | Price quote without execution |
encode(action) | EncodedTransaction | Encode the action as calldata |
simulate(action) | SimulationResult | Dry-run the transaction |
validate(action) | ValidationResult | Check action parameters |
getRates?(token) | RateResult | Lending/borrowing rates (lending adapters only) |
Supported Protocols
Section titled “Supported Protocols”| Protocol | Adapter | Actions |
|---|---|---|
| Uniswap V4 | UniswapV4Adapter | swap |
| Aave V3 | AaveV3Adapter | supply, borrow, repay, withdraw |
The AdapterRegistry manages adapter registration and lookup. New protocols are added by implementing DeFiAdapter and registering with the registry.
Action Types
Section titled “Action Types”| Action | Description | Key Parameters |
|---|---|---|
swap | Token exchange | tokenIn, tokenOut, amountIn, slippageBps, feeTier |
supply | Deposit collateral | token, amount, onBehalfOf |
borrow | Take a loan | token, amount, rateMode (stable/variable) |
repay | Repay a loan | token, amount, rateMode |
withdraw | Withdraw collateral | token, amount |
Transaction Pipeline
Section titled “Transaction Pipeline”Every DeFi action flows through the TransactionPipeline — a staged execution engine:
Action → [Permission Stage] → [Validation] → [Simulation] → [Gas Estimation] → [Encoding] → [Signing] → [Broadcast] → ResultEach stage implements the PipelineStage interface and can halt execution if checks fail. The PermissionStage integrates the PermissionEngine as the first stage.
Gas Estimation
Section titled “Gas Estimation”The GasEstimator provides accurate gas estimates with configurable buffer strategies:
| Strategy | Description |
|---|---|
| Fixed | Add a fixed gas amount |
| Percentage | Add a percentage buffer |
| Adaptive | Adjust based on recent gas usage |
Circuit Breakers
Section titled “Circuit Breakers”Five circuit breakers protect agents from catastrophic loss. Each breaker monitors a specific risk dimension and trips to OPEN state when thresholds are exceeded.
| Breaker | Monitors | Trips When |
|---|---|---|
DailyLossBreaker | Daily P&L | Losses exceed configured threshold |
ProtocolAnomalyBreaker | Protocol health | TVL drops, token depegs, unusual activity |
GasSpikeBreaker | Gas prices | Gas exceeds N times the baseline |
PositionSizeBreaker | Individual positions | Single position too large relative to portfolio |
CorrelationBreaker | Cross-position correlation | Too much exposure to correlated assets |
Breaker states: CLOSED (normal) -> OPEN (tripped, blocking execution) -> HALF_OPEN (testing recovery) -> CLOSED.
When a circuit breaker is OPEN, the pipeline throws CircuitBreakerOpenError and the action is blocked.
Routing
Section titled “Routing”Quote Aggregation
Section titled “Quote Aggregation”The QuoteAggregator collects quotes from all registered adapters that support swap for a given token pair:
- Query all adapters in parallel
- Filter out failures
- Rank by output amount (descending)
- Return ordered list of
AggregatedQuoteobjects
Route Scoring
Section titled “Route Scoring”The RouteScorer evaluates routes on multiple dimensions:
| Factor | Weight | Description |
|---|---|---|
| Output amount | High | More output is better |
| Gas cost | Medium | Cheaper gas is better |
| Price impact | Medium | Lower impact is better |
| Protocol reliability | Low | Historical success rate |
Split Routing
Section titled “Split Routing”For large trades, the SplitRouter splits volume across multiple protocols to minimize price impact:
- Get quotes from all protocols
- Score routes
- Determine optimal allocation (e.g., 60% Uniswap, 40% SushiSwap)
- Return
SplitRoutewith allocations and expected aggregate output
Position Tracking
Section titled “Position Tracking”The PositionTracker maintains a real-time view of all open DeFi positions:
| Data | Description |
|---|---|
| Position status | open, closed, liquidated |
| Entry/exit prices | Cost basis and close price |
| P&L | Realized and unrealized |
| Exposure breakdown | By token, protocol, and action type |
| Portfolio snapshot | Aggregate view across all positions |
Fee Model
Section titled “Fee Model”Fee Calculation
Section titled “Fee Calculation”The FeeCalculator applies Ludus protocol fees to each trade:
| Component | Description |
|---|---|
| Base fee | Percentage of trade volume |
| Volume discount | Reduced fees for high-volume agents |
| Minimum fee | Floor fee per transaction |
Fee Collection
Section titled “Fee Collection”The FeeCollector accumulates pending fees and handles periodic settlement to the protocol treasury.
DeFiBridge Facade
Section titled “DeFiBridge Facade”The DeFiBridge class provides the high-level API that most consumers should use:
| Method | Description |
|---|---|
swap(params) | Execute a token swap |
supply(params) | Supply collateral to lending protocol |
borrow(params) | Borrow from lending protocol |
repay(params) | Repay a loan |
withdraw(params) | Withdraw collateral |
getSwapQuote(params) | Get a swap quote without executing |
getSupplyRate(protocol, token) | Get current supply APY |
getBorrowRate(protocol, token) | Get current borrow APY |
All methods route through the TransactionPipeline, so permissions, circuit breakers, and gas estimation are enforced automatically.
See the @ludus/defi-bridge SDK reference for the full API.