Mangrove
Developper
Developper
  • Welcome
  • Protocol
    • Introduction
    • Technical References
      • Overview
      • Ticks, ratios, and prices
      • Offer-list
        • Views on offers
      • Market-order
        • Delegation
      • Creating & Updating offers
        • Maker contract
        • Offer provisions
        • Gas requirement
        • Public data structures
        • Executing offers
      • Cleaning offers
      • Governance-parameters
        • Global variables
        • Local variables
        • Data structures and views
      • Periphery Contracts
        • MgvReader
        • MgvOracle
      • Literate Source Code
    • Background
      • Taking available liquidity
      • Making liquidity available
      • Reneging on offers
  • Strat Lib
    • What is the Strat Library?
    • Getting-started
      • Set Up Your Local Environment
      • Post a Smart Offer
    • Guides
      • Unlocking liquidity
      • Reposting an offer in the posthook
      • Using last look to renege trades
      • Determining gas requirements
      • Creating a Direct contract
      • Deploying your contract
      • Testing a maker contract
      • Safe offer logic guidelines
      • Approvals
    • Technical references
      • Principal hooks
      • Liquidity routing
      • API preferences
        • Core
          • SRC
            • IMangrove
        • Strats
          • SRC
            • Strategies
              • MangroveOffer
              • MangroveOrder
              • Integrations
                • AaveV3Borrower
                • AaveV3BorrowerImplementation
                • AaveV3BorrowerStorage
                • AaveV3Lender
                • CompoundModule
              • Interfaces
                • IForwarder
                • ILiquidityProvider
                • IOfferLogic
                • IOrderLogic
              • Offer_forwarder
                • Abstract
                  • Forwarder
              • Offer_maker
                • Abstract
                  • Direct
                • Market_making
                  • Kandel
                    • AaveKandel
                    • AaveKandelSeeder
                    • KandelSeeder
                    • Abstract
                      • AbstractKandelSeeder
                      • CoreKandel
                      • DirectWithBidsAndAsksDistribution
                      • GeometricKandel
                      • HasIndexedBidsAndAsks
                      • KandelLib
                      • TradesBaseQuotePair
              • Routeurs
                • SimpleRouter
                • Abstract
                  • AbstractRouter
                • Integrations
                  • AavePooledRouter
                  • HasAaveBalanceMemoizer
              • Utils
                • AccessControlled
              • Vendor
                • AAVE
                  • V3
                    • Contracts
                      • Dependencies
                        • Oppenzeppelin
                          • Contracts
                            • IERC20
                      • Interfaces
                        • IAToken
                        • IAaveIncentivesController
                        • IAaveOracle
                        • ICreditDelegationToken
                        • IInitializableAToken
                        • IPool
                        • IPoolAddressesProvider
                        • IPriceOracleGetter
                        • IScaledBalanceToken
                      • Protocol
                        • Libraries
                          • Configurations
                            • ReserveConfiguration
                          • Helpers
                            • Errors
                          • Types
                            • DataTypes
                    • Periphery
                      • Contracts
                        • MISC
                          • Interfaces
                            • IEACAggregatorProxy
                        • Rewards
                          • Interfaces
                            • IRewardsController
                            • IRewardsDistributor
                            • ITransferStrategyBase
                          • Libraries
                            • RewardsDataTypes
                • Compound
                  • CarefulMath
                  • Exponential
                  • ExponentialNoError
                  • ICompound
    • Background
      • Building Blocks
        • MangroveOffer
        • Direct
        • Forwarder
  • Vaults
    • Understanding vaults
      • Oracles
    • Managing a vault (CLI)
      • Deploying an oracle
      • Creating a vault
      • Monitoring the vault
      • Setting the vault position
      • Setting the fee data
      • Rebalancing
      • Adding or removing liquidity
    • Custom interactions
      • Oracles
      • Vault Factory
      • Managing a vault
        • Setting the position
        • Rebalancing
        • Setting a manager
        • Setting fee
  • Keeper Bots
    • Keeper Bots
    • Guides
      • Using borrowed funds for cleaning
    • Backgroud
      • The role of cleaning bots in Mangrove
      • The role of gas price updater bots in Mangrove
  • Adresses
    • Deployment Addresses
  • Quick Links
    • Glossary
    • Website
    • Whitepaper
Powered by GitBook
On this page
  • A simple Direct implementation - the OfferMaker​
  • Advanced Direct offer: Liquidity Amplification with Amplifier​
  1. Strat Lib
  2. Guides

Creating a Direct contract

PreviousDetermining gas requirementsNextDeploying your contract

Last updated 1 month ago

Work in progress

This page is currently being updated - thank you for your understanding.

Info :

This section will go through two implementations of a , which inherits from the Direct contract. If you don't know what the Direct contract is, we recommend reading through both the documentation on and on before continuing.

A simple Direct implementation - the OfferMaker

Below, we start by going through a fairly simple implementation of the abstract contract.

Recall that Direct is an abstract implementation of MangroveOffer, which is itself a partial implementation of - the basic interface for maker contracts built with the Strat Library.

Constructor

The Direct constructor looks like this:

Direct contract's constructor

constructor(IMangrove mgv, AbstractRouter router_, address reserveId) MangroveOffer(mgv) {
  if (router_ != NO_ROUTER) {
    setRouter(router_);
  }
  address reserveId_ = reserveId == address(0) ? address(this) : reserveId;
  RESERVE_ID = reserveId_;
  emit SetReserveId(reserveId_);
}

Details:

  • mgv (the address of the Mangrove contract) is provided to MangroveOffer.

  • The specific arguments of the Direct's constructor are:

Note :

Passing address(0) as reserveId is interpreted by Direct as requiring reserveId to be the contract's address.

Preamble and constructor

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import {ILiquidityProvider} from "@mgv-strats/src/strategies/interfaces/ILiquidityProvider.sol";
import {OLKey} from "@mgv/src/core/MgvLib.sol";
import {Tick, TickLib} from "@mgv/lib/core/TickLib.sol";
import {Direct} from "@mgv-strats/src/strategies/offer_maker/abstract/Direct.sol";
import {IMangrove} from "@mgv/src/IMangrove.sol";
import {AbstractRouter} from "@mgv-strats/src/strategies/routers/abstract/AbstractRouter.sol";
import {ITesterContract} from "@mgv-strats/src/toy_strategies/interfaces/ITesterContract.sol";
import {IERC20} from "@mgv/lib/IERC20.sol";

contract OfferMaker is ILiquidityProvider, ITesterContract, Direct {
  // router_ needs to bind to this contract
  // since one cannot assume `this` is admin of router, one cannot do this here in general
  constructor(IMangrove mgv, AbstractRouter router_, address deployer, address owner) Direct(mgv, router_, owner) {
    // stores total gas requirement of this strat (depends on router gas requirements)
    // if contract is deployed with static address, then one must set admin to something else than msg.sender
    if (deployer != msg.sender) {
      setAdmin(deployer);
    }
  }

Our implementation of newOffer is simply to expose the internal _newOffer provided by Direct making sure the function is admin restricted (Direct provides the appropriate modifier onlyAdmin):

Offer management functions

///@inheritdoc ILiquidityProvider
function newOffer(OLKey memory olKey, Tick tick, uint gives, uint gasreq)
  public
  payable
  override
  onlyAdmin
  returns (uint offerId)
{
  (offerId,) = _newOffer(
    OfferArgs({olKey: olKey, tick: tick, gives: gives, gasreq: gasreq, gasprice: 0, fund: msg.value, noRevert: false})
  );
}

///@inheritdoc ILiquidityProvider
function updateOffer(OLKey memory olKey, Tick tick, uint gives, uint offerId, uint gasreq)
  public
  payable
  override
  onlyAdmin
{
  _updateOffer(
    OfferArgs({olKey: olKey, tick: tick, gives: gives, gasreq: gasreq, gasprice: 0, fund: msg.value, noRevert: false}),
    offerId
  );
}

///@inheritdoc ILiquidityProvider
function retractOffer(OLKey memory olKey, uint offerId, bool deprovision)
  public
  adminOrCaller(address(MGV))
  returns (uint freeWei)
{
  freeWei = _retractOffer(olKey, offerId, deprovision);
  if (freeWei > 0) {
    require(MGV.withdraw(freeWei), "Direct/withdrawFail");
    // sending native tokens to `msg.sender` prevents reentrancy issues
    // (the context call of `retractOffer` could be coming from `makerExecute` and a different recipient of transfer than `msg.sender` could use this call to make offer fail)
    (bool noRevert,) = admin().call{value: freeWei}("");
    require(noRevert, "mgvOffer/weiTransferFail");
  }
}

FIXME: Describe the new functions in OfferMaker: newOfferByVolume and updateOfferByVolume

Redeeming funds

We do not provide any method to redeem inbound or outbound tokens from the contract. However, MangroveOffer provides an admin-only approve function, that allows contract's admin to retrieve any token, following a call sequence of the form:

makerContract.approve(token, address(this), amount);
token.transferFrom(address(makerContract), address(this), amount);

With a simple implementation of Direct under our belt, let us proceed show how we can tweak our maker contract to do something more interesting that posting plain offers on Mangrove.

Suppose we have a certain amount N of some BASE token and we wish to put it for sale on two markets at the same time. To simplify assume that BASE is some volatile asset like ETH and we wish to sell it for any of two (equivalent-ish) stables STABLE1 and STABLE2 (e.g. DAI and USDC).

We have a design choice here. Either we

We modify the simple constructor of OfferMaker to take into account the additional gas requirements of Amplifier's logic: To retract (or update) the second offer each time an offer is taken. We also choose to specialize instances of our maker contract to a particular choice of BASE, STABLE1 and STABLE2 tokens - requiring these to be given as arguments when construing the contract.

Amplifier - Preamble and constructor

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@mgv-strats/src/strategies/offer_maker/abstract/Direct.sol";
import "@mgv-strats/src/strategies/routers/SimpleRouter.sol";
import {MgvLib, Offer, OfferDetail} from "@mgv/src/core/MgvLib.sol";
import {TickLib, Tick} from "@mgv/lib/core/TickLib.sol";

contract Amplifier is Direct {
  IERC20 public immutable BASE;
  IERC20 public immutable STABLE1;
  IERC20 public immutable STABLE2;
  uint public immutable TICK_SPACING1;
  uint public immutable TICK_SPACING2;

  ///mapping(IERC20 => mapping(IERC20 => uint)) // base -> stable -> offerid

  uint offerId1; // id of the offer on stable 1
  uint offerId2; // id of the offer on stable 2

  //           MangroveOffer <-- makerExecute
  //                  /\
  //                 / \
  //        Forwarder  Direct <-- offer management (our entry point)
  //    OfferForwarder  OfferMaker <-- new offer posting

  constructor(
    IMangrove mgv,
    IERC20 base,
    IERC20 stable1,
    IERC20 stable2,
    uint tickSpacing1,
    uint tickSpacing2,
    address admin
  ) Direct(mgv, NO_ROUTER, admin) {
    // SimpleRouter takes promised liquidity from admin's address (wallet)
    STABLE1 = stable1;
    STABLE2 = stable2;
    TICK_SPACING1 = tickSpacing1;
    TICK_SPACING2 = tickSpacing2;
    BASE = base;
    AbstractRouter router_ = new SimpleRouter();
    setRouter(router_);
    // adding `this` to the allowed makers of `router_` to pull/push liquidity
    // Note: `admin` needs to approve `this.router()` for base token transfer
    router_.bind(address(this));
    router_.setAdmin(admin);
    setAdmin(admin);
  }

Note that as we manually construct and configure router_ and set it as the router of Amplifier, we initially send the constant NO_ROUTER as argument to the Direct constructor.

As in the example above, we need to create a way for the maker contract to post an offer. For this example, we will not try to comply to the ILiquidityProvider interface - and therefore this contract will no longer be fully usable with the SDK. We will use a custom way of posting our two offers in the same transaction.

Amplifier - Publishing amplified offers

function newAmplifiedOffers(
  // this function posts two asks
  uint gives,
  uint wants1,
  uint wants2,
  uint gasreq
) external payable onlyAdmin returns (uint, uint) {
  // there is a cost of being paternalistic here, we read MGV storage
  // an offer can be in 4 states:
  // - not on mangrove (never has been)
  // - on an offer list (isLive)
  // - not on an offer list (!isLive) (and can be deprovisioned or not)
  // MGV.retractOffer(..., deprovision:bool)
  // deprovisioning an offer (via MGV.retractOffer) credits maker balance on Mangrove (no native token transfer)
  // if maker wishes to retrieve native tokens it should call MGV.withdraw (and have a positive balance)
  require(
    !MGV.offers(OLKey(address(BASE), address(STABLE1), TICK_SPACING1), offerId1).isLive(),
    "Amplifier/offer1AlreadyActive"
  );
  require(
    !MGV.offers(OLKey(address(BASE), address(STABLE2), TICK_SPACING2), offerId2).isLive(),
    "Amplifier/offer2AlreadyActive"
  );
  // FIXME the above requirements are not enough because offerId might be live on another base, stable market

  Tick tick = TickLib.tickFromVolumes(wants1, gives);

  (offerId1,) = _newOffer(
    OfferArgs({
      olKey: OLKey(address(BASE), address(STABLE1), TICK_SPACING1),
      tick: tick,
      gives: gives,
      gasreq: gasreq,
      gasprice: 0,
      fund: msg.value,
      noRevert: false
    })
  );
  // no need to fund this second call for provision
  // since the above call should be enough
  tick = TickLib.tickFromVolumes(wants2, gives);

  (offerId2,) = _newOffer(
    OfferArgs({
      olKey: OLKey(address(BASE), address(STABLE2), TICK_SPACING2),
      tick: tick,
      gives: gives,
      gasreq: gasreq,
      gasprice: 0,
      fund: 0,
      noRevert: false
    })
  );

  return (offerId1, offerId2);
}

Possible gas optimization

Amplifier - Reposting the residual

function __posthookSuccess__(MgvLib.SingleOrder calldata order, bytes32 makerData)
  internal
  override
  returns (bytes32)
{
  // reposts residual if any (conservative hook)
  bytes32 repost_status = super.__posthookSuccess__(order, makerData);

Default reposting policy

We continue our implementation of the __posthookSuccess__ hook by handling case 1:

Amplifier - Reposting case 1: An offer was reposted with a residual

(OLKey memory altOlKey, uint alt_offerId) = IERC20(order.olKey.inbound_tkn) == STABLE1
  ? (OLKey(order.olKey.outbound_tkn, address(STABLE2), TICK_SPACING2), offerId2)
  : (OLKey(order.olKey.outbound_tkn, address(STABLE1), TICK_SPACING1), offerId1);
if (repost_status == REPOST_SUCCESS) {
  (uint new_alt_gives,) = __residualValues__(order); // in base units
  Offer alt_offer = MGV.offers(altOlKey, alt_offerId);
  OfferDetail alt_detail = MGV.offerDetails(altOlKey, alt_offerId);

  uint old_alt_wants = alt_offer.wants();
  // old_alt_gives is also old_gives
  uint old_alt_gives = order.offer.gives();
  // we want new_alt_wants == (old_alt_wants:96 * new_alt_gives:96)/old_alt_gives:96
  // so no overflow to be expected :)
  uint new_alt_wants;
  unchecked {
    new_alt_wants = (old_alt_wants * new_alt_gives) / old_alt_gives;
  }

  // the call below might throw
  bytes32 reason = _updateOffer(
    OfferArgs({
      olKey: altOlKey,
      gives: new_alt_gives,
      tick: TickLib.tickFromVolumes(new_alt_wants, new_alt_gives),
      gasreq: alt_detail.gasreq(),
      gasprice: 0,
      fund: 0,
      noRevert: true
    }),
    alt_offerId
  );
  if (reason != REPOST_SUCCESS) {
    return "posthook/altOfferRepostFail";
  } else {
    return "posthook/bothOfferReposted";
  }
  • the offer was completely filled

In all of these cases we wish to retract the other offer from the book.

Amplifier - Reposting case 2: Offer was not reposted

} else {
  // repost failed or offer was entirely taken
  retractOffer({olKey: altOlKey, offerId: alt_offerId, deprovision: false});
  return "posthook/bothRetracted";
}

Refunding offer automatically

Suppose that you instrumented your offer logic to do this. Now, if an attacker found a reproducible way of making your offer fail, they could loop that attack for as long as you repost a reprovision for your offer. This could ultimately draining your native token balance!

When writing posthooks, we need to consider all possible outcomes. The first outcome we have handled above assumed that the offer was successful. However, it might also be that the offer failed when it was taken. In this setup, this may happen, for instance, because we opted for using a router that brings liquidity from deployer's account. Nothing prevents this account from being empty when the market order actually arrives.

Amplifier - Managing offer failure

function __posthookFallback__(MgvLib.SingleOrder calldata order, MgvLib.OrderResult calldata)
  internal
  override
  returns (bytes32)
{
  // if we reach this code, trade has failed for lack of base token
  (IERC20 alt_stable, uint tickSpacing, uint alt_offerId) = IERC20(order.olKey.inbound_tkn) == STABLE1
    ? (STABLE2, TICK_SPACING2, offerId2)
    : (STABLE1, TICK_SPACING1, offerId1);
  retractOffer({
    olKey: OLKey(order.olKey.outbound_tkn, address(alt_stable), tickSpacing),
    offerId: alt_offerId,
    deprovision: false
  });
  return "posthook/bothFailing";
}

the 's address, and

its .

The router_ argument can be either the address of a deployed , or the zero address cast to an AbstractRouter type, when you wish to build a Direct contract that will do its own liquidity routing. (In the latter case, for clarity, you may also use the public constant provided by MangroveOffer.)

We will allow users of OfferMaker to supply a , and use the following constructor for our contract:

We use 30K for default of our strat. This does not leave room for any advanced , so we'll stick here with a very simple one where liquidity is stored on this contract. See for more information.

Simple offer management

With this constructor in place we almost have a deployable maker contract. Direct already provides the implementation of a default as well as internal functions to post, update and retract offers posted by our contract.

However, Direct does not expose any function able to on Mangrove, since the function of Direct is internal. The requirement in our constructor to implement ILiquidityProvider imposes on us to have a public newOffer function. Using ILiquidityProvider ensures our contract is compatible with the , which expects the ILiquidityProvider ABI.

Our maker contract is now complete and ready to be and .

Advanced Direct offer: Liquidity Amplification with Amplifier

Of course, if we offer N tokens both on the (BASE, STABLE1) and the (BASE, STABLE2) , one of our offers will fail if both are taken.

let the second offer fail and compensate the taker with our offer's , or,

incorporate in our offer logic that we wish to the second offer when the first one is taken.

Let's follow the second design principle as it allows us to illustrate how to use the provided by Direct to update offer prices or to retract offers.

Constructor

In the constructor below, we also show how to instantiate and setup a simple in order to use the deployer's account as fund reserve.

Publishing amplified liquidity

We already know some of the parameters we need to implement posting new offers, since we gave them in the constructor: We know the and the tokens of both offers. Also, we do not want the to have to specify new offer's and so we just use default values.

If we specify a gasprice of zero when posting the offer, Mangrove will use . For gasreq, we can use the public getter offerGasreq(), which returns the default gas requirement for the contract plus the gas required for the .

This leaves us having to provide the amount that the offer should in BASE token, and the amount of STABLE1 and STABLE2, which the offer - wants1 and wants2. We also need to specify the TODO:%pivot ids|pivot-id% for insertion of the two offers (pivot1 and pivot2) in the relevant . As for OfferMaker, we only want the admin of the contract to able to post offers, so we use the modifier onlyAdmin again.

In the implementation of newAmplifiedOffers notice the calls to the offer data getter MGV.offers(address, address, uint): This returns a packed data structure offer whose fields f can be unpacked by doing offer.f() (see the documentation for the ).

If both our amplified offers were once live on Mangrove, but are no longer (either after a retract or because one of them was consumed by a taker), it is more gas efficient to to reinstate them on the , rather than creating new ones as we do in the above code.

Updating an under-collateralized offer on the fly

With newAmplifiedOffers implemented, we can now post new offers. We hope that one of these offers will be taken at some point. When this happens, as per the specification we decided upon , we wish to retract the other offer, which is now un(der)-collateralized, in order to save some . To do this we override the posthookSuccess .

The signature and first line of our custom looks like this:

Notice that we call super's implementation of the hook. This ultimately ends up attempting to repost the offer residual (cf. the documentation of and the reference for ). The return value captured in repost_status tells us whether the offer had a residual (in case of a ).

Direct offers that are partially filled are automatically reposted during posthook, adapting to remaining in order to maintain offer's original price. Direct's posthook returns the constants REPOST_SUCCESS in case the offer's residual was reposted, or COMPLETE_FILL if the offer was entirely consumed by taker (these constants are defined in MangroveOffer). If the offer fails to repost, the hook returns Mangrove's reason.

Implementing case 1: An offer was reposted with a residual

Notice the use of the hook in the code snippet above. For the offer currently being executed, it returns the at that offer when it is reposted. By default, this is calculated by subtracting what the taker took during from what the offer originally gave.

Also notice that we go through a slightly more complex calculation to compute the updated wants for the other offer: We cannot use to deduce the amount of tokens the other offer should , because we cannot assume both STABLE1 and STABLE2 have the same decimals. (For this example, we only assume that they have the same value with respect to BASE.) We could zero-pad or truncate, but it is more elegant to compute the new based on the new - we set the constraint that we wish to preserve the TODO:%entailed price|offer-entailed-price%.

Retracting the uncollateralized offer on the fly

During the execution of the it may occur that the taken offer does not repost itself on the . This may happen for the following reasons:

the offer is but its residual is below the offer list's

the offer no longer has enough . This last case may occur if one is reposting an offer that has failed (because a part of the was turned into a ), or because Mangrove's is now above the offer's gasprice. (This may happen, if Mangrove updated its after the offer was last posted.)

Implementing case 2: An offer was not reposted, and we need to retract the other offer

We continue our hook by handling case 2 from our .

There is an alternative to retracting both offers in case the taken offer failed to repost itself for lack of provision: We might replenish the maker contract's balance on Mangrove. However, we advise against refunding provisions automatically within the itself:

Managing offer failure

If this happens, this means that the offer that was unsuccessfully taken is no longer live on Mangrove and that some has been sent to the taker. However, in this case, we know that the other offer will also fail if taken. For this reason, in case if a trade fails, rather than waiting for the other offer to fail by itself, we can save some and override to retract the other offer:

maker contract
MangroveOffer
Direct
​
Direct
IOfferLogic
​
See entire file on GitHub
router_
reserveId
router
NO_ROUTER
router
See entire file on GitHub
gasreq
gasreq
offer logic
how to evaluate gasreq
​
offer logic
create new offers
_newOffer
Mangrove SDK
See entire file on GitHub
tested
deployed
​
offer lists
bounty
retract
hooks
​
router
See entire file on GitHub
​
inbound
outbound
offer owner
gasprice
gasreq
its own gas price
router
give
wants
offer lists
See entire file on GitHub
offer data structure
update the offers
offer list
​
above
provision
hook
hook
See entire file on GitHub
Post trade hooks for MangroveOffer
Customizing makerPosthook
maker partial fill
wants
gives
​
See entire file on GitHub
__residualGives__
give
makerExecute
__residualWants__
want
wants
gives
​
offer logic
offer list
partially filled
density
provision
provision
bounty
gasprice
own gasprice
​
breakdown above
See entire file on GitHub
offer logic
​
bounty
provision
posthookFallback
See entire file on GitHub