🪙mTokens
Integration Quickstart
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import {MErc20} from "@moonwell/MErc20.sol";
import {EIP20Interface} from "@moonwell/EIP20Interface.sol";
import {ComptrollerInterface} from "@moonwell/ComptrollerInterface.sol";
contract MoonwellIntegration {
/// @notice Supply USDC and borrow WETH against it
function supplyAndBorrow(
address mUSDC, // Moonwell USDC mToken
address mWETH, // Moonwell WETH mToken
address comptroller,
uint256 supplyAmount,
uint256 borrowAmount
) external {
// 1. Approve the mToken to pull underlying
EIP20Interface usdc = EIP20Interface(MErc20(mUSDC).underlying());
usdc.approve(mUSDC, supplyAmount);
// 2. Supply - mints mTokens to this contract
uint err = MErc20(mUSDC).mint(supplyAmount);
require(err == 0, "mint failed");
// 3. Enter the market - enables USDC as collateral
address[] memory markets = new address[](1);
markets[0] = mUSDC;
uint[] memory results = ComptrollerInterface(comptroller).enterMarkets(markets);
require(results[0] == 0, "enterMarkets failed");
// 4. Borrow WETH against USDC collateral
err = MErc20(mWETH).borrow(borrowAmount);
require(err == 0, "borrow failed");
}
/// @notice Repay WETH borrow and withdraw USDC
function repayAndWithdraw(
address mUSDC,
address mWETH,
uint256 repayAmount,
uint256 withdrawAmount
) external {
// 1. Approve and repay the borrow
EIP20Interface weth = EIP20Interface(MErc20(mWETH).underlying());
weth.approve(mWETH, repayAmount);
uint err = MErc20(mWETH).repayBorrow(repayAmount);
require(err == 0, "repay failed");
// 2. Withdraw USDC by specifying the underlying amount
err = MErc20(mUSDC).redeemUnderlying(withdrawAmount);
require(err == 0, "redeem failed");
}
/// @notice Query current positions
function getPositions(
address mToken,
address account
) external view returns (
uint256 mTokenBalance,
uint256 borrowBalance,
uint256 exchangeRate
) {
(uint err, uint bal, uint borrows, uint rate) =
MErc20(mToken).getAccountSnapshot(account);
require(err == 0, "snapshot failed");
return (bal, borrows, rate);
}
}Key Concepts
Exchange Rate
Interest Accrual
Error Handling
Deployed Contracts
Base
Market
Address
OP Mainnet
Market
Address
Last updated

