yhtx
Version:
HTX API
105 lines (93 loc) • 2.58 kB
JavaScript
const crypto = require("crypto");
const axios = require("axios");
function getSign(queryString, secret, method, path) {
let signString = [
method,
path.includes("linear-swap-api") ? "api.hbdm.com" : "api.huobi.pro",
path,
queryString || undefined,
]
.filter(Boolean)
.join("\n");
return crypto.createHmac("sha256", secret).update(signString).digest("base64");
}
async function call(path, { apiKey, secret, data, method, recvWindow } = {}) {
apiKey ||= "";
secret ||= "";
method ||= "GET";
recvWindow ??= 30000;
const origin = path.includes("linear-swap-api")
? "https://api.hbdm.com" //UM //for debig:https:api.btcgateway.pro, aws:https://api.hbdm.vn
: "https://api.huobi.pro"; //spot //https:api-aws.huobi.pro
data ||= {};
let timestamp = Date.now();
let url;
let sign;
timestamp = new Date(timestamp).toISOString().slice(0, 19);
let preBody = {
AccessKeyId: apiKey,
SignatureMethod: "HmacSHA256", //Ed25519
SignatureVersion: 2,
Timestamp: timestamp,
};
body = {
...preBody,
...data,
};
let pars = [];
for (let k in method == "GET" ? body : preBody)
pars.push(k + "=" + encodeURIComponent(body[k]));
let queryString = pars.sort().join("&");
if (method === "POST") {
url = origin + path + "?" + queryString;
sign = getSign(queryString, secret, method, path);
url += `&Signature=${sign}`;
} /*GET*/ else {
url = origin + path + "?" + queryString;
sign = getSign(queryString, secret, method, path);
url += `&Signature=${sign}`;
}
let headers = { "Content-Type": "application/json" };
let config = {
method,
url,
headers,
...(method == "POST" && { data }), //must be "data" //if GET, don't send
};
let r = await axios(config)
.then((r) => {
if (!(r.data?.code == 200 /*success*/ || r.data?.status == "ok"))
console.log(r.data); //if not code:200 or status:ok, then log
let rs = r.data.data;
return rs;
})
.catch(function (e) {
console.log(e.response.data);
});
return r;
}
class api {
constructor(apiKey = "", secret = "") {
this.apiKey = apiKey;
this.secret = secret;
}
async get(path, pr = {}) {
let data = {
apiKey: this.apiKey,
secret: this.secret,
data: pr,
};
return call(path, data);
}
async post(path, pr = {}) {
let data = {
apiKey: this.apiKey,
secret: this.secret,
method: "POST",
data: pr,
};
return call(path, data);
}
}
module.exports = api;
module.exports.call = call;