[ERR_INVALID_ARG_TYPE]: The”key” argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, KeyObject, or CryptoKey

got the error on the title when executing the function executeNewOrder, it seems to be something about the format of the signature, maybe something about the string or type, could anyone help?

import axios from "axios";
import crypto from "crypto";

const apiKey = process.env.API_KEY;
const apiSecret = process.env.API_SECRET;
const apiUrl = process.env.API_URL;

export async function executeNewOrder(symbol, quantity, side, price) {
  const data = {
    symbol,
    quantity,
    side,
    price,
    type: "LIMIT",
    timeInForce: "GTC",
  };

  const timeStamp = Date.now();
  const recvWindow = 50000;
  // limite de tempo para executar ordem

  const signature = crypto.createHmac("sha256", apiSecret).update(
    `${new URLSearchParams({
      ...data,
      timeStamp,
      recvWindow,
    }).toString()}`.digest("hex")
  );

  const newData = { ...data, timeStamp, recvWindow, signature };
  const qs = `?${new URLSearchParams(newData).toString()}`;

  const result = await axios({
    method: "POST",
    url: `${apiUrl}/v3/order${qs}`,
    headers: { " X-MBX-APIKEY": apiKey },
  });

  return result;
}

  • from the code you posted, it’s likely complaining about the value of apiSecret in crypto.createHmac("sha256", apiSecret) … troubleshooting hint … console.log(typeof apiSecret) to see what type it is

    – 

  • how is API_SECRET being set in the environment? An actual environment value, or are you using dotenv?

    – 

  • just checked and its really returning undenifed (apiSecret), good idea trying a typeof. My API_KEY and other are all set in .env file!!!

    – 

  • omg, think i forgot to import on the file

    – 

  • yeah!!! i forgot to import and config dotenv, my bad guys, thank u so much, thats my first job alone!!

    – 

Try this:

npm install dotenv

And insert the following code between the ‘crypto import’ statement and the ‘const apiKey = process.env.API_KEY’ declaration.

import * as dotenv from "dotenv";

dotenv.config();

I hope I’ve helped!

Leave a Comment