Yield Farming Protocol Security Best Practices | PandaSecurity
Web3 Security

Yield Farming Protocol Security Best Practices

PandaSecurity Team •
#Yield Farming Security#DeFi Security#Smart Contract Audit
Yield farming protocol security and DeFi smart contract protection

Yield Farming Protocol Security Best Practices

Yield farming looks simple from the user’s perspective. Deposit assets, provide liquidity, earn rewards, and withdraw later. Behind that simple interface, however, a farming protocol can contain vaults, reward distributors, strategies, price oracles, DEX integrations, upgradeable contracts, and complex accounting logic.

That complexity is exactly what makes yield farming an attractive target.

In our experience at PandaSecurity, the most important question during a DeFi security review is not whether the protocol contains a familiar vulnerability such as reentrancy. It is whether an attacker can manipulate the relationship between assets, accounting, and rewards.

If that relationship breaks, an attacker may not need to exploit a traditional Solidity bug at all.

Follow the Money First

When reviewing a yield farming protocol, we prefer to start with the flow of assets rather than the individual functions.

Where does the user’s token go after deposit()? Is it held directly by the farming contract, moved into a vault, deposited into an external lending protocol, or converted into LP tokens?

Then follow the opposite direction. What exactly happens when the user calls withdraw()? Which contract actually releases the funds, and what assumptions does that contract make?

This approach often reveals the important parts of the system much faster than reading hundreds of lines of Solidity sequentially.

For example, a protocol may have perfectly reasonable deposit and withdrawal functions while using an unsafe exchange rate between user shares and underlying assets. From a traditional function-level review, nothing may immediately look wrong. From an asset-flow perspective, however, the question becomes obvious: can the attacker increase their ownership of the underlying assets without contributing equivalent value?

That is the type of question a yield farming audit should answer.

Reward Accounting Deserves Special Attention

Reward calculations are one of the areas where small mistakes can become economically significant.

A common farming design tracks accumulated rewards per share. As rewards accrue, the global reward index increases, and each user’s pending reward is calculated from their stake and the change in that index.

The formula is usually straightforward. The edge cases are not.

Consider what happens when the first user deposits, when the pool temporarily has no liquidity, when the reward rate changes, or when a user deposits immediately before a reward update and withdraws immediately afterward.

The important question is not simply whether the reward formula is mathematically correct.

It is whether users can manipulate when the formula is evaluated.

This distinction matters because smart contracts operate through discrete state transitions. A calculation that appears correct at one point in time can produce an unintended result when several transactions are executed in a carefully chosen sequence.

At PandaSecurity, we therefore pay particular attention to transaction ordering around deposits, withdrawals, reward updates, and claims. A farming protocol should be tested as a sequence of adversarial actions, not just as isolated function calls.

Share Accounting Can Create Unexpected Attack Surfaces

Vault-based farming systems introduce another important concept: shares.

Instead of recording that a user owns exactly 10 tokens, the protocol may record that the user owns a certain number of shares representing a percentage of the vault.

This creates an exchange rate between shares and assets.

Whenever an exchange rate exists, we want to understand what happens when the vault is nearly empty, when the first deposit is made, and when assets are transferred directly to the contract without going through the normal deposit function.

Direct token transfers are particularly easy to overlook.

Suppose a vault calculates shares using its current token balance. An attacker may be able to send tokens directly to the contract and change the apparent asset balance without receiving shares in return.

Whether this becomes exploitable depends on the exact accounting model, but the underlying principle is general:

The protocol should distinguish between assets that are economically accounted for and arbitrary changes to the contract’s token balance.

This is one reason why testing only the intended user flow is insufficient.

Token Behavior Cannot Always Be Assumed

Another common source of risk is assuming that every ERC20 token behaves exactly like a standard token.

Some tokens charge transfer fees. Others rebase their balances. Some have unusual decimal configurations or transfer restrictions.

If a farming contract assumes that a user depositing 100 tokens always results in exactly 100 tokens arriving at the contract, that assumption may be incorrect.

A safer accounting model can measure the actual balance change after a transfer when the protocol intends to support tokens with non-standard transfer behavior.

The same principle applies to withdrawals and strategies.

The code should account for what actually happened on-chain rather than what the developer expected to happen.

This becomes even more important when a protocol supports third-party assets that it does not control.

Oracle Security Is About Integration

Yield farming protocols often depend on asset prices to calculate collateral values, rewards, liquidation conditions, or share values.

Using a reputable oracle does not automatically make the integration secure.

The protocol still needs to handle stale prices, decimal conversion, unexpected zero values, large price movements, and oracle availability.

The source of the price also matters. A spot price taken directly from an AMM can potentially be manipulated, particularly when the protocol uses that price inside an atomic transaction where the attacker can temporarily change pool reserves.

This is where economic analysis becomes important.

An oracle manipulation issue is not automatically exploitable simply because a price can move. The real question is whether that manipulated value can be converted into more protocol assets than the attacker spends to perform the manipulation.

For that reason, our approach at PandaSecurity is to connect oracle analysis with the actual money flow. We want to know what the price controls and how much value can be extracted from changing it.

Privileged Functions Should Be Treated as Part of the Attack Surface

Yield farming protocols frequently contain administrative functionality for changing reward rates, updating strategies, pausing the protocol, recovering tokens, or upgrading contracts.

These permissions are sometimes excluded from the main security discussion because they are technically “trusted.”

That can be misleading.

If an administrator can replace the strategy holding all user assets, that permission is directly connected to user funds. If an administrator can arbitrarily change the reward rate, that may affect the solvency of the reward system.

The right question is therefore not simply whether a function is restricted to an admin.

The question is:

What can this role ultimately do to the protocol’s assets and accounting?

Clear role separation, multisig control, timelocks, and carefully limited upgrade permissions can significantly reduce the consequences of a compromised privileged key.

Emergency Functions Need Real Testing

Almost every serious DeFi protocol has some form of emergency mechanism.

The problem is that emergency functions are often tested less thoroughly than the normal user flow.

Imagine a strategy stops working and normal withdrawals start reverting. The protocol is paused and users are instructed to use an emergency withdrawal function.

If that emergency withdrawal still depends on the broken strategy, the protocol may not actually have an effective emergency exit.

Emergency paths should therefore be tested under abnormal states rather than only under normal conditions.

A good security review should ask what happens when the reward token is unavailable, an external protocol reverts, a strategy loses liquidity, or the protocol has already been paused.

An emergency mechanism is valuable only if it works when the system is already in trouble.

Cross-Contract Assumptions Are Often Where Bugs Hide

Modern DeFi protocols rarely operate as a single contract.

A farming contract may trust a strategy, which trusts a router, which interacts with a DEX. A vault may depend on an oracle while another contract controls the reward rate.

Each individual contract may look reasonable.

The vulnerability can exist in the assumption between them.

For example, a vault might assume that its strategy always returns the requested amount of assets. The strategy might assume that only the vault can call a particular function. If neither assumption is explicitly enforced, an attacker may be able to create a state that the developers never considered.

This is why a good audit cannot stop at checking individual contracts. The important security properties often exist at the system level.

Think Like an Arbitrageur, Not Just an Attacker

One of the biggest differences between DeFi security and traditional application security is that attackers can be extremely capital-efficient.

An attacker may use flash liquidity, temporary positions, DEX arbitrage, or transaction ordering to manipulate the protocol for only a few seconds.

The attack does not need to permanently compromise the contract.

It only needs to create a profitable state transition.

For example, imagine a farming protocol that rewards users based on the value of an LP position. If that value is calculated using a manipulatable market price, the attacker may temporarily distort the market, interact with the farming contract, and unwind the position in the same transaction.

The correct security question is therefore not:

“Can the attacker manipulate the price?”

It is:

“Can the attacker manipulate the price and turn that manipulation into more value than the attack costs?”

That distinction is critical when assessing real DeFi risk.

Our Approach to Yield Farming Security

At PandaSecurity, we believe yield farming audits should be driven by the protocol’s economic design rather than a generic vulnerability checklist.

We first reconstruct the important asset flows and state transitions. From there, we identify the assumptions that determine who can receive assets, how rewards are created, and how ownership is calculated.

Only then do we go deeper into individual Solidity vulnerabilities.

This approach helps connect seemingly unrelated issues. A rounding problem may matter because it can be repeated through deposits. An oracle problem may matter because it controls borrowing capacity. An access-control issue may matter because the compromised role controls the strategy holding the entire pool.

The severity of a DeFi vulnerability is often determined by these connections.

Final Thoughts

Yield farming security is ultimately about maintaining a consistent relationship between what users contribute, what the protocol records, and what the protocol allows them to withdraw.

Reward calculations, share accounting, token behavior, oracle integrations, privileged roles, emergency mechanisms, and external protocols all contribute to that relationship.

Developers should not rely solely on standard security checklists. The most valuable testing often comes from constructing unusual transaction sequences and asking whether an attacker can make the protocol believe something that is economically untrue.

For teams building yield farming protocols, vaults, staking systems, or other DeFi applications, PandaSecurity focuses on this exact problem: following the value, challenging the protocol’s assumptions, and testing whether the accounting remains correct under adversarial conditions.

A smart contract may compile perfectly and pass conventional tests. That does not necessarily mean its economic model is safe.

In DeFi, the final security test is simple:

Can someone extract more value than the system intended to give them?

Related articles

← Back to Blog