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:
- Design (1 day) — selection of reward model, parameters
- Development (2-3 days) — implementation in Solidity with OpenZeppelin
- Testing (1-2 days) — fuzzing, multi-user scenarios, edge cases
- 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.







