This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
129 lines (107 loc) · 2.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
//
// Created by Anton Spivak.
//
const tonlibjson = require("./build/Release/tonlibjson.node");
const uuid = require("uuid");
class Client {
#lib;
#promises;
#parameters;
constructor(_parameters) {
const parameters = Object.assign(
{},
{
logging: 0,
network: "mainnet",
},
_parameters
);
if (!parameters || !parameters.configuration) {
throw new Error("Configuration required.");
}
if (!parameters.keystorePath) {
throw new Error("Configuration `keystorePath` is required.");
}
this.#lib = new tonlibjson.Tonlib(parameters.logging, (data) => {
this.#receive(data);
});
this.#promises = {};
this.#parameters = parameters;
this.#configurate();
}
send(object) {
const extra = uuid.v4();
object["@extra"] = extra;
const string = JSON.stringify(object);
if (!string) {
throw new Error(`Can't parse JSON ${object}`);
}
let resolve, reject;
const promise = new Promise((resolve_, reject_) => {
resolve = resolve_;
reject = reject_;
});
this.#promises[extra] = {
resolve,
reject,
};
this.#lib.send(string);
return promise;
}
execute(object) {
const string = JSON.stringify(object);
if (!string) {
throw new Error(`Can't parse JSON ${object}`);
}
return this.#lib.execute(string);
}
#configurate() {
this.send({
"@type": "init",
options: {
"@type": "options",
config: {
"@type": "config",
config: this.#parameters.configuration,
use_callbacks_for_network: false,
blockchain_name: this.#parameters.network,
ignore_cache: false,
},
keystore_type: {
"@type": "keyStoreTypeDirectory",
directory: this.#parameters.keystorePath,
},
},
}).catch((error) => {
this.#error(error.message);
});
}
#receive(data) {
const object = JSON.parse(data);
if (!object) {
return;
}
const extra = object["@extra"];
if (!extra) {
return;
}
const promise = this.#promises[extra];
if (!promise) {
return;
}
delete this.#promises[extra];
delete object["@extra"];
setInterval(() => {
if (object["@type"] === "error") {
const message = object.message || "Undefined error";
promise.reject(new Error(message));
} else {
promise.resolve(object);
}
}, 1);
}
#error(message) {
console.log("\x1b[31m", "[node-tonlib]:", message, "\x1b[0m");
}
}
exports.Client = Client;