Skip to content

DeFi Protocol Engineer Interview Questions & Answers

40 questions for DeFi Protocol Engineer interviews — 21 medium, 19 hard.

About the DeFi Protocol Engineer role

A DeFi protocol engineer designs and builds financial protocols such as exchanges, lending markets, vaults and staking systems. Beyond Solidity, the role requires understanding of AMM maths, oracle design, liquidation mechanics, tokenomics and risk parameters. Engineers model attacks like flash-loan manipulation, integrate with other protocols, and work with risk and governance teams to keep user funds safe. Strong maths and testing discipline are essential for this role.

AMM and lending maths Oracle integration Risk modelling Protocol integrations Tokenomics
Solved for this roleStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Design token vesting for team members and early investors.

Save to ▾
Show answer
Use a vesting contract that holds allocated tokens and releases them on a schedule, typically a one-year cliff followed by monthly or linear vesting over two to four years. OpenZeppelin VestingWallet gives linear vesting per beneficiary; add a cliff and an owner-controlled revoke for employees who leave, returning unvested tokens. Make schedules public on-chain for transparency, and avoid admin functions that could release tokens early, as that erodes investor trust.
02

Show a contract vulnerable to reentrancy and a fixed version.

Save to ▾
Show answer
Vulnerable: the balance is cleared after sending. function withdraw() external { uint256 bal = balances[msg.sender]; (bool ok, ) = msg.sender.call{value: bal}(''); require(ok); balances[msg.sender] = 0; } Fixed: update state first and add a guard. import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; function withdraw() external nonReentrant { uint256 bal = balances[msg.sender]; require(bal > 0, 'nothing'); balances[msg.sender] = 0; (bool ok, ) = msg.sender.call{value: bal}(''); require(ok, 'send failed'); }
03

How do you calculate a borrower's health factor in a lending protocol?

Save to ▾
Show answer
Health factor = (sum of collateral value x liquidation threshold) / total debt value. Below 1, the position can be liquidated. Example: collateral 10 ETH at 3,000 dollars = 30,000 dollars, liquidation threshold 80 percent, debt 18,000 dollars of stablecoins. HF = (30,000 x 0.80) / 18,000 = 1.33. If ETH falls to 2,250, collateral is 22,500, so HF = 18,000 / 18,000 = 1.0 and liquidation begins. Users raise HF by repaying debt or adding collateral.
04

What are Delegated Proof of Stake and Proof of Authority?

Save to ▾
Show answer
In Delegated Proof of Stake, token holders vote for a small set of block producers who validate on their behalf, giving high throughput but more centralisation. In Proof of Authority, a fixed set of known, reputable validators sign blocks; their identity, not stake, is at risk. PoA, often via Clique, IBFT or QBFT, suits private and consortium EVM networks and some testnets, where participants are known and fast, predictable block times matter more than open participation.
05

You are asked to design a cross-chain bridge. What are the main risks and design choices?

Save to ▾
Show answer
Bridges hold large pooled funds, so they are top hacking targets. Main risks are compromised validator or multisig keys, faulty message verification, and replay of messages across chains. Prefer verification based on light clients or zk proofs over a small trusted multisig. Use rate limits, per-transfer caps, pausing, monitoring of mint-versus-lock balances, and a delay for large transfers. Get multiple audits, run a bug bounty, and consider established messaging protocols instead of building from scratch.
06

You need the same contract at the same address on five chains. How do you do it?

Save to ▾
Show answer
Use CREATE2 through a deterministic deployment factory that already exists at the same address on all those chains. Keep the init code identical: same compiler version, optimiser settings, constructor arguments and metadata. Pick a salt, compute the expected address off-chain, then deploy on each chain. Foundry scripts support this by passing a salt. Avoid constructor arguments that differ per chain, or move chain-specific settings into an initialiser restricted to the deployer.
07

A stablecoin used as collateral in your protocol loses its peg. How do you respond?

Save to ▾
Show answer
Activate the risk plan: pause new borrowing against that asset and freeze its use as new collateral through governance or the guardian. Switch its oracle to a market price rather than a hard-coded one dollar, so positions are valued honestly, which may trigger liquidations. Reduce its loan-to-value and supply caps. Communicate clearly with users. Longer term, cap exposure per stablecoin, diversify collateral and model depeg scenarios in risk dashboards.
08

How does a constant product automated market maker work, and what is impermanent loss?

Save to ▾
Show answer
A constant product AMM holds two tokens with reserves x and y and keeps x times y equal to k. A trader adds one token and removes the other so that k stays constant after fees, which makes price equal to the reserve ratio and rise with trade size. Liquidity providers earn fees, but when prices move, arbitrage rebalances the pool, leaving them worse off than simply holding; that gap is impermanent loss.
09

Describe a time you found a security problem in code and how you handled it.

Save to ▾
Show answer
Situation: while reviewing a teammate's staking contract, I saw it sent tokens before updating the user's balance. Task: confirm the risk without blaming anyone. Action: I wrote a Foundry test with a malicious receiver that re-entered withdraw and drained extra funds, then shared it privately with a suggested fix using checks-effects-interactions and a reentrancy guard. Result: the fix merged before the audit, and we added reentrancy tests to our standard checklist.
10

Your contract fails to deploy because it exceeds the 24 KB size limit. What do you do?

Save to ▾
Show answer
The EIP-170 limit is 24,576 bytes of runtime code. First enable the optimiser and try a lower runs value or via-IR. Replace revert strings with custom errors, move repeated logic out of modifiers into internal functions, and remove unused code. If still too big, split logic into separate contracts or external libraries, or use a modular pattern like the Diamond (EIP-2535). Splitting also often improves clarity and auditability.
11

A sharp market fall causes cascading liquidations in your lending protocol and bad debt. How do you design against it?

Save to ▾
Show answer
Set conservative loan-to-value ratios and liquidation thresholds per asset based on volatility and on-chain liquidity. Use supply and borrow caps for illiquid tokens, isolation mode for risky assets, and a liquidation bonus that attracts liquidators without over-penalising users. Allow partial liquidations so positions shrink gradually. Keep reliable oracles, an insurance or reserve fund to absorb bad debt, and run stress tests simulating 30 to 50 percent price drops.
12

Why should you check return values of low-level calls and use SafeERC20?

Save to ▾
Show answer
Low-level call, send and delegatecall return false instead of reverting on failure, so ignoring the result means the contract continues as if the transfer succeeded. Similarly, some ERC-20 tokens do not return a bool from transfer, and others return false instead of reverting. OpenZeppelin's SafeERC20 wraps transfer, transferFrom and approve to handle both cases and revert on failure. Always write (bool ok, ) = to.call{value: x}(''); require(ok).
13

A user's transaction has been pending for an hour. How do you troubleshoot it?

Save to ▾
Show answer
First check it on a block explorer: if it is not found, it was never broadcast. If pending, the fee is probably below current market rates, or an earlier transaction with a lower nonce is stuck and blocking it. On Ethereum you fix it by sending a replacement with the same nonce and a higher max fee and priority fee, or cancel by sending zero ETH to yourself with that nonce. Then make the wallet estimate fees dynamically.
14

A client in India wants to tokenise real estate for fractional ownership. What do you consider?

Save to ▾
Show answer
Regulation comes first: fractional real estate is likely a security or collective investment, so SEBI rules, including those for fractional ownership platforms, apply, and crypto-like tokens are taxed as virtual digital assets at 30 percent with 1 percent TDS. Use a permissioned token with KYC-gated transfers, such as ERC-3643, and a legal SPV that holds the property. Keep title documents off-chain, put hashes on-chain, and plan for rent distribution, transfer restrictions and recovery.
15

What are storage collision and uninitialised implementation risks in proxies?

Save to ▾
Show answer
With delegatecall, the implementation's code writes to the proxy's storage. If the proxy stores its admin or implementation address in a normal slot, implementation variables can overwrite it, so EIP-1967 uses pseudo-random slots. New implementation versions must only append variables, or use namespaced storage (ERC-7201). Implementations must also disable initialisers in their constructor; otherwise an attacker can initialise the implementation directly, take ownership and, in UUPS, potentially destroy or hijack it.
16

Explain Byzantine Fault Tolerance and the 3f+1 rule.

Save to ▾
Show answer
Byzantine Fault Tolerance is the ability of a system to reach agreement even when some nodes lie or act arbitrarily. Classical BFT protocols such as PBFT, Tendermint and QBFT need at least 3f+1 nodes to tolerate f Byzantine nodes, because a quorum of 2f+1 votes guarantees that any two quorums overlap in at least one honest node. They give instant deterministic finality but involve heavy message passing, so they work best with tens to low hundreds of validators.
17

Tell me about working with product, legal or compliance teams on a blockchain feature.

Save to ▾
Show answer
Situation: we planned a token reward feature for Indian users, and legal raised VDA tax and securities concerns. Task: as tech lead I had to find a compliant design. Action: I ran workshops to understand their constraints, proposed non-transferable points that convert to vouchers, and documented the data flow for compliance. Result: we launched a month later than planned but with sign-off from all teams, and avoided a costly redesign after launch.
18

What did EIP-4844 (proto-danksharding) change?

Save to ▾
Show answer
EIP-4844, shipped in the Dencun upgrade in March 2024, added blob-carrying transactions. Blobs are large data chunks of about 128 KB that rollups use to post batch data, priced in a separate fee market and pruned by nodes after roughly 18 days. Contracts cannot read blob contents, only their KZG commitments. This cut L2 data costs dramatically. Later upgrades raised blob capacity, and PeerDAS in the Fusaka upgrade lets nodes sample data instead of downloading every blob.
19

The business wants to change contract logic after launch. How do you plan for it?

Save to ▾
Show answer
Decide early whether upgradeability is needed, because it adds trust and storage risks. Options are a proxy (UUPS or Transparent) controlled by a multisig with a timelock, a parameter-driven design where only settings like fees change through governed setters, or a migration plan to a new immutable version. Whatever you choose, document it for users, protect upgrade rights, keep storage layout append-only, and test each upgrade on a fork before executing.
20

Write a Foundry invariant test for a token's total supply.

Save to ▾
Show answer
Invariant tests call random functions on target contracts and check a property after every call. import {Test} from 'forge-std/Test.sol'; import {MyToken} from '../src/MyToken.sol'; import {Handler} from './Handler.sol'; contract SupplyInvariant is Test { MyToken token; Handler handler; function setUp() public { token = new MyToken(); handler = new Handler(token); targetContract(address(handler)); } function invariant_supplyMatchesBalances() public view { assertEq(token.totalSupply(), handler.sumOfBalances()); } } The handler bounds inputs and tracks actors so calls stay realistic.
21

A user lost funds on our DeFi app due to their own mistake and is angry. How would you handle it?

Save to ▾
Show answer
Situation: a user sent tokens to the contract address directly instead of using deposit, and they were stuck. Task: support him honestly. Action: I listened, explained calmly what happened without blaming him, checked whether a recovery function existed, and escalated to the team. We had a rescue function for stray tokens behind the multisig, so after verification we returned them. Result: he thanked us publicly, and we added a front-end warning.
22

What is a signature replay attack and how do you prevent it?

Save to ▾
Show answer
If a contract accepts a signed message to perform an action, an attacker can resubmit the same signature to repeat it, or replay it on another chain or another contract using the same code. Prevent it by including a per-user nonce that increments on use, a deadline, the chain ID and the verifying contract address in the signed data. EIP-712 typed data with a domain separator gives a standard way to include these fields.
23

Your protocol is being exploited right now. What do you do?

Save to ▾
Show answer
Act fast with a prepared runbook. Pause affected contracts through the guardian or multisig, and disable front-end actions. Gather the core team and security partners in a war room. Trace the attack transactions to understand the bug and estimate losses, and check whether a white-hat rescue of remaining funds is needed. Communicate publicly with facts and no speculation, contact exchanges and bridges to flag stolen funds, then fix, audit the fix and publish a post-mortem.
24

Tell me about a time you explained blockchain to a non-technical stakeholder.

Save to ▾
Show answer
Situation: a business head wanted 'blockchain' in a vendor portal because competitors mentioned it. Task: help him decide. Action: I compared it to a shared online spreadsheet that nobody can secretly edit, then showed cost, speed and privacy trade-offs against a normal database with audit logs. Result: we agreed to keep the portal on a database and anchor monthly hashes of invoices on a chain for proof, saving months of work while meeting the trust goal.
25

What is MEV and what is proposer-builder separation?

Save to ▾
Show answer
MEV, maximal extractable value, is profit a block producer or searcher earns by including, excluding or reordering transactions, for example arbitrage, liquidations and sandwich attacks on swaps. On Ethereum, most validators use MEV-Boost, where specialised builders assemble profitable blocks and bid for them through relays, separating block building from proposing. This spreads MEV revenue to validators but concentrates building power. Enshrined PBS and inclusion lists are being researched to reduce censorship risk.
26

What is the difference between a soft fork and a hard fork?

Save to ▾
Show answer
A soft fork tightens the rules so that new blocks are still valid for old nodes; it is backward compatible, like Bitcoin's SegWit upgrade. A hard fork changes the rules so that old nodes reject new blocks, so every node must upgrade or the chain splits, as with Ethereum and Ethereum Classic in 2016. Planned network upgrades on Ethereum, such as Dencun and Pectra, are coordinated hard forks that all clients adopt together.
27

Your dApp's users are paying high gas fees on Ethereum mainnet. How would you choose a Layer 2?

Save to ▾
Show answer
I would compare candidate rollups on security (proof system live, stage of decentralisation, upgrade keys), EVM compatibility so our Solidity code deploys unchanged, ecosystem fit (wallets, oracles, liquidity, bridges our users already use), fees and throughput, and withdrawal experience. I would deploy to testnets first, measure real costs and latency, and check that our dependencies such as Chainlink feeds exist there. Then migrate gradually, keeping L1 contracts for high-value settlement if needed.
28

What are cross-function and read-only reentrancy?

Save to ▾
Show answer
Cross-function reentrancy happens when an attacker re-enters a different function that shares state with the one making the external call, so a guard on only one function does not help. Read-only reentrancy happens when a view function, such as a pool's price getter, returns inconsistent state mid-execution, and another protocol reads it during the callback and misprices assets. Mitigate by guarding all state-sharing functions, updating state before calls, and checking a reentrancy lock in view functions other protocols rely on.
29

Calculate impermanent loss when one token's price doubles.

Save to ▾
Show answer
Formula: IL = 2 x sqrt(r) / (1 + r) - 1, where r is the price ratio change. For r = 2: sqrt(2) = 1.414, so IL = 2 x 1.414 / 3 - 1 = -0.057, about 5.7 percent. Example: deposit 1 ETH plus 3,000 USDC when ETH is 3,000 (6,000 dollars). ETH goes to 6,000. Holding would be 9,000 dollars; the pool position is worth about 8,485. Fees earned must exceed the 515 dollar gap for providing liquidity to beat holding.
30

What is the difference between optimistic rollups and zk-rollups?

Save to ▾
Show answer
Optimistic rollups assume batches are valid and allow a challenge window, typically about seven days, during which anyone can submit a fraud proof; this makes them EVM-compatible and simpler but slows native withdrawals. Zk-rollups submit a validity proof with each batch, so L1 verifies correctness mathematically and withdrawals finalise once the proof is accepted. Zk proving is computationally heavy and EVM equivalence was harder, though zkEVMs have matured a lot by 2026.
31

How do you manage deployer private keys in a CI/CD pipeline?

Save to ▾
Show answer
Never commit keys or put them in plain environment files. For testnets, use CI secret storage with restricted access. For mainnet, avoid hot keys in CI entirely: have CI produce a transaction proposal that signers approve in a multisig, or use a cloud KMS or HSM signer so the key never leaves secure hardware. Separate deployer and admin roles, transfer ownership to a multisig immediately after deployment, and log and review every deployment.
32

Four organisations are building a private EVM network. Which consensus would you pick: Raft or QBFT?

Save to ▾
Show answer
Raft is crash fault tolerant: fast and simple, but it assumes no node lies, so it fits when all members trust each other's infrastructure. QBFT is Byzantine fault tolerant and tolerates f malicious nodes out of 3f+1, so with four validators it survives one bad actor and gives immediate finality. Since the organisations are separate businesses that may not fully trust each other, I would choose QBFT and run at least four validators, ideally more.
33

Write the core reward-per-token logic for a staking rewards contract.

Save to ▾
Show answer
uint256 public rewardRate; // tokens per second uint256 public rewardPerTokenStored; uint256 public lastUpdate; uint256 public totalStaked; mapping(address => uint256) public paid; mapping(address => uint256) public rewards; mapping(address => uint256) public staked; function rewardPerToken() public view returns (uint256) { if (totalStaked == 0) return rewardPerTokenStored; return rewardPerTokenStored + (block.timestamp - lastUpdate) * rewardRate * 1e18 / totalStaked; } modifier updateReward(address a) { rewardPerTokenStored = rewardPerToken(); lastUpdate = block.timestamp; rewards[a] += staked[a] * (rewardPerTokenStored - paid[a]) / 1e18; paid[a] = rewardPerTokenStored; _; }
34

How do you build a tokenised vault using ERC-4626?

Save to ▾
Show answer
ERC-4626 standardises yield vaults: users deposit an asset and receive shares, and share price rises as the vault earns yield. import {ERC4626} from '@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; contract YieldVault is ERC4626 { constructor(IERC20 asset_) ERC20('Vault Share', 'vSHR') ERC4626(asset_) {} function totalAssets() public view override returns (uint256) { return IERC20(asset()).balanceOf(address(this)); // plus deployed funds } } OpenZeppelin uses virtual shares to defend against the first-depositor inflation attack.
35

What does a smart contract audit process look like?

Save to ▾
Show answer
It starts with scoping: fixed commit, documentation, threat model and test coverage. Auditors run automated tools like Slither and fuzzers, then do manual line-by-line review, checking business logic, access control, economic attacks and integrations. They write findings rated critical, high, medium, low and informational with fixes. The team fixes issues, auditors review the fixes, and a final report is published. Audits reduce risk but do not guarantee safety, so add bug bounties and monitoring.
36

Your team is preparing a contract for an external audit. What do you do beforehand?

Save to ▾
Show answer
Freeze the code at a commit and stop adding features. Write clear documentation: architecture, roles, trust assumptions, invariants and known risks. Reach high test coverage including fuzz and invariant tests, and run Slither and fix its findings. Remove dead code, add NatSpec comments, and make the build reproducible. Share a scope list and a walkthrough call. A clean, well-documented codebase lets auditors spend their limited time on deep logic bugs.
37

What is slashing in Proof of Stake?

Save to ▾
Show answer
Slashing is a penalty that burns part of a validator's stake and forcibly exits it when it provably breaks protocol rules. On Ethereum the slashable offences are proposing two different blocks in the same slot and making conflicting or surrounding attestations. The penalty grows if many validators are slashed around the same time, which punishes coordinated attacks. Simply being offline is not slashing; it only causes small inactivity penalties. Running the same key on two machines is the most common cause.
38

How do flash loans enable oracle manipulation attacks?

Save to ▾
Show answer
A flash loan lets anyone borrow huge amounts without collateral if it is repaid in the same transaction. An attacker borrows, makes a large trade in a thin DEX pool to move its spot price, then uses a protocol that reads that pool as its price oracle, for example borrowing too much against inflated collateral, and finally reverses the trade and repays. Defend with decentralised oracles like Chainlink, TWAPs, multiple sources and sanity bounds.
39

How can a smart contract suffer denial of service?

Save to ▾
Show answer
Common causes: loops over arrays that grow with users until they exceed the block gas limit; push payments in a loop where one reverting recipient blocks everyone; relying on an external call that an attacker can make fail; and griefing by filling storage cheaply. For example, an auction that refunds the previous bidder will freeze if that bidder is a contract that reverts. Use pull payments, bounded loops, pagination and failure isolation.
40

An attacker borrows governance tokens with a flash loan to pass a malicious DAO proposal. How do you prevent it?

Save to ▾
Show answer
Use snapshot-based voting power: count votes from token balances at a past block, as ERC20Votes does, so tokens acquired in the same transaction have no weight. Add a voting delay before voting starts, a quorum, and a timelock between approval and execution so the community can react or a guardian can veto. Require a proposal threshold, and keep critical actions such as treasury transfers behind additional safeguards like spending limits.

Frequently asked questions

What does a DeFi Protocol Engineer do?

A DeFi protocol engineer designs and builds financial protocols such as exchanges, lending markets, vaults and staking systems. Beyond Solidity, the role requires understanding of AMM maths, oracle design, liquidation mechanics, tokenomics and risk parameters. Engineers model attacks like flash-loan manipulation, integrate with other protocols, and work with risk and governance teams to keep user funds safe. Strong maths and testing discipline are essential for this role.

Which skills are tested in a DeFi Protocol Engineer interview?

Expect questions on AMM and lending maths, Oracle integration, Risk modelling, Protocol integrations, Tokenomics. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a DeFi Protocol Engineer interview?

Revise DeFi, Tokens and NFTs, Smart Contract Security, Consensus and Scaling first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.