Untitled

 avatar
unknown
plain_text
9 days ago
4.1 kB
5
Indexable
 async placeBidOrder(orderPayload) {
    try {
      console.log("orderPayload:::: placeBidOrder ->", orderPayload);
      const { id: userId, coin, amount, quantity } = orderPayload;
      console.log(coin, "");

      let tokenPriceUserwanttogiveInUsd = coin.toLowerCase() === "usdc" ? amount : null;
      let coinPrice = null;

      if (!tokenPriceUserwanttogiveInUsd) {
        const baseCurrencyPrice = await this.priceService.getCmcPriceByName(
          coin
        );
        if (baseCurrencyPrice.error) throw baseCurrencyPrice;
        coinPrice = baseCurrencyPrice.data.coin_price;
        tokenPriceUserwanttogiveInUsd = await bn_operations(
          amount.toString(),
          coinPrice.toString(),
          "*"
        );
      }

      const tokenInfo = await this.tokenModel.findOne();
      if (!tokenInfo) throw new Error("Token info not found");

      const finalTokenWillGet = String(
        await bn_operations(
          tokenPriceUserwanttogiveInUsd.toString(),
          tokenInfo.tokenPrice.toString(),
          "/"
        )
      );
      const finalTokenAmount = Number(finalTokenWillGet).toFixed(3);
      const requestedQuantity = Number(quantity).toFixed(3);

      console.table({
        tokenPriceUserwanttogiveInUsd,
        finalTokenAmount,
        "tokenInfo_tokenPrice": tokenInfo.tokenPrice,
        requestedQuantity,
      });

      if (finalTokenAmount < requestedQuantity)
        throw new Error("Price has been updated, not matching with quantity!");

      if (
        await bn_operations(finalTokenWillGet.toString(), String(MINBUY), "<")
      )
        throw new Error(`${Buy.BUY_LIMIT.MIN} ${MINBUY}`);
      if (
        await bn_operations(finalTokenWillGet.toString(), String(MAXBUY), ">")
      )
        throw new Error(`${Buy.BUY_LIMIT.MAX} ${MAXBUY}`);

      const userDetails = await this.usersService.findOneById(userId);
      if (userDetails.error) throw userDetails;

      const { client_id } = userDetails.data;
      const walletBalanceResponse = await this.gatewayService.getBalance({
        apiKey: this.configService.get("WALLET_API_KEY"),
        clientId: client_id,
        coin,
      });

      if (
        walletBalanceResponse.status !== HttpStatus.OK ||
        (await bn_operations(
          amount.toString(),
          walletBalanceResponse.data.balance.toString(),
          ">"
        ))
      ) {
        throw new Error(Buy.BALANCE.NOT_ENOUGH_BALANCE);
      }

      const transactionPayload = {
        amount,
        coinName: coin,
        baseCurrencyName: "USD",
        paymentType: PAYMENT_TYPES.CRYPTO,
        userId,
        tokenAmount: parseFloat(finalTokenWillGet).toFixed(8),
        orderType: ORDER_TYPE_ENUM.BID,
      };

      const transactionRes = await this.buyQueries.createTransactions(
        transactionPayload
      );
      if (transactionRes.error) throw new Error(WRONG_RESULT);

      const updateBalancePayload = {
        client_id,
        coin,
        transactionId: transactionRes.data.id,
        convertedamount: parseFloat(finalTokenWillGet).toFixed(8),
        vesting: 0,
        locking: 0,
        coinAmount: convert_to_bn(amount, "*"),
        tokenAmount: parseFloat(finalTokenWillGet).toFixed(8),
        fromCoin: coin,
      };

      if ((await this.updateAccountBalance(updateBalancePayload)).error)
        throw new Error("Balance update failed");
      if (
        (await this.updateTokenBalance(updateBalancePayload)).status !==
        HttpStatus.OK
      )
        throw new Error("Token balance update failed");

      tokenInfo.userTriggeredSpikedPrice = tokenPriceUserwanttogiveInUsd;
      tokenInfo.tokenPrice =
        Number(tokenInfo.marketPriceDifference) + Number(tokenPriceUserwanttogiveInUsd);
      await tokenInfo.save();

      return returnSuccess(false, Buy.TRANSACTION.CREATED, {
        transactionId: transactionRes.data.id,
        tokenAmount: parseFloat(finalTokenWillGet).toFixed(8),
      });
    } catch (error) {
      console.error("Error in bidOrder function", error);
      return returnError(true, error.message, error.status);
    }
  }
Editor is loading...
Leave a Comment