Skip to content

DeFi Bridge

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.

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.

TierLevelAllowed ActionsPosition LimitDaily Volume Limit
NONE0Nothing
CONSERVATIVE1Quotes only (no execution)
BALANCED2Swaps10 ETH50 ETH
AGGRESSIVE3Swaps, supply, borrow, repay, withdraw100 ETH500 ETH
FULL4All actionsUnlimitedUnlimited

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:

  1. Policy lookup — find the agent’s stored policy
  2. Temporal check — is the policy currently valid?
  3. Protocol check — is the target protocol in the allowlist?
  4. Tier check — does the tier permit this action type?
  5. Size check — does the position size exceed tier limits?
  6. Volume check — would this trade exceed the daily volume cap?

Policies can be revoked at any time by the owner.

All protocol integrations implement the DeFiAdapter interface:

MethodReturnsDescription
quote(action)QuoteResultPrice quote without execution
encode(action)EncodedTransactionEncode the action as calldata
simulate(action)SimulationResultDry-run the transaction
validate(action)ValidationResultCheck action parameters
getRates?(token)RateResultLending/borrowing rates (lending adapters only)
ProtocolAdapterActions
Uniswap V4UniswapV4Adapterswap
Aave V3AaveV3Adaptersupply, borrow, repay, withdraw

The AdapterRegistry manages adapter registration and lookup. New protocols are added by implementing DeFiAdapter and registering with the registry.

ActionDescriptionKey Parameters
swapToken exchangetokenIn, tokenOut, amountIn, slippageBps, feeTier
supplyDeposit collateraltoken, amount, onBehalfOf
borrowTake a loantoken, amount, rateMode (stable/variable)
repayRepay a loantoken, amount, rateMode
withdrawWithdraw collateraltoken, amount

Every DeFi action flows through the TransactionPipeline — a staged execution engine:

Action → [Permission Stage] → [Validation] → [Simulation] → [Gas Estimation] → [Encoding] → [Signing] → [Broadcast] → Result

Each stage implements the PipelineStage interface and can halt execution if checks fail. The PermissionStage integrates the PermissionEngine as the first stage.

The GasEstimator provides accurate gas estimates with configurable buffer strategies:

StrategyDescription
FixedAdd a fixed gas amount
PercentageAdd a percentage buffer
AdaptiveAdjust based on recent gas usage

Five circuit breakers protect agents from catastrophic loss. Each breaker monitors a specific risk dimension and trips to OPEN state when thresholds are exceeded.

BreakerMonitorsTrips When
DailyLossBreakerDaily P&LLosses exceed configured threshold
ProtocolAnomalyBreakerProtocol healthTVL drops, token depegs, unusual activity
GasSpikeBreakerGas pricesGas exceeds N times the baseline
PositionSizeBreakerIndividual positionsSingle position too large relative to portfolio
CorrelationBreakerCross-position correlationToo 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.

The QuoteAggregator collects quotes from all registered adapters that support swap for a given token pair:

  1. Query all adapters in parallel
  2. Filter out failures
  3. Rank by output amount (descending)
  4. Return ordered list of AggregatedQuote objects

The RouteScorer evaluates routes on multiple dimensions:

FactorWeightDescription
Output amountHighMore output is better
Gas costMediumCheaper gas is better
Price impactMediumLower impact is better
Protocol reliabilityLowHistorical success rate

For large trades, the SplitRouter splits volume across multiple protocols to minimize price impact:

  1. Get quotes from all protocols
  2. Score routes
  3. Determine optimal allocation (e.g., 60% Uniswap, 40% SushiSwap)
  4. Return SplitRoute with allocations and expected aggregate output

The PositionTracker maintains a real-time view of all open DeFi positions:

DataDescription
Position statusopen, closed, liquidated
Entry/exit pricesCost basis and close price
P&LRealized and unrealized
Exposure breakdownBy token, protocol, and action type
Portfolio snapshotAggregate view across all positions

The FeeCalculator applies Ludus protocol fees to each trade:

ComponentDescription
Base feePercentage of trade volume
Volume discountReduced fees for high-volume agents
Minimum feeFloor fee per transaction

The FeeCollector accumulates pending fees and handles periodic settlement to the protocol treasury.

The DeFiBridge class provides the high-level API that most consumers should use:

MethodDescription
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.