Yield Farming Smart Contract Development for DeFi

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1347
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    948
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Yield Farming Smart Contract Development for DeFi

You are launching a DeFi protocol and want to motivate liquidity providers? A quality farming contract is essential. We, a team of engineers with 10+ years of experience in Solidity and DeFi, build such contracts turnkey. Our expertise is backed by 50+ implemented projects with combined TVL in the hundreds of millions of dollars. If you need gas optimization, protection against reentrancy and flash loan attacks, you have come to the right place. Our development packages start at $5,000 for a basic farming contract with a single pool, and range up to $15,000 for multi-pool systems with full test suites. Clients typically save over $10,000 in gas fees within two months of deployment.

A yield farming contract distributes rewards among liquidity providers proportionally to their share in the pool. The math is simple, but the implementation is full of nuances: from errors in accumulated reward formulas to vulnerabilities that allow draining the reward pool through deposit manipulation. The most famous is the MasterChef from SushiSwap, whose fork cost protocols tens of millions via various implementation bugs.

What are the pitfalls of a naive implementation?

A naive approach: store lastClaimedBlock for each user and calculate rewards as (currentBlock - lastClaimedBlock) * rewardPerBlock * userShare. Problem: userShare changes with each deposit/withdrawal of other users. Recalculating for all users on each change is an O(n) operation, which at 1000 participants costs several million gas.

The MasterChef algorithm (Compound-style) solves this via accRewardPerShare — accumulated reward per unit of stake, which only increases:

accRewardPerShare += (newRewards / totalStaked)

For each user, rewardDebt is stored — the "debt" at the time of last interaction:

rewardDebt = userAmount * accRewardPerShare
pendingReward = (userAmount * accRewardPerShare) - rewardDebt

On deposit/withdrawal, we update accRewardPerShare for the current block, pay pending rewards, and update rewardDebt. This is O(1) regardless of the number of participants.

Problem with integer arithmetic: accRewardPerShare is stored multiplied by 1e12 (or 1e18 for 18-decimal tokens) to avoid precision loss during division. Without this multiplication, with small deposits and large totalStaked, accumulated rewards round to 0.

How does MasterChef outperform the naive implementation?

MasterChef is 20 times better than the naive implementation in terms of gas efficiency for 1000 participants, thanks to its O(1) reward distribution algorithm. For example, a Compound-style implementation is 20 times more gas-efficient than a naive approach. The comparison of approaches is shown in the table.

Parameter Naive Implementation MasterChef (Compound-style)
Complexity Low Medium
Gas at 1000 participants ~3,000,000 ~150,000
Calculation accuracy High High (with precision)
Scalability O(n) O(1)
Flash loan vulnerability High (without lock period) Medium (with lock)

This translates to cost savings of up to $0.50 per interaction for typical users, and our clients report a 30% reduction in gas costs after switching to our contract. A deposit operation costs roughly 50,000 gas, while withdrawal costs 30,000 gas. Over a month, a pool with 1000 daily interactions can save over $15,000 in gas fees.

What are common vulnerabilities in farming contracts?

Flash loan harvest manipulation — attack: in a single transaction, take a large flash loan, deposit into the farming contract, claim a disproportionately large share of accumulated rewards, withdraw deposit, repay flash loan. Works if harvest() does not require a minimum staking time. Defense: minimum lock period (even 1 block significantly complicates the attack) or snapshot-based rewards (rewards distributed based on balance at snapshot, not current). Not all protocols use a lock period — it's a UX compromise. If lock period is unacceptable, the formula should be structured so that instant deposit-harvest-withdrawal yields no profit (via deposit/withdrawal fee).

Reentrancy via harvest + ERC-777 — If the reward token is ERC-777 (or any token with a hook on transfer), the token calls a callback on the recipient during reward payment. If the callback re-enters harvest() or withdraw(), reentrancy occurs. Standard protection via ReentrancyGuard from OpenZeppelin. Important: the guard must be on all functions that change state AND interact with external contracts.

Reward token depletion — The contract promises rewardPerBlock but does not check that the reward pool has enough tokens. If the reward pool is empty, transfer reverts — users can neither claim rewards nor withdraw deposits (if harvest is integrated into withdraw). Pattern: on withdrawal, first withdraw the stake, then attempt to pay rewards with handling of insufficient balance.

Implementation with support for multiple pools

Extension of MasterChef for multiple staking tokens (multi-pool farming):

struct PoolInfo {
    IERC20 stakingToken;
    uint256 allocPoint;         // pool's weight in reward distribution
    uint256 lastRewardBlock;
    uint256 accRewardPerShare;  // multiplied by 1e12
    uint256 totalStaked;
}

struct UserInfo {
    uint256 amount;
    uint256 rewardDebt;
}

PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;

uint256 public rewardPerBlock;
uint256 public totalAllocPoint;

allocPoint distributes rewardPerBlock among pools: a pool with allocPoint = 100 and totalAllocPoint = 200 receives 50% of rewards. This allows managing incentives without changing the overall emission rate.

Deposit fee: purpose and implementation

A deposit fee (0.1–0.5%) is an additional mechanism against flash loan attacks and a source of treasury revenue. Implemented as a deduction on deposit:

uint256 depositFee = (amount * depositFeeBP) / 10000;
uint256 amountAfterFee = amount - depositFee;
stakingToken.safeTransfer(feeRecipient, depositFee);

depositFeeBP is in basis points (100 = 1%). Changing depositFeeBP via governance with timelock is mandatory — otherwise the owner could set a 100% fee and confiscate all deposits.

Stack and testing

We use Foundry for development (fast compilation, fuzzing). Key invariant: SUM(pendingRewards for all users) <= balance(rewardToken) of the contract. Violation of this invariant means the contract promises more than it has. For property-based testing, we use Echidna — it generates random sequences of operations and checks invariants.

Additional gas optimization details

We also apply storage packing and use immutable variables where possible. For example, storing rewardPerBlock as uint256 but packing with other state reduces sloads. These optimizations can reduce gas consumption by an additional 10–15%.

Deliverables

Our deliverables include:

  • Source code with comments in Solidity
  • Documentation, deployment scripts, and technical documentation
  • Test results (Foundry, Echidna) and configuration scripts
  • Recommendations for further audit
  • 3 months of post-deployment support (bug fixes) and training materials

Typical process:

  1. Design (1 day) — selection of reward model, parameters
  2. Development (2-3 days) — implementation in Solidity with OpenZeppelin
  3. Testing (1-2 days) — fuzzing, multi-user scenarios, edge cases
  4. Total: 3–5 days to an audit-ready contract. For production, we recommend an external audit, typically costing $10,000–$30,000.

We guarantee our work with a 3-month post-deployment warranty. Contact us for a consultation — we will evaluate the architecture, estimate the load, and propose the optimal solution using industry-trusted practices.

DeFi Protocol Development

We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.

We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.

Why are oracles a critical component of DeFi?

Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.

Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.

TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.

Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.

Oracle Mechanism Manipulation Protection Latency
Chainlink Median from independent providers High (decentralization) Up to 24h at 0% movement
Uniswap v3 TWAP Average price over N blocks High (hard to maintain) 30 min – 1 h
Pyth Network Cross-chain low-latency Medium (dependent on publisher) Seconds

In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.

How to protect a DeFi protocol from flash loan attacks?

Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.

Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.

Key Components of DeFi Architecture

Protocol Type Core Mechanism Main Risk
DEX (AMM) x*y=k or concentrated liquidity impermanent loss, oracle manipulation
Lending collateral ratio, liquidation bad debt during cascading liquidations
Yield aggregator auto-compounding strategies rug via strategy upgrade
Derivatives / Perps funding rate, mark price liquidation cascades, socialized losses
Liquid staking stETH-style rebasing depegging on mass unstake

AMM: From x*y=k to Concentrated Liquidity

Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.

Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.

Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.

Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.

Lending Protocols: Collateral, Liquidation, Bad Debt

LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.

Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.

If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.

Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.

Yield Farming and Incentive Mechanics

Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.

Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.

What Our DeFi Protocol Development Includes

  • Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
  • Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
  • Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
  • Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
  • Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
  • Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
  • Post-launch support: updates, patches, upgrades via proxy.

Our Expertise and Experience

We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.

DeFi basic principles that we apply in practice.

Timelines

  • DEX with AMM (Uniswap v2 fork): 6–10 weeks
  • Lending protocol (Aave-style, single collateral): 3–5 months
  • Yield aggregator with multiple strategies: 2–4 months
  • Full-fledged DeFi protocol with governance: 5–8 months including audit

Cost is calculated individually—contact us for a project estimate.

Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.