Sending a Quote

Sending a quote requires us to fetch the various collateral requirements necessary to open a position from the hedger.

async function executeSendQuoteMarket(subAccount, positionType, quantity, slippage) {
  const { markets } = await fetchMarketSymbolId(config.HEDGER_URL, userConfig.SYMBOL);
  const lockedParams = await fetchLockedParams(markets[0].name, userConfig.LEVERAGE);

Let's first look at how we can fetch the markets from the hedger, which contains the autoSlippage for a specific pair.

Fetching the Market by SymbolId

The fetchMarketSymbolId() function is designed to asynchronously fetch market data from specified URLs by the Symbol ID. Here we're simply querying the hedger for symbols, then filtering them by the provided symbol. At the end we return the market object. The 'error_codes' API endpoint helps us understand the meaning of error codes.

async function fetchMarketSymbolId(url, symbol) {
  if (!url) {
    throw new Error("hedgerUrl is empty");
  }
  const marketsUrl = new URL('contract-symbols', url).href;
  const errorMessagesUrl = new URL('error_codes', url).href;

  try {
    const [marketsResponse, errorMessagesResponse] = await Promise.all([
      axios.get(marketsUrl),
      axios.get(errorMessagesUrl),
    ]);
      const filteredMarkets = marketsResponse.data.symbols
      .filter(market => market.symbol === symbol)
      .map(market => ({
          id: market.symbol_id,
          name: market.name,
          symbol: market.symbol,
          asset: market.asset,
          pricePrecision: market.price_precision,
          quantityPrecision: market.quantity_precision,
          isValid: market.is_valid,
          minAcceptableQuoteValue: market.min_acceptable_quote_value,
          minAcceptablePortionLF: market.min_acceptable_portion_lf,
          tradingFee: market.trading_fee,
          maxLeverage: market.max_leverage,
          maxNotionalValue: market.max_notional_value,
          maxFundingRate: market.max_funding_rate,
          rfqAllowed: market.rfq_allowed,
          hedgerFeeOpen: market.hedger_fee_open,
          hedgerFeeClose: market.hedger_fee_close,
          autoSlippage: (60 / market.max_leverage / 100) + 1,
      }));
    const errorMessages = errorMessagesResponse.data;
    return { markets: filteredMarkets, errorMessages };
  } catch (error) {
    console.error("Error fetching market symbols:", error);
  }
}

Parameters

  • url (String): The base URL from which the contract-symbols and error_codes endpoints can be constructed.

  • symbol (String): The market symbol for which detailed information is requested.

Returns:

  • filteredMarkets (Object): The information related to the symbol.

  • errorMessages(String): Any error messages associated with the hedger query

For more information on the returned data, consult the documentation for this API query.

Fetching the Locked Parameters

The fetchLockedParams() function asynchronously retrieves the locked values required to enter a position for a trading pair. This is the cva, the lf, and the mm. These variables are percentages of the notional value and will fluctuate depending on the leverage and the pair.

async function fetchLockedParams(pair, leverage) {
  const url = `${config.HEDGER_URL}get_locked_params/${pair}?leverage=${leverage}`;

  try {
    const response = await axios.get(url);
    const data = response.data;

    const output = {
      cva: data.cva,
      partyAmm: data.partyAmm,
      lf: data.lf,
      leverage: data.leverage,
      partyBmm: data.partyBmm
    };

    return output;
  } catch (error) {
    console.error('Error fetching data:', error);
  }

}

Parameters:

  • pair (String): The currency pair for which to fetch locked parameters (e.g., "BTCUSD").

  • leverage (Number): The leverage level for which the parameters are to be fetched.

Returns:

An object containing the following keys with their respective values from the fetched data:

  • cva (Number): The Credit valuation adjustment. This is

  • partyAmm (Number): PartyA's maintenance margin.

  • lf (Number): The liquidation fee awarded to liquidators.

  • leverage (Number): The leverage.

  • partyBmm (Number): PartyA's maintenance margin.

Now that we've declared these required functions, we can move onto defining the sendQuote() function. For this example we'll be sending a MARKET order.

Executing a MARKET Order

First we need to determine the requestedPrice of the asset. This is the market price from the Muon Signature +- the slippage (either from the hedger or determined by the user).

async function executeSendQuoteMarket(subAccount, positionType, quantity, slippage) {
  const { markets } = await fetchMarketSymbolId(config.HEDGER_URL, userConfig.SYMBOL);
  const lockedParams = await fetchLockedParams(markets[0].name, userConfig.LEVERAGE);
  const autoSlippage = markets[0].autoSlippage;
  
  const signatureResult = await getMuonSigImplementation(subAccount);
  let adjustedPrice = BigInt(signatureResult.signature.price); //Getting Price from the Muon Signature
  let numericSlippage;

  if (signatureResult.success) {
    if (slippage === "auto") {
      const autoSlippageNumerator = BigInt(Math.floor(autoSlippage * 1000));
      const autoSlippageDenominator = BigInt(1000); 
      adjustedPrice = positionType === 1
        ? (adjustedPrice * autoSlippageDenominator) / autoSlippageNumerator
        : (adjustedPrice * autoSlippageNumerator) / autoSlippageDenominator;
    } else {
      numericSlippage = Number(slippage); 
      if (isNaN(numericSlippage)) {
        console.error("Slippage must be a number or 'auto'");
        return;
      }
      const spSigned = positionType === 1 ? numericSlippage : -numericSlippage;
      const slippageFactored = (100 - spSigned) / 100;
      const slippageFactorBigInt = BigInt(Math.floor(slippageFactored * 100));
      adjustedPrice = (adjustedPrice * slippageFactorBigInt) / BigInt(100);
    }
  
    const requestedPrice = adjustedPrice;

The next step is to format the signature we received from Muon so it can be processed by the smart contract. This is done by converting the reqId and gatewaySignature to bytes arrays, and converting the other values to strings:

    const { reqId, timestamp, upnl, price, gatewaySignature, sigs } = signatureResult.signature;
    console.log("Price of asset: ", price);
    if (typeof reqId === 'undefined' || !reqId.startsWith('0x')) {
      console.error("reqId is undefined or not a hex string:", reqId);
    }
    if (typeof gatewaySignature === 'undefined' || !gatewaySignature.startsWith('0x')) {
      console.error("gatewaySignature is undefined or not a hex string:", gatewaySignature);
    }
    const upnlSigFormatted = {
        reqId: web3.utils.hexToBytes(reqId),
        timestamp: timestamp.toString(),
        upnl: upnl.toString(),
        price: price.toString(),
        gatewaySignature: web3.utils.hexToBytes(gatewaySignature),
        sigs: {
            signature: sigs.signature.toString(),
            owner: sigs.owner,
            nonce: sigs.nonce,
        }
    };
    const partyBsWhiteList = [config.PARTY_B_WHITELIST];
    const symbolId = markets[0].id;
    const orderType = 1; // This will be a MARKET order

Using the Locked Values

The locked values provided by the hedger should be implemented by applying them to the notional value of the quote. This can be done with the following logic:

Getting the Notional Value of the Quote:

    const requestedQuantityWei = web3.utils.toWei(quantity.toString(), 'ether');
    console.log("requestedQuantityWei:", requestedQuantityWei);
    const adjustedPriceStr = adjustedPrice.toString();
    const notionalValue = new BigNumber(requestedQuantityWei).multipliedBy(new BigNumber(adjustedPriceStr));
    console.log("notionalValue:", notionalValue.toString());

Getting the CVA (Credit Value Adjustment):

    const cvaWei = notionalValue
    * (new BigNumber(lockedParams.cva * 100))
    / (new BigNumber(10000)) 
    / (new BigNumber(lockedParams.leverage))
    / (new BigNumber(1e18));

Getting the LF (Liquidator Fee):

    const lfWei = notionalValue
    * (new BigNumber(lockedParams.lf * 100))
    / (new BigNumber(10000)) 
    / (new BigNumber(lockedParams.leverage))
    / (new BigNumber(1e18));

Getting the Maintenance Margin (Also required for partyB)

    const partyAmmWei = notionalValue
    * (new BigNumber(lockedParams.partyAmm * 100))
    / (new BigNumber(10000)) 
    / (new BigNumber(lockedParams.leverage))
    / (new BigNumber(1e18));

Finally, set the maxFundingRate and deadline:

    const maxFundingRate = web3.utils.toWei('200', 'ether'); 
    const deadline = (Math.floor(Date.now() / 1000) + 120).toString(); //120 seconds

We can then create an array of sendQuoteParamaters with all the variables we've defined:

    const sendQuoteParameters = [
      partyBsWhiteList,
      symbolId,
      positionType,
      orderType,
      requestedPrice.toString(), 
      requestedQuantityWei.toString(),
      cvaWei.toString(), 
      lfWei.toString(),
      partyAmmWei.toString(),
      partyBmmWei.toString(), 
      maxFundingRate.toString(), 
      deadline.toString(),
      upnlSigFormatted
  ];

To finalize the transaction, first encode it using the ABI from the sendQuote() function within the Diamond Facet. Then, leverage the _call function from the MultiAccount contract to pass the encoded data (_callData).

  //Encoding the Parameters
  const encodedSendQuoteData = web3.eth.abi.encodeFunctionCall(sendQuoteFunctionAbi, sendQuoteParameters);

  //Creating the Calldata
  const _callData = [
    subAccount,
    [ encodedSendQuoteData ]
  ];

    try {
    //Gas Estimates
      const bufferPercentage = 0.20;
      const bufferFactor = BigInt(Math.floor(bufferPercentage * 100));
      const sendQuoteGasEstimate = await multiAccountContract.methods._call(..._callData).estimateGas({ from: process.env.WALLET_ADDRESS });
      const adjustedGasLimit = sendQuoteGasEstimate + (sendQuoteGasEstimate * bufferFactor / BigInt(100));
      const sendQuotePrice = await web3.eth.getGasPrice();
      
    //Sending the Quote
      const sendQuoteReceipt = await multiAccountContract.methods._call(..._callData).send({
        from: account.address,
        gas: adjustedGasLimit.toString(), 
        gasPrice: sendQuotePrice.toString() 
      });

    } catch (error) {
        console.error('Error sending quote:', error);
    }
  } else {
    console.error('Failed to obtain signature:', signatureResult.error);
  }
}

Last updated

Logo

All rights to the people (c) 2023 Symmetry Labs A.G.