· 4 years ago · Jul 28, 2021, 12:06 AM
1"use strict";
2const crypto = require('crypto');
3const _ = require('lodash');
4const axios = require("axios");
5const API_KEY = '<API_KEY>';
6const API_SECRET = '<SECRET_KEY>';
7
8class Tokocrypto {
9
10 constructor(sandbox) {
11 this.key = API_KEY;
12 this.secret = API_SECRET;
13
14 this.baseUrl = `https://api.tokocrypto.com`;
15 }
16
17 createRequestConfig({ key, secret, payload }) {
18
19 const encodedPayload = (new Buffer(JSON.stringify(payload)))
20 .toString(`base64`);
21
22 const signature = crypto
23 .createHmac(`sha384`, secret)
24 .update(encodedPayload)
25 .digest(`hex`);
26
27 return {
28 headers: {
29 'X-TC-APIKEY': key,
30 'X-TC-PAYLOAD': encodedPayload,
31 'X-TC-SIGNATURE': signature,
32 },
33 };
34 }
35
36 requestPrivate(endpoint, method, params = {}) {
37 if (!this.key || !this.secret) {
38 throw new Error(
39 `API key and secret key required to use authenticated methods`);
40 }
41
42 const requestPath = `/v1${endpoint}`;
43 const requestUrl = `${this.baseUrl}${requestPath}`;
44 let payload = {
45 nonce: Date.now()
46 };
47 payload = _.assign(payload, params);
48 const config = this.createRequestConfig({
49 payload,
50 key: this.key,
51 secret: this.secret,
52 });
53
54 if (method === 'post'){
55 return new Promise(function (resolve, reject) {
56 axios.post(requestUrl, {}, config)
57 .then(function (response) {
58 resolve(response.data);
59 }).catch(function (err) {
60 reject(err.response.data.message);
61 });
62 });
63 }else if (method === 'get'){
64 return new Promise(function (resolve, reject) {
65 axios.get(requestUrl, config)
66 .then(function (response) {
67 resolve(response.data);
68 }).catch(function (err) {
69 reject(err.response.data.message);
70 });
71 });
72 }
73
74
75 }
76
77 async account() {
78 try {
79 let account = await this.requestPrivate('/account', 'get',{});
80 return account;
81 } catch (error) {
82 throw error;
83 }
84 }
85}
86
87module.exports = new Tokocrypto();
88
89async function main(){
90 let account = await module.exports.account();
91 console.log(account);
92}
93
94main();