Defi Yield Strategies

Production-grade guide to defi yield strategies covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

DeFi yield strategies are automated on‑chain workflows that move capital between protocols to generate risk‑adjusted returns. From an engineering perspective they matter when you are building, auditing, or operating strategy contracts, vault aggregators, or bridge‑integrated reward loops. This page covers the concrete steps of writing, deploying, and troubleshooting those workflows, using only shipping tooling and generic interface patterns that apply across any EVM‑compatible chain.

Optimizing Gas Across Multi‑Step Yield Executions

Yield strategies typically compose several internal calls—a deposit into a lending market, a liquidity addition to an AMM, a reward claim, and a final withdrawal—all within a single transaction to avoid multiple round‑trips and reduce gas per token moved. The pattern is always the same: an external‑owned account or a keeper contract sends a transaction to a strategy contract, which internally uses call/delegatecall to invoke target interfaces.

Calling a strategy from an EOA with cast


cast send 0xStrategyAddress \
  --exec "execute(uint256,address)" 1000 0xTokenAddress \
  --value 0 \
  --gas-limit 300000 \
  --rpc-url https://mainnet.infura.io/v3/<your‑project-id> \
  --private-key 0x<your‑eoa‑private-key>

Flags decoded

FlagMeaning
--execSolidity function signature and ABI‑encoded arguments. The function must be external and typically returns bool.
--gas-limitHard upper bound for the EVM execution. Strategies that batch multiple calls often need 250 k–400 k gas depending on the number of target contracts touched.
--rpc-urlJSON‑RPC endpoint; any public or self‑hosted provider (Infura, Alchemy, QuickNode, or a local geth/erigon instance) works.
--private-keySigner for the transaction. Never embed this in CI pipelines; use environment‑injected keys or signer middleware.

If the strategy uses delegatecall to delegate into a library or a proxy target, the gas limit must also cover the target contract’s execution path. A common misstep is setting a static limit that works for a minimal test case but reverts under full load because an Aave deposit or Uniswap V3 Mint` call adds calldata and state‑access gas.

Estimating gas before sending

cast estimate 0xStrategyAddress "execute(uint256,address)" 1000 0xTokenAddress \
  --rpc-url https://mainnet.infura.io/v3/<your‑project-id>

The returned number is a baseline; always add a 20 % buffer for path‑dependent gas (e.g., varying token balances, congested block numbers). Never rely on eth_estimateGas from an explorer UI for automated scripts—they omit access lists and 1559 fee dynamics.

Routing Capital Through Lending or Liquidity Modules

A strategy contract’s core logic rarely implements the actual deposit or swap. Instead it conforms to a small, well‑defined interface that the target protocol exposes. The strategy builds calldata, sends it via call, and inspects the return value or emitted events to decide whether the step succeeded.

Generic ethers.js pattern for a single hop

const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider("https://mainnet.infura.io/v3/<project-id>");
const wallet = new ethers.Wallet("<keeper‑private-key>", provider);

const strategyAbi = [
  "function execute(uint256 amount, address token) external returns (bool)"
];
const strategy = new ethers.Contract("0xStrategyAddress", strategyAbi, wallet);

async function runHop() {
  const tx = await strategy.execute(ethers.parseUnits("1000", 18), "0xTokenAddress");
  console.log("tx hash:", tx.hash);
  const receipt = await tx.wait();
  console.log("status:", receipt.status === 1 ? "success" : "reverted");
}
runHop();

What the code does

  1. Loads a provider and wallet—no custom SDK, just the standard ethers transport.
  2. Defines only the ABI fragment the strategy needs; this keeps the compiled contract size minimal and makes introspection predictable.
  3. Calls execute with two uint256‑encoded arguments: the amount and the target token address.
  4. Waits for the receipt and checks the status field. A value of 0 means the EVM reverted; the transaction is still on‑chain but marked failed.

If the target is a lending market, the calldata typically follows the ERC‑300 deposit signature (uint256 amount, address onBehalfOf, address receiver, uint16 referral). If it’s an AMM, the pattern switches to mint(uint256 amountA, uint256 amountB, address to, uint16 referral). The strategy never hard‑codes these signatures; they are loaded from a JSON file or generated from the protocol’s interface at build time.

Supplying Oracle‑Derived Parameters

Yield strategies frequently need a price feed to compute ratios, calculate APY, or determine whether a rebalance threshold has been crossed. Most production strategies pull price data from a trusted oracle contract (Chainlink, Band, Pyth) via eth_call before executing the capital‑movement steps.

Fetching a Chainlink aggregate price with curl

curl -s https://mainnet.infura.io/v3/<project-id> \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0x875F974D7FbCF8A7A8cF3241f5b2921E24A08d32","data":"0x00c5d1b6"},"latest"],"id":1}' | jq '.result'

The data field 0x00c5d1b6 is the latestRoundData() selector for the Chainlink AggregatorV2 interface. The response returns a hex string that, when decoded, yields roundId, answer, startedAt, updatedAt, and answeredInRound. The answer field is the price in eight decimal places (for USD/ETH) or 18 decimals (for native ETH).

Common pitfall: Strategies that cache the price at construction time and never re‑query it will silently compound on stale data. The sharp edge is a price that moves >5 % between the oracle query and the actual execute call, causing the strategy to either under‑collateralize or attempt a swap at a price that no longer exists on‑chain, resulting in a transaction revert with revert: Price outside expected range.

Rebalancing and Compounding Without External Dependencies

Many strategies auto‑compound rewards by claiming native token (e.g., BOB, SOL‑derived rewards) and restaking them into the same position. The engineering pattern is:

  1. Claim the reward token to a controlled address.
  2. Approve the strategy contract to spend the reward.
  3. Swap the reward for the base asset (if the reward is not the base).
  4. Deposit the swapped base asset back into the original strategy.

All four steps can be bundled into a single execute call if the strategy contract implements an internal transferFrom → swap → deposit sequence using call to the relevant routers (1inch, Paraswap, or direct AMM paths).

Example: Claim + restake in a single transaction (pseudo‑code, tool‑agnostic)

function execute(uint256 amount,) external {
    // 1. Claim reward from the vault
    (bool ok, ) = rewardVault.call(abi.encodeWithSelector(0x...));
    require(ok, "claim failed");

    // 2. Swap reward → base using a router
    ISwapRouter router = ISwapRouter(0x1111...);
    router.swapExactETHForTokens{value: amount}(0, baseToken, address(this), block.timestamp);

    // 3. Deposit base into the yield source
    IYieldSource(source).deposit(amount);
}

Sharp edge: If the router’s swap path relies on a pair that has been temporarily paused (e.g., due to a bug‑induced emergency shutdown), step 2 reverts, but step 3 may have already been partially executed if the strategy uses transfer before call returns. This partial‑state condition is hard to detect without replay‑proof logging. Production‑grade strategies emit Claimed, Swapped, and Deposited events at each sub‑step and require a keeper to verify the full chain before marking the round successful.

Sharp Edges: What Silently Fails, Confused Options, Lessons From Production

Gas Estimation Mismatches

eth_estimateGas historically returned a “base” gas limit that omitted access‑list and 1559‑style priority fee calculations. Strategies that batch four or five calls often see the estimate 15–30 % lower than the actual consumed gas when the block includes an elevated baseFeePerGas. The result is a transaction that passes the pre‑flight check but reverts in‑execution with out of gas. Always run a dry‑run with --gas-limit set 20 % above the estimate, or use cast send --gas-limit <estimated+buffer>.

Oracle Delay and Price Staleness

Chainlink round data is updated per‑aggregate‑period (typically every hour on major pairs). If a strategy queries latestRoundData() and then immediately routes capital, the price may already be 2–3 rounds old. On volatile assets (e.g., ETH/USD during market opens), this staleness can cause the strategy to compute a misleading APY or trigger a rebalance at the wrong price point. The mechanism to mitigate this is to read updatedAt and compare it against block.timestamp; if the delta exceeds a configured threshold (e.g., 30 minutes), the strategy should abort or fall back to the previous valid price.

Approval and Whitelist Race Conditions

Many yield contracts require an ERC‑20 approve(spender, amount) call before they can transferFrom the user’s balance. A common race occurs when two keepers attempt to approve the same token simultaneously: the second transaction’s approve overwrites the first, but the first’s internal transferFrom still succeeds because the allowance was set at a higher point in the same block. The net effect is an unexpected token transfer that the user did not authorize. Production systems mitigate this by using increaseAllowance with a delta, or by checking the current allowance via allowance(owner, spender) before each submit.

Mis‑aligned Reward Tokens

Strategies that auto‑compound often assume the reward token is ERC‑20 compatible with 18 decimals. Some protocols emit rewards in native units (e.g., 0.001 ETH per epoch) or use non‑standard decimals (6 for USDC, 9 for USDT). If the strategy hard‑codes uint256(10**18) as the unit, the transfer or approve call will either move an astronomically large amount (causing an out‑of‑gas revert) or move zero due to truncation. Always read the reward token’s decimals() at initialization and normalize all internal calculations accordingly.

Debugging Workflow with Standard Tooling

Using cast for Replay and Inspection

# Replay a transaction that already mined, printing calldata and return data
cast receipt 0x<tx-hash> --rpc-url https://mainnet.infura.io/v3/<project-id>

The output includes gasUsed, status, and returnData. If the strategy reverted, returnData will contain the revert reason (e.g., revert: ERC20 transfer amount exceeds balance). This is often the fastest way to confirm whether the failure originated in the strategy’s logic or in a called target contract.

Tracing Transactions with ethers Event Logs

const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider("https://mainnet.infura.io/v3/<project-id>");

provider.getTransaction("0x<tx-hash>").then(tx => {
  return provider.getTransactionReceipt(tx.hash);
}).then(receipt => {
  receipt.logs.forEach(log => {
    console.log("address:", log.address);
    console.log("topics:", log.topics);
    console.log("data:", log.data);
  });
});

Each log entry corresponds to an emit inside the strategy or any target contract. By filtering on address (the strategy contract) and inspecting topics, you can confirm whether a Deposit, Withdraw, or RewardClaimed event fired as expected. If a log is missing, the corresponding call either reverted or the event was emitted to a different address (e.g., a proxy).

Offline Simulation with anvil (Foundry’s local fork)

anvil -f <fork‑url> --block-number 19000000

Starting a local fork lets you mine blocks, increase time, and send transactions without paying real gas. You can then cast send to the strategy with --gas-limit 999999 and observe state changes in real time. This is invaluable for reproducing race conditions or oracle‑delay scenarios that are hard to trigger on mainnet.

Bottom line: DeFi yield strategies are a composition pattern—strategy contracts emit a sequence of calls to lending, AMM, and oracle interfaces, all orchestrated within a single transaction to minimize round‑trips and gas. The engineering work lies in correct ABI selection, gas budgeting with buffers, oracle freshness checks, and defensive handling of approval races and partial‑state reverts. All of the above can be inspected, simulated, and debugged using only cast, ethers.js, curl against JSON‑RPC, and local forks—no vendor‑specific SDK or closed‑source config is required.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.