### HTTP GET Request Example for Querying Documentation Source: https://docs.mangrove.exchange/dev/protocol/technical-references/takers/delegation This example shows how to query the documentation dynamically by performing an HTTP GET request with an 'ask' query parameter. ```http GET https://docs.mangrove.exchange/dev/protocol/technical-references/takers/delegation.md?ask= ``` -------------------------------- ### Query Documentation Example Source: https://docs.mangrove.exchange/dev/protocol/technical-references/makers/maker-contract Demonstrates how to query the documentation dynamically using an HTTP GET request with the `ask` query parameter. This is useful for retrieving specific information or clarifications not explicitly present on the page. ```http GET https://docs.mangrove.exchange/dev/protocol/technical-references/makers/maker-contract.md?ask= ``` -------------------------------- ### Querying Documentation Example Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/abstract/hasindexedbidsandasks Demonstrates how to query documentation dynamically using an HTTP GET request with an 'ask' query parameter. This is useful for retrieving specific information or clarification. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/abstract/hasindexedbidsandasks.md?ask= ``` -------------------------------- ### Setup for Testing with Mock Tokens Source: https://docs.mangrove.exchange/mangrove-core/how-to-guides/howtotest Initializes mock ERC20 tokens and sets up markets for testing. This snippet demonstrates how to get token instances and prepare them for use in tests, including dealing initial amounts to a 'taker' address. ```solidity usdc = IERC20(fork.get("USDC")); setupMarket(dai, weth); setupMarket(usdc, weth); // setup separate taker and give some native token (for gas) + USDC and DAI taker = freshAddress("taker"); deal(taker, 10_000_000); deal($(usdc), taker, cash(usdc, 10_000)); deal($(dai), taker, cash(dai, 10_000)); // approve DAI and USDC on Mangrove for taker vm.startPrank(taker); dai.approve($(mgv), type(uint).max); usdc.approve($(mgv), type(uint).max); vm.stopPrank(); } ``` -------------------------------- ### Install Foundry Source: https://docs.mangrove.exchange/dev/strat-lib/getting-started/set-up-your-local-environment Installs the Foundry development framework for Ethereum. Remember to reopen your shell after execution. ```bash curl -L https://foundry.paradigm.xyz | bash # Reopen shell foundryup ``` -------------------------------- ### Querying Documentation with GET Request Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/interfaces/iforwarder Demonstrates how to query the documentation dynamically using an HTTP GET request with the 'ask' query parameter. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/interfaces/iforwarder.md?ask= ``` -------------------------------- ### Install Dependencies with Bun Source: https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli Install the project dependencies using the bun package manager. ```bash bun install ``` -------------------------------- ### Solidity Example for Offer Sniping Source: https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/taker-order Example of how to use the `snipes` function in Solidity to target specific offers. ```APIDOC ## Solidity Example ### Description Demonstrates the usage of the `snipes` function in Solidity. ### Code ```solidity import "src/IMangrove.sol"; import "src/MgvLib.sol"; // Context of the call address MGV; address outTkn; // address of offer's outbound token address inbTkn; // address of offer's inbound token uint offer1; // first offer one wishes to snipe uint offer2; // second offer one wishes to snipe // If Mangrove is not approved yet for inbound token transfer. IERC20(inbTkn).approve(MGV, type(uint).max); // Sniping the offers to check whether they fail (uint successes, uint takerGot, uint takerGave, uint bounty, uint fee) = Mangrove(MGV).snipes( outTkn, inbTkn, [ [offer1, 1 ether, 1 ether, 100000], // first snipe (price of 1 / 1 ) [offer2, 1.5 ether, 1 ether, 50000] // second snipe (price of 1.5 / 1) ], true // fillWants ); // We have: `successes < 2 <=> bounty > 0` ``` ``` -------------------------------- ### Install Node.js and Yarn 2 Source: https://docs.mangrove.exchange/dev/strat-lib/getting-started/set-up-your-local-environment Installs Node.js LTS and enables the Yarn 2 package manager using nvm. Remember to reopen your shell after execution. ```bash curl -o- https://raw.githubusercontent.com/nvm/nvm/v0.39.1/install.sh | bash # Reopen shell nvm install --lts # Enable the Yarn 2 package manager corepack enable ``` -------------------------------- ### Install Mangrove.js SDK Source: https://docs.mangrove.exchange/mangrove-js Install the Mangrove.js API using npm. This command is typically run in your project's sandbox folder. ```bash sandbox_folder$> npm install @mangrovedao/mangrove.js ``` -------------------------------- ### Querying Documentation API Source: https://docs.mangrove.exchange/mangrove-core/how-to-guides/cleaning-an-offer This example shows how to query the documentation API to get answers to specific questions. Replace '' with your natural language query. The response will include direct answers and relevant documentation excerpts. ```http GET https://docs.mangrove.exchange/mangrove-core/how-to-guides/cleaning-an-offer.md?ask= ``` -------------------------------- ### Install Mangrove Dependencies and Forge Source: https://docs.mangrove.exchange/dev/strat-lib/getting-started/set-up-your-local-environment Installs the Mangrove core and strategy library via npm, initializes a Foundry project, and sets up remappings for the strat library. ```bash # To create Solidity smart contracts # Install NPM package with Mangrove core and Strat library npm install --save @mangrovedao/mangrove-strats@next # Prepare Foundry's forge forge init --force # Set up remappings to use the strat library cd node_modules/@mangrovedao/mangrove-strats echo "@mgv/src/=node_modules/@mangrovedao/mangrove-core/src/ @mgv/src/=node_modules/@mangrovedao/mangrove-core/src/ @mgv/lib/=node_modules/@mangrovedao/mangrove-core/lib/ @mgv/test/=node_modules/@mangrovedao/mangrove-core/test/ @mgv/script/=node_modules/@mangrovedao/mangrove-core/script/ @mgv/forge-std/=node_modules/@mangrovedao/mangrove-core/lib/forge-std/src/ ds-test/=node_modules/@mangrovedao/mangrove-core/lib/forge-std/lib/ds-test/src @mgv-strats/src/=node_modules/@mangrovedao/mangrove-strats/src/ @mgv-strats/lib/=node_modules/@mangrovedao/mangrove-strats/lib/ @mgv-strats/test/=node_modules/@mangrovedao/mangrove-strats/test/ @mgv-strats/script/=node_modules/@mangrovedao/mangrove-strats/script/ " > remappings.txt ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.mangrove.exchange/strategies/kandel-aave/how-does-kandel-work/parameters.md Use this HTTP GET request to query the documentation dynamically. Include your question as the value for the 'ask' query parameter. ```http GET https://docs.mangrove.exchange/strategies/kandel-aave/how-does-kandel-work/parameters.md?ask= ``` -------------------------------- ### ethers.js Example for Offer Sniping Source: https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/taker-order Example of how to use the `snipes` function with ethers.js. ```APIDOC ## ethers.js Example ### Description Demonstrates the usage of the `snipes` function with ethers.js. ### Code ```javascript const { ethers } = require("ethers"); // Context // outTkn: address of outbound token ERC20 // inbTkn: address of inbound token ERC20 // ERC20_abi: ERC20 abi // MGV_address: address of Mangrove // MGV_abi: Mangrove contract's abi // signer: transaction signer // Loading ethers.js contracts const Mangrove = new ethers.Contract(MGV_address, MGV_abi, ethers.provider); const InboundTkn = new ethers.Contract(inbTkn, ERC20_abi, ethers.provider); const OutboundTkn = new ethers.Contract(outTkn, ERC20_abi, ethers.provider); // If Mangrove is not approved yet for inbound token transfer. await InboundTkn.connect(signer).approve(MGV_address, ethers.constant.MaxUint256); // Preparing snipes data const outDecimals = await OutboundTkn.decimals(); const inbDecimals = await InboundTkn.decimals(); // Note: The full ethers.js example is not provided in the source text, // but this setup demonstrates the initial steps for interacting with the snipes function. ``` ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/abstract/tradesbasequotepair To get additional information not directly on the page, perform an HTTP GET request with the 'ask' query parameter. The response will include an answer and relevant excerpts. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/abstract/tradesbasequotepair.md?ask= ``` -------------------------------- ### Query Documentation with 'ask' Parameter Source: https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/setting-the-fee-data Use this HTTP GET request to dynamically query the documentation. Append the 'ask' query parameter with your specific question to get direct answers and relevant excerpts. ```bash GET https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/setting-the-fee-data.md?ask= ``` -------------------------------- ### Query Documentation with GET Request Source: https://docs.mangrove.exchange/dev/protocol/technical-references/governance-parameters/local-variables Perform an HTTP GET request to the current page URL with the 'ask' query parameter to query the documentation dynamically. The question should be specific and self-contained. ```http GET https://docs.mangrove.exchange/dev/protocol/technical-references/governance-parameters/local-variables.md?ask= ``` -------------------------------- ### Amplifier Contract Setup Source: https://docs.mangrove.exchange/dev/strat-lib/guides/testing-a-maker-contract Sets up the Amplifier contract for testing, including defining tokens, markets, and taker addresses. It utilizes Foundry cheatcodes for setup and Mangrove testing library helpers. ```solidity contract AmplifierTest is StratTest { IERC20 weth; IERC20 dai; IERC20 usdc; PolygonFork fork; address payable taker; Amplifier strat; OLKey olKeyWethDai; uint constant GASREQ = 200_000; receive() external payable virtual {} function setUp() public override { // use the pinned Polygon fork fork = new PinnedPolygonFork(39880000); // use polygon fork to use dai, usdc and weth addresses fork.setUp(); // use convenience helpers to setup Mangrove mgv = setupMangrove(); reader = new MgvReader($(mgv)); // setup tokens, markets and approve them dai = IERC20(fork.get("DAI.e")); weth = IERC20(fork.get("WETH.e")); usdc = IERC20(fork.get("USDC.e")); olKeyWethDai = OLKey($(weth), $(dai), options.defaultTickSpacing); olKey = OLKey($(usdc), $(weth), options.defaultTickSpacing); lo = olKey.flipped(); setupMarket(olKeyWethDai); setupMarket(olKey); // setup separate taker and give some native token (for gas) + USDC and DAI taker = freshAddress("taker"); deal(taker, 10_000_000); deal($(usdc), taker, cash(usdc, 10_000)); deal($(dai), taker, cash(dai, 10_000)); // approve DAI and USDC on Mangrove for taker vm.startPrank(taker); dai.approve($(mgv), type(uint).max); usdc.approve($(mgv), type(uint).max); vm.stopPrank(); } ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/vendor/aave/v3/contracts Perform an HTTP GET request to the documentation URL with the 'ask' query parameter to ask a question. The question should be specific and self-contained. The response includes a direct answer and relevant excerpts. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/vendor/aave/v3/contracts.md?ask= ``` -------------------------------- ### Example Maker Contract: MyOffer Source: https://docs.mangrove.exchange/dev/protocol/technical-references/makers/maker-contract An example Solidity contract demonstrating the `makerExecute` function. It verifies if the contract has sufficient outbound tokens to satisfy a market order and transfers inbound tokens to a reserve. This snippet requires importing necessary interfaces from `@mgv/src/core/MgvLib.sol`. ```solidity import {IERC20, IMaker, SingleOrder} from "@mgv/src/core/MgvLib.sol"; contract MyOffer is IMaker { // IMangrove mgv = IMangrove(payable(
)); // Mangrove contract IMangrove mgv = IMangrove(payable(mgv)); address reserve; // token reserve for inbound tokens // an example of offer execution that simply verifies that `this` contract has enough outbound tokens to satisfy the market order. function makerExecute(MgvLib.SingleOrder calldata order) external returns (bytes32 makerData) { // revert below (in case of insufficient funds) to signal mangrove we renege on trade // reverting as soon as early to minimize bounty require( IERC20(order.offer.gives()).balanceOf(address(this)) >= order.offer.wants(), "MyOffer/NotEnoughFunds"); // do not perform any state changing call if caller is not Mangrove! require(msg.sender == mgv, "MyOffer/OnlyMangroveCanCallMe"); // `order.gives` has been transfered by Mangrove to `this` balance // sending incoming tokens to reserve IERC20(order.offer.wants()).transfer(reserve, order.offer.gives()); // this string will be passed to `makerPosthook` return "MyOffer/tradeSuccess"; } } ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/keeper-bots/keeper-bots Perform an HTTP GET request to query the documentation dynamically. Use the 'ask' query parameter with a specific question in natural language to get direct answers and relevant excerpts. ```http GET https://docs.mangrove.exchange/dev/keeper-bots/keeper-bots.md?ask= ``` -------------------------------- ### Create Tutorial Folder and Initialize npm Source: https://docs.mangrove.exchange/dev/strat-lib/getting-started/set-up-your-local-environment Creates a new directory for tutorials, navigates into it, and initializes a new npm project. ```bash # Create a folder for the tutorial and enter it mkdir tutorial cd tutorial npm init -y ``` -------------------------------- ### Get Offer List Endpoints Source: https://docs.mangrove.exchange/dev/protocol/technical-references/periphery-contracts/mgvreader Calculates the start ID and length of live offers in an offer list, optionally starting from a given ID and limiting the count. ```solidity function offerListEndPoints(OLKey memory olKey, uint fromId, uint maxOffers) external view returns (uint startId, uint length); ``` -------------------------------- ### Example .env File Configuration Source: https://docs.mangrove.exchange/dev/strat-lib/getting-started/set-up-your-local-environment Configure environment variables for local development. This includes private keys, addresses, and RPC URLs for both main and local chains. ```bash export PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 # The first anvil private key export ADMIN_ADDRESS=0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 # The matching public key, to the first anvil private key export RPC_URL=https://polygon-mumbai.blockpi.network/v1/rpc/public # Public RPC provided by Block Pi export LOCAL_URL=http://127.0.0.1:8545 # Url for the local chan that anvil starts ``` -------------------------------- ### Example MakerContract Offer Logic Source: https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/reactive-offer/maker-contract An example implementation of the makerExecute function in Solidity. This contract verifies sufficient outbound tokens and transfers inbound tokens to a reserve. It returns a success message or reverts if conditions are not met. ```solidity import {IERC20, IMaker, SingleOrder} "src/MgvLib.sol"; contract MyOffer is IMaker { address MGV; // address of Mangrove address reserve; // token reserve for inbound tokens // an example of offer execution that simply verifies that `this` contract has enough outbound tokens to satisfy the taker Order. function makerExecute(SingleOrder calldata order) external returns (bytes32 makerData){ // revert below (in case of insufficient funds) to signal mangrove we renege on trade // reverting as soon as early to minimize bounty require( IERC20(order.outbound_tkn).balanceOf(address(this)) >= order.wants), "MyOffer/NotEnoughFunds"; ); // do not perform any state changing call if caller is not Mangrove! require(msg.sender == MGV, "MyOffer/OnlyMangroveCanCallMe"); // `order.gives` has been transfered by Mangrove to `this` balance // sending incoming tokens to reserve IERC20(order.inbound_tkn).transfer(reserve, order.gives); // this string will be passed to `makerPosthook` return "MyOffer/tradeSuccess"; } } ``` -------------------------------- ### Initialize Project with Bun Source: https://docs.mangrove.exchange/dev/interacting-with-js/getting-started Initializes a new project using Bun. This is the first step before adding dependencies. ```bash bun init ``` -------------------------------- ### Get Slice of Open Markets and Configurations Source: https://docs.mangrove.exchange/dev/protocol/technical-references/periphery-contracts/mgvreader Retrieves a subset of open markets and their configurations starting from a specified index. The `from` parameter indicates the starting index in MgvReader's internal market array. ```solidity function openMarkets(uint from, uint maxLen) external view returns (Market[] memory markets, MarketConfig[] memory configs) ``` -------------------------------- ### PopulateStart Event Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/abstract/directwithbidsandasksdistribution Logs the start of a call to populate offers. Indexers can use this to track offer population contexts. ```solidity event PopulateStart() ``` -------------------------------- ### Querying Documentation via HTTP GET Source: https://docs.mangrove.exchange/dev/strat-lib/background/building-blocks/direct To get additional information not directly available on a page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://docs.mangrove.exchange/dev/strat-lib/background/building-blocks/direct.md?ask= ``` -------------------------------- ### Example Market Price and Ratio Calculations Source: https://docs.mangrove.exchange/dev/protocol/technical-references/ticks-ratios-and-prices Demonstrates how to calculate ask and bid prices and raw ratios for different markets, considering the specific token decimals involved. ```text Market | Token Decimals | Ask (quote/base) | Ask ratio (raw) | Bid (base/quote) | Bid ratio (raw) DAI/USDC | DAI = 18
USDC = 6 | $1$ | $1 * 10^{-12} = 10^{6}/10^{18}$ | $1$ | $1 * 10^{12} = 10^{18}/10^{6}$ WETH/DAI | WETH = 18
DAI = 18 | $2{,224}$ | $2{,224} * 10^{0} = 2{,224} * 10^{18}/10^{18}$ | $0.0004410$ | $0.0004410 * 10^{0} = 0.0004410 * 10^{18}/10^{18}$ ``` -------------------------------- ### Viem Client Setup with Mangrove Actions Source: https://docs.mangrove.exchange/dev/interacting-with-js/getting-started Sets up a viem wallet client, extending it with Mangrove actions. Requires PRIVATE_KEY and optionally RPC_URL environment variables. ```typescript import { mangroveActions } from "@mangrovedao/mgv"; import { createWalletClient, http, publicActions, type Hex } from "viem"; import { privateKeyToAccount } from "viem/accounts"; import { base } from "viem/chains"; import { mangroveConfig } from "./config"; export const client = createWalletClient({ chain: base, transport: http(process.env.RPC_URL), account: privateKeyToAccount(process.env.PRIVATE_KEY as Hex), }) .extend(publicActions) .extend(mangroveActions(mangroveConfig)); ``` -------------------------------- ### Obtaining a LiquidityProvider Instance (Direct) Source: https://docs.mangrove.exchange/mangrove-js/technical-references/api-classes-overview Demonstrates how to get a LiquidityProvider instance for direct offer posting on a specific market. ```APIDOC ## Obtain LiquidityProvider (Direct) ### Description Instantiates a `LiquidityProvider` object for direct offer posting on a given Mangrove market. ### Method `mgv.liquidityProvider(mgvMarket)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const mgvDirectLP = await mgv.liquidityProvider(mgvMarket); ``` ### Response #### Success Response - **mgvDirectLP** (`LiquidityProvider` instance) - An instance of the LiquidityProvider class. ``` -------------------------------- ### Querying Documentation via HTTP GET Source: https://docs.mangrove.exchange/mangrove-js/guides/sell-and-buy-orders To get information not explicitly on the page, make an HTTP GET request to the page URL with an 'ask' query parameter. The response will include a direct answer and relevant documentation excerpts. ```http GET https://docs.mangrove.exchange/mangrove-js/guides/sell-and-buy-orders.md?ask= ``` -------------------------------- ### Post New Offer with Solidity Source: https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/reactive-offer Example of posting a new offer using Solidity, including token approvals, configuration retrieval, and the `newOffer` call with provision. ```solidity import "src/IMangrove.sol"; import {IERC20, MgvStructs} "src/MgvLib.sol"; // context of the call address MGV; address outTkn; // address offer's outbound token address inbTkn; // address of offer's inbound token address admin; // admin address of this contract uint pivotId; // offer id whose price is the closest to this new offer (observed offchain) // Approve Mangrove for outbound token transfer if not done already IERC20(outTkn).approve(MGV, type(uint).max); uint outDecimals = IERC20(outTkn).decimals(); uint inbDecimals = IERC20(inbTkn).decimals(); // importing global and local (pertaining to the (outTkn, inTkn) offer list) parameters. (MgvStructs.GlobalPacked global, MgvStructs.LocalPacked local) = IMangrove(MGV) .config(outTkn, inTkn); uint gasprice = global.gasprice() * 10**9; // Mangrove's gasprice is in gwei units uint gasbase = local.offer_gasbase() ; // gas necessary to process a market order uint gasreq = 500_000; // assuming this logic requires 30K units of gas to execute uint provision = (gasreq + gasbase) * gasprice; // minimal provision in wei // calling mangrove with `pivotId` for initial positioning. // sending `provision` amount of native tokens to cover for the bounty of the offer IMangrove(MGV).newOffer{value: provision}( outTkn, // reposting on the same market inbTkn, 5.0*10**inbDecimals, // maker wants 5 inbound tokens 7.0*10**outDecimals, // maker gives 7 outbound tokens 30_000, // maker requires 500_000 gas units to comply 0, // use mangrove's gasprice oracle pivotId // heuristic: tries to insert this offer after pivotId ); ``` -------------------------------- ### Solidity Example for Updating an Offer Source: https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/reactive-offer A Solidity code snippet demonstrating how to fetch offer details and use the `updateOffer` function to modify an existing offer's parameters, such as decreasing the 'gives' amount. ```solidity import "src/IMangrove.sol"; import {MgvStructs} form "src/MgvLib.sol"; // context of the call // MGV: address of Mangrove's deployment // outTkn, inbTkn: addresses of the offer list in which the updated offer is // offerId: offer identifier in the (outTkn, inbTkn) offer list MgvStruct.OfferPacked memory offer32 = IMangrove(MGV).offers(outTkn, inbTkn, offerId); MgvStruct.OfferPacked memory offerDetail32 = IMangrove(MGV).offerDetails(outTkn, inbTkn, offerId); IMangrove(MGV).updateOffer( outTkn, inbTkn, offer32.wants(), // do not update what the offer wants offer32.gives() * 0.9, // decrease what offer gives by 10% offerDetail32.gasreq(), // keep offer's current gasreq offerDetail32.gasprice(), // keep offer's current gasprice offer32.next(), // heuristic: use next offer as pivot since offerId might be off the book offerId // id of the offer to be updated ); ``` -------------------------------- ### Start Anvil Node for Local Fork Source: https://docs.mangrove.exchange/dev/strat-lib/guides/deploying-your-contract Start an Anvil node forking the Mumbai network. Ensure your MUMBAI_NODE_URL is sourced from your .env file. ```bash anvil --port 8545 --fork-url $MUMBAI_NODE_URL --silent ``` -------------------------------- ### Post Direct Offer with Mangrove.js Source: https://docs.mangrove.exchange/mangrove-js/getting-started/basic-offer This script shows how to post a direct offer using Mangrove.js. It covers loading environment variables, connecting to Mangrove, setting up a market, approving token transfers, computing the offer provision, and posting the new ask. Ensure you have a .env file with NODE_URL and PRIVATE_KEY. ```javascript // Load the NODE_URL and PRIVATE_KEY from .env file into process.env // This script assumes NODE_URL points to your access point and PRIVATE_KEY contains private key from which one wishes to post offers var parsed = require("dotenv").config(); // Import the Mangrove API const { Mangrove, ethers } = require("@mangrovedao/mangrove.js"); // Create a wallet with a provider to interact with the chain. const provider = new ethers.providers.WebSocketProvider( process.env.NODE_URL ); const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider); // Connect the API to Mangrove const mgv = await Mangrove.connect({ signer: wallet }); // Connect mgv to a DAI, USDC market const market = await mgv.market({ base: "DAI", quote: "USDC" }); // Check it's live, should display the best bids and asks of the DAI, USDC market market.consoleAsks(); market.consoleBids(); // Create a simple liquidity provider on `market`, using `wallet` as a source of liquidity const directLP = await mgv.liquidityProvider(market); // Liquidity provider needs to approve Mangrove for transfer of base token (DAI) which // will be transferred from the wallet to Mangrove and then to the taker when the offer is taken. const tx = await directLP.approveAsks(); await tx.wait(); // Query mangrove to know the bounty for posting a new Ask on `market` const provision = await directLP.computeAskProvision(); // Post a new ask (offering 105 DAI for 104 USDC) at a price of 150/104~=1.0096 // Consider looking at the consoleAsks above and increase gives such that the offer becomes visible in this list const { id: offerId } = await directLP.newAsk({ wants: 105, gives: 104, fund: provision }); // Check the order was posted (or look at https://testnet.mangrove.exchange. market.consoleAsks(); ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dapp-guide/trade/how-to-make-an-order.md Use this GET request to ask questions about the documentation. The response includes direct answers and relevant excerpts. ```http GET https://docs.mangrove.exchange/dapp-guide/trade/how-to-make-an-order.md?ask= ``` -------------------------------- ### Querying Documentation Source: https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/creating-a-vault To get additional information not directly on the page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and in natural language. ```bash GET https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/creating-a-vault.md?ask= ``` -------------------------------- ### constructor Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/abstract/direct Initializes the Direct offer maker contract. It sets the Mangrove instance, the router for liquidity management, and the reserve ID. ```APIDOC ## constructor ### Description Initializes the Direct offer maker contract. It sets the Mangrove instance, the router for liquidity management, and the reserve ID. *`reserveId == address(0)` will set `RESERVE_ID` to `address(this)`.* ### Parameters #### Parameters - **mgv** (contract IMangrove) - The Mangrove deployment that is allowed to call `this` for trade execution and posthook. - **router_** (contract AbstractRouter) - The router that this contract will use to pull/push liquidity from the offer maker's reserve. This can be `NO_ROUTER`. - **reserveId** (address) - Identifier of this contract's reserve when using a router. ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/vendor/aave/v3/periphery/contracts To get information not directly on the page, send an HTTP GET request to the page URL with an 'ask' query parameter containing your question. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/vendor/aave/v3/periphery/contracts.md?ask= ``` -------------------------------- ### Query Documentation with HTTP GET Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats Use this method to ask specific questions about the documentation. The response includes a direct answer, relevant excerpts, and sources. ```bash GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats.md?ask= ``` -------------------------------- ### Query Documentation API Source: https://docs.mangrove.exchange/mgv-incentives/vault-lp-programs/current-programs To get information not directly on a page, make an HTTP GET request to the page URL with an 'ask' query parameter. The question should be in natural language. ```bash GET https://docs.mangrove.exchange/mgv-incentives/vault-lp-programs/current-programs.md?ask= ``` -------------------------------- ### Obtaining a LiquidityProvider Instance (Logic-based) Source: https://docs.mangrove.exchange/mangrove-js/technical-references/api-classes-overview Shows how to obtain a LiquidityProvider instance when using an offer logic for posting bids and asks. ```APIDOC ## Obtain LiquidityProvider (Logic) ### Description Instantiates a `LiquidityProvider` object for posting bids and asks via an offer logic on a given Mangrove market. ### Method `mgvLogic.liquidityProvider(mgvMarket)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const mgvOnchainLP = await mgvLogic.liquidityProvider(mgvMarket); ``` ### Response #### Success Response - **mgvOnchainLP** (`LiquidityProvider` instance) - An instance of the LiquidityProvider class. ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/governance/general-governance/governance-process/initial-discussions To get information not directly on a page, make an HTTP GET request to the page URL with an 'ask' query parameter. The question should be in natural language. ```http GET https://docs.mangrove.exchange/governance/general-governance/governance-process/initial-discussions.md?ask= ``` -------------------------------- ### initialize Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/aavekandel Sets the AaveRouter as the active router for base and quote tokens and specifies the gas requirement for offers. ```APIDOC ## initialize ### Description Sets the AaveRouter as the active router for base and quote tokens and specifies the gas requirement for offers. ### Parameters #### Parameters - **router_** (contract AavePooledRouter) - the Aave router to use. - **gasreq** (uint256) - the gas required to execute an offer of this Kandel strat ``` -------------------------------- ### Query Documentation Page Source: https://docs.mangrove.exchange/developers-doc/page-2 Send an HTTP GET request to a documentation page URL with the 'ask' query parameter to get specific information. The question should be in natural language. ```http GET https://docs.mangrove.exchange/developers-doc/page-2.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/abstract Perform an HTTP GET request to query the documentation. Include your question as the 'ask' query parameter. The response will contain an answer and relevant excerpts. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/abstract.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.mangrove.exchange/dev/vaults/custom-interactions To get information not explicitly on a page, make an HTTP GET request to the page URL with the 'ask' query parameter. The question should be in natural language. ```http GET https://docs.mangrove.exchange/dev/vaults/custom-interactions.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/protocol/technical-references/governance-parameters To get specific information not found on the page, make an HTTP GET request to the page URL with an 'ask' query parameter containing your question. ```http GET https://docs.mangrove.exchange/dev/protocol/technical-references/governance-parameters.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/rebalancing Use this method to ask questions about the documentation. The response includes direct answers and relevant excerpts. ```bash GET https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/rebalancing.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/strategies/kandel-aave/how-does-kandel-work/step-by-step-visual-explanation.md To get additional information not directly available on a page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.mangrove.exchange/strategies/kandel-aave/how-does-kandel-work/step-by-step-visual-explanation.md?ask= ``` -------------------------------- ### Querying Documentation with Agent Instructions Source: https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/market Use this method to dynamically query the documentation for specific information. The response includes a direct answer, relevant excerpts, and sources. ```http GET https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/market.md?ask= ``` -------------------------------- ### Query Documentation API Source: https://docs.mangrove.exchange/mangrove-core/technical-references/contract-addresses To get more information not present on the page, make an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.mangrove.exchange/mangrove-core/technical-references/contract-addresses.md?ask= ``` -------------------------------- ### Query Mangrove Documentation Source: https://docs.mangrove.exchange/mangrove-core/explanations To get additional information not directly present on a page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.mangrove.exchange/mangrove-core/explanations.md?ask= ``` -------------------------------- ### Query Documentation Source: https://docs.mangrove.exchange/dapp-guide/trade/minimum-volume.md Perform an HTTP GET request to query the documentation dynamically. Append the 'ask' query parameter with your specific question. ```http GET https://docs.mangrove.exchange/dapp-guide/trade/minimum-volume.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/protocol/technical-references To get specific information not directly on a page, make an HTTP GET request to the page URL with an 'ask' query parameter. The question should be clear and self-contained. ```http GET https://docs.mangrove.exchange/dev/protocol/technical-references.md?ask= ``` -------------------------------- ### Query Documentation with 'ask' Parameter Source: https://docs.mangrove.exchange/keeper-bots/how-to-guides Use this GET request to query the documentation dynamically. Append the 'ask' query parameter with your question to the page URL. The response includes a direct answer and relevant excerpts. ```http GET https://docs.mangrove.exchange/keeper-bots/how-to-guides.md?ask= ``` -------------------------------- ### Creating Offers with Mangrove Protocol Source: https://docs.mangrove.exchange/dev/protocol/technical-references/makers Demonstrates how to create new offers in the Mangrove order book using both tick and volume specifications. Ensure the Mangrove contract address and OLKey parameters are correctly set. ```solidity import {IMangrove} from "@mgv/src/IMangrove.sol"; import "@mgv/src/core/MgvLib.sol"; // context of the call // IMangrove mgv = IMangrove(payable(
)); // Mangrove contract IMangrove mgv = IMangrove(payable(mgv)); // OLKey olKey = OLKey(
,
, ); // struct containing outbound_tkn, inbound_tkn and tickSpacing OLKey memory olKey = OLKey(address(base), address(quote), 1); // Tick tick = TickLib.tickFromRatio(mantissa,exponent); // ratios are represented as a (mantissa,exponent) pair which represents the number `mantissa * 2**-exponent` // calculates the tick from a desired 1.25 ratio (1.25 = 20 * 2^(-4)) Tick tick = TickLib.tickFromRatio(20, 4); // creates an offer at tick mgv.newOfferByTick(olKey, tick, 1 ether, 10_000, 0); // creates an offer at ⌈wants/tick⌉ mgv.newOfferByVolume(olKey, 1 ether, 1 ether, 10_000, 0); ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/keeper-bots/backgroud/the-role-of-cleaning-bots-in-mangrove To get information not directly on a page, make an HTTP GET request to the page URL with an 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.mangrove.exchange/dev/keeper-bots/backgroud/the-role-of-cleaning-bots-in-mangrove.md?ask= ``` -------------------------------- ### constructor Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/mangroveorder Initializes the MangroveOrder contract, linking it to a specific Mangrove contract instance and setting the deployer address. ```APIDOC ## constructor ### Description Initializes the MangroveOrder contract, linking it to a specific Mangrove contract instance and setting the deployer address. ### Parameters #### Parameters - **mgv** (contract IMangrove) - The mangrove contract on which this logic will run taker and maker orders. - **deployer** (address) - The address of the admin of `this` at the end of deployment ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/mgv-incentives/ms1-program-closed/trading-points To get answers to questions not explicitly covered on a page, make an HTTP GET request to the page URL with an 'ask' query parameter. The question should be in natural language. ```http GET https://docs.mangrove.exchange/mgv-incentives/ms1-program-closed/trading-points.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.mangrove.exchange/mangrove-core/explanations/offer-maker To get additional information not directly on the page, make an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.mangrove.exchange/mangrove-core/explanations/offer-maker.md?ask= ``` -------------------------------- ### Query Documentation Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/abstract/directwithbidsandasksdistribution Perform an HTTP GET request on the current page URL with the `ask` query parameter to dynamically query the documentation. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/offer_maker/market_making/kandel/abstract/directwithbidsandasksdistribution.md?ask= ``` -------------------------------- ### Query Documentation with 'ask' Parameter Source: https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/adding-or-removing-liquidity To get additional information not directly present on a page, perform an HTTP GET request with the 'ask' query parameter. The question should be specific and in natural language. ```bash GET https://docs.mangrove.exchange/dev/vaults/managing-a-vault-cli/adding-or-removing-liquidity.md?ask= ``` -------------------------------- ### Node.js Connection and Market Query Source: https://docs.mangrove.exchange/mangrove-js Connect to Mangrove using Node.js with a provided wallet and provider. This example demonstrates how to access the WETH/DAI market and print available bids. ```javascript const { Mangrove } = require("@mangrovedao/mangrove.js"); const { ethers } = require("ethers"); let provider = new ethers.providers.WebSocketProvider( "https://polygon-mumbai.g.alchemy.com/v2/" ); let myWallet = new ethers.Wallet( "", provider ); let mgvAPI = await Mangrove.connect({ signer: myWallet }); let market = await mgvAPI.market({base:"WETH", quote:"DAI"}); console.log("pretty prints available bids from the WETH,DAI market on Mangove"); // pretty prints available bids from the WETH,DAI market on Mangove await market.consoleBids(); ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/vendor/aave/v3/contracts/protocol To get specific information not directly on the page, make an HTTP GET request to the page URL with an 'ask' query parameter. The question should be clear and in natural language. ```http GET https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/vendor/aave/v3/contracts/protocol.md?ask= ``` -------------------------------- ### Accessing Mangrove Configuration Information Source: https://docs.mangrove.exchange/mangrove-core/technical-references/governance-parameters/mangrove-configuration Demonstrates how to retrieve Mangrove's global and local configuration parameters in both unpacked and packed formats using Solidity. Use unpacked for off-chain static calls and packed for gas-efficient on-chain interactions. ```Solidity import "src/IMangrove.sol"; // context of the call address MGV; address outTkn; address inbTkn; // getting Mangrove's global configuration parameters and those that pertain to the `(outTkn, inTkn)` offer list // in an ABI compatible format (gas costly, use for offchain static calls) (MgvStructs.GlobalUnpacked global, MgvStructs.LocalUnpacked local) = IMangrove(MGV) .configInfo(outTkn, inbTkn); // getting packed config data (gas efficient) (MgvStructs.GlobalPacked global32, MgvStructs.LocalPacked local32) = IMangrove(MGV) .config(outTkn, inbTkn); // for all fields f of `GlobalUnpacked global` // one may unpack a specific element of `GlobalPacked global32` using the following scheme: global.f == global32.f() // for all fields f of `LocalUnpacked local` // a similar scheme applies to `LocalPacked local32`: local.f == local32.f() ``` -------------------------------- ### Querying Documentation with `ask` Parameter Source: https://docs.mangrove.exchange/dev/protocol/technical-references/overview To get additional information not directly present on a page, perform an HTTP GET request with the `ask` query parameter. The question should be specific and in natural language. ```HTTP GET https://docs.mangrove.exchange/dev/protocol/technical-references/overview.md?ask= ``` -------------------------------- ### Import SimpleRouter Source: https://docs.mangrove.exchange/dev/strat-lib/guides/unlocking-liquidity Add this import at the top of your Solidity file to use the SimpleRouter for managing liquidity. ```solidity import {SimpleRouter} from "@mgv-strats/src/strategies/routers/SimpleRouter.sol"; ``` -------------------------------- ### Solidity Example: myRetractOffer Function Source: https://docs.mangrove.exchange/mangrove-core/technical-references/taking-and-making-offers/reactive-offer An example Solidity function `myRetractOffer` that retracts an offer from the Mangrove order book. It includes checks for the caller and calls the `retractOffer` function on the Mangrove contract. ```solidity import "./Mangrove.sol"; // context of the call address MGV; address outTkn; // address of market's base token address inbTkn; // address of market's quote token address admin; // admin address of this contract ... ... // external function to update an offer // assuming this contract has enough provision on Mangrove to repost the offer if need be function myRetractOffer(uint offerId) external { require(msg.sender == admin, "Invalid caller"); // calling mangrove with offerId as pivot (assuming price update will not change much the position of the offer) Mangrove(MGV).retractOffer( outTkn, // reposting on the same market inbTkn, offerId, // id of the offer to be updated false // do not deprovision offer, saves gas if one wishes to repost the offer later ); } ... ... ``` -------------------------------- ### Add Viem and Mangrove SDK Dependencies Source: https://docs.mangrove.exchange/dev/interacting-with-js/getting-started Adds Viem and the @mangrovedao/mgv SDK as project dependencies using Bun. ```bash bun add viem @mangrovedao/mgv ``` -------------------------------- ### Querying Documentation with 'ask' Parameter Source: https://docs.mangrove.exchange/dev/protocol/background/reneging-on-offers To get additional information not directly present on a page, you can query the documentation dynamically. Perform an HTTP GET request on the page URL with the 'ask' query parameter. ```http GET https://docs.mangrove.exchange/dev/protocol/background/reneging-on-offers.md?ask= ``` -------------------------------- ### Log Order Start Data Source: https://docs.mangrove.exchange/dev/strat-lib/technical-references/api-preferences/strats/src/strategies/mangroveorder Logs the 'MangroveOrderStart' event. This internal function is optimized to avoid loading excessive variables onto the stack. ```solidity function logOrderData(struct IOrderLogic.TakerOrder tko) internal ``` -------------------------------- ### Retract Offer Example Source: https://docs.mangrove.exchange/dev/protocol/technical-references/makers Demonstrates how to retract an offer from the order book using the `retractOffer` function. This example shows retracting an offer without deprovisioning its funds, which is gas-efficient if the offer is to be reposted later. ```solidity import {IMangrove} from "@mgv/src/IMangrove.sol"; // continuing from the previous example for the creation of new offers // context of the call: // mgv: address of Mangrove's deployment typed as IMangrove // olKey struct containing outbound_tkn, inbound_tkn and tickSpacing // ofrId_1: offer identifier of the offer created in the examples for new offer creation // retracting offer with ID = ofrId_1 mgv.retractOffer( olKey, ofrId_1, // id of the offer to be retracted false // no deprovision of the offer, saves gas if one wishes to repost the offer later ); ``` -------------------------------- ### Querying Documentation with GitBook Agent Source: https://docs.mangrove.exchange/dev/protocol/technical-references/makers To ask questions about the documentation, perform an HTTP GET request to the current page URL with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.mangrove.exchange/dev/protocol/technical-references/makers.md?ask= ``` -------------------------------- ### Query Documentation with 'ask' Parameter Source: https://docs.mangrove.exchange/keeper-bots/explanations Use this method to ask questions about the documentation. The response includes direct answers and relevant excerpts. ```http GET https://docs.mangrove.exchange/keeper-bots/explanations.md?ask= ```