Skip to content

Manage Positions

This guide shows you how to manage your positions in Morpho Vaults using Solidity snippets.

To use these snippets, you can either:

  1. Deploy the full MorphoVaultSnippets contract
  2. Copy the specific functions you need into your own contract

Imports

import {IMetaMorpho, MarketAllocation} from "@metamorpho/interfaces/IMetaMorpho.sol";
import {MarketParamsLib} from "../../lib/metamorpho/lib/morpho-blue/src/libraries/MarketParamsLib.sol";
import {IMorpho} from "../../lib/metamorpho/lib/morpho-blue/src/interfaces/IMorpho.sol";
import {ERC20} from "@openzeppelin/token/ERC20/ERC20.sol";

Base Contract

contract MetaMorphoSnippets {
 
    IMorpho public immutable morpho;
 
    constructor(address morphoAddress) {
        morpho = IMorpho(morphoAddress);
    }
 
    ...

Functions

Deposit
    function _approveMaxVault(address vault) internal {
        if (ERC20(IMetaMorpho(vault).asset()).allowance(address(this), vault) == 0) {
            ERC20(IMetaMorpho(vault).asset()).approve(vault, type(uint256).max);
        }
    }
 
    /// @notice Deposit `assets` into the `vault` on behalf of `onBehalf`.
    /// @dev Sender must approve the snippets contract to manage his tokens before the call.
    /// @param vault The address of the MetaMorpho vault.
    /// @param assets the amount to deposit.
    /// @param onBehalf The address that will own the increased deposit position.
    function depositInVault(address vault, uint256 assets, address onBehalf) public returns (uint256 shares) {
        ERC20(IMetaMorpho(vault).asset()).transferFrom(msg.sender, address(this), assets);
 
        _approveMaxVault(vault);
 
        shares = IMetaMorpho(vault).deposit(assets, onBehalf);
    }