A Solidity smart contract that opens and closes a leveraged yield-farming position on Moonwell (a Compound V2 fork) on Base, using a Balancer flash loan for the leverage. Ships with a full Hardhat test suite, gas reporting, and mainnet-fork tests.
What this demonstrates: flash-loan mechanics end to end, integrating third-party DeFi protocols (Balancer, Moonwell/Compound), and testing against a forked mainnet with Hardhat and Ethers.js.
Educational implementation. Not audited; do not use with real funds.
Solidity ^0.8.x · Hardhat · Ethers.js v6 · Alchemy (Base RPC) · Balancer (flash-loan provider) · Moonwell (supply/borrow) · Base (Ethereum L2).
The contract has two entry points, deposit() and withdraw(), each wrapped around a Balancer flash loan.
Deposit
- Take amount X from the flash loan.
- Supply X plus a 30% margin into Moonwell.
- Borrow X back from Moonwell.
- Repay X to the flash loan.
Withdraw
- Take amount X from the flash loan.
- Repay the X borrowed from Moonwell.
- Redeem the amount supplied to Moonwell.
- Repay X to the flash loan.
- Claim and forward rewards to the user.
Internal flow: deposit() → getFlashLoan() → receiveFlashLoan() → handleDeposit() (and the mirror path for withdraw()). Balancer calls back into receiveFlashLoan() and reverts the whole transaction unless the borrowed tokens are returned in the same call, which is what makes the strategy atomic.
Sequence diagrams are in /diagrams.
npm install
cp .env.example .env # add ALCHEMY_API_KEY for a Base app
npx hardhat test # run the suite against a Base mainnet fork
REPORT_GAS=true npx hardhat test # optional: with gas reportingThe default fork block is set in hardhat.config.js. The tests exercise real Base contract addresses (USDC, Moonwell mUSDC/WELL/Comptroller, Balancer Vault); addresses differ by network.
APY and reward rates change with market conditions and with Moonwell's own parameters, so simulated end-of-test returns are indicative, not guaranteed. The contract structure is designed to extend to other Compound V2 forks or collateral markets.