-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
189 lines (172 loc) · 8.15 KB
/
index.mjs
File metadata and controls
189 lines (172 loc) · 8.15 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"use strict";
import { Address } from "./lib/Address.mjs";
import { Addresses } from "./lib/Addresses.mjs";
import { APIError } from "./lib/APIError.mjs";
import { APIResource } from "./lib/APIResource.mjs";
import { APIResponse } from "./lib/APIResponse.mjs";
import { Cache } from "./lib/Cache.mjs";
import { createAlchemyWeb3 } from "@alch/alchemy-web3";
import { createHash } from "crypto";
import http from "http";
import { MareBits } from "./lib/MareBits.mjs";
import { readFileSync } from "fs";
const Secrets = globalThis.JSON.parse(readFileSync("./secrets.json"));
class MareBitsAPI extends APIResponse {
static #CHAIN_IDS = { ETHEREUM: 1, POLYGON: 137 };
static #CHAINS = { ETHEREUM: 1n << globalThis.BigInt(this.#CHAIN_IDS.ETHEREUM), POLYGON: 1n << globalThis.BigInt(this.#CHAIN_IDS.POLYGON) }
static #MARE_BITS_DEPLOYER_ADDRESS = "0x00Ad9AEb02CC7892c94DBd9E9BE93Ec5cf644632";
static #MARE_BITS_CONTRACT_ADDRESS = { ETHEREUM: "0xc5a1973E1f736e2aD991573f3649F4F4a44c3028", POLYGON: "0xb362A97aD06C907c4b575D3503fB9DC474498480" };
static #MARE_BITS_VAULT_ADDRESS = { ETHEREUM: "", POLYGON: "0x3d41144B7236Fb2119c52546D6F5Df15C0c316a8" };
static #MARE_BITS_OWNER_ADDRESS = "0x341256c1D56657B0c5A12E4157078251A32d7b75";
static #MAX_SIMULTANEOUS_REQUESTS = 6;
static #SERVER_URI = "https://api.mare.biz";
static #cache = new Cache();
static #server;
static #getWeb3() { return { ethereum: createAlchemyWeb3(Secrets.ALCHEMY_API_KEY.ETHEREUM), polygon: createAlchemyWeb3(Secrets.ALCHEMY_API_KEY.POLYGON) }; }
static listener(request, response) { return new this(request, response); }
static startListening() {
this.#server = http.createServer(this.listener.bind(this));
this.#server.listen(62737);
}
#isHeadWritten = false;
#request;
#requestUrl;
#response;
#status = 200;
#web3;
constructor(request, response) {
super();
[this.#request, this.#response] = [request, response];
this.#requestUrl = new globalThis.URL(this.#request.url, this.constructor.#SERVER_URI);
let endpoint;
if (this.#isCached)
endpoint = async () => this.#status = this.#cachedResponse.status;
else if (this.#request.method === "OPTIONS") {
switch (this.#requestUrl.pathname) {
case "*":
case "/balanceOf":
case "/circulatingSupply":
case "/totalSupply":
this.#response.setHeader("Allow", "GET, HEAD, OPTIONS"); break;
}
endpoint = async () => this.#status = 204;
} else if (this.#request.method === "GET" || this.#request.method === "HEAD") {
this.#web3 = this.constructor.#getWeb3();
switch (this.#requestUrl.pathname) {
case "/balanceOf": endpoint = this.#balanceOf; break;
case "/circulatingSupply": endpoint = this.#circulatingSupply; break;
case "/totalSupply": endpoint = this.#totalSupply; break;
default:
endpoint = async () => {
this.addError(new APIError({ detail: `The \`${this.#requestUrl.pathname}\` endpoint is unsupported.`, title: "Unsupported Method", status: "404" }));
this.#status = 404;
};
}
} else
endpoint = async () => {
this.addError(new APIError({ detail: `Server does not support request method \`${this.#request.method}\``, title: "Unimplemented Request Method", status: "501" }));
this.#status = 501;
};
endpoint.call(this)
.catch(this.#errorHandler.bind(this))
.then(() => this.#end())
.catch(console.error);
}
get [globalThis.Symbol.toStringTag]() { return "MareBitsAPI"; }
get #cachedResponse() { return this.constructor.#cache.get(this.#cacheKey); }
get #cacheKey() { return globalThis.JSON.stringify({ method: this.#request.method, url: this.#requestUrl.toString() }); }
get #isCached() { return typeof(this.#cachedResponse) !== "undefined"; }
get #message() { return this.#isCached ? this.#cachedResponse.message : globalThis.JSON.stringify(this); }
get #messageHash() {
const hash = createHash("sha256");
hash.update(this.#message);
return hash.digest().toString("base64");
}
async #balanceOf(inputAddresses = []) {
const addresses = await this.#getAddresses();
if (addresses.length === 0)
return;
const dataArrayPromise = { ethereum: [], polygon: [] };
const mareBits = {
ethereum: new MareBits(this.constructor.#MARE_BITS_CONTRACT_ADDRESS.ETHEREUM, this.#web3.ethereum),
polygon: new MareBits(this.constructor.#MARE_BITS_CONTRACT_ADDRESS.POLYGON, this.#web3.polygon)
};
let j = 0;
await addresses.forEach(async (address, i) => {
if (typeof(address.meta.error) !== "undefined")
return this.addError(new APIError({ detail: `Address \`${address.id}\` is not a valid address.`, title: "Invalid Address" }));
if (j >= this.constructor.#MAX_SIMULTANEOUS_REQUESTS)
return this.addError(new APIError({ detail: `Too many simultaneous requests, unable to get balance for address \`${address}\`.`, title: "Too Many Simultaneous Requests" }));
dataArrayPromise.ethereum[i] = mareBits.ethereum.balanceOf(address.id);
dataArrayPromise.polygon[i] = mareBits.polygon.balanceOf(address.id);
j++;
});
const dataArray = { ethereum: await globalThis.Promise.all(dataArrayPromise.ethereum), polygon: await globalThis.Promise.all(dataArrayPromise.polygon) };
const { fromWei, toBN } = this.#web3.ethereum.utils;
addresses.forEach((address, i) => {
if (typeof(dataArrayPromise.ethereum[i]) !== "undefined")
address.addAttribute({
balances: {
ethereum: fromWei(dataArray.ethereum[i]),
polygon: fromWei(dataArray.polygon[i]),
total: fromWei(toBN(dataArray.ethereum[i]).add(toBN(dataArray.polygon[i])))
}
});
this.addData(address);
});
}
async #circulatingSupply() {
const { fromWei, mareBits, toBN } = await this.#totalSupply();
const nums = await globalThis.Promise.all([
mareBits.ethereum.balanceOf(this.constructor.#MARE_BITS_DEPLOYER_ADDRESS),
mareBits.polygon.balanceOf(this.constructor.#MARE_BITS_DEPLOYER_ADDRESS),
mareBits.ethereum.balanceOf(this.constructor.#MARE_BITS_OWNER_ADDRESS),
mareBits.polygon.balanceOf(this.constructor.#MARE_BITS_OWNER_ADDRESS),
// mareBits.ethereum.balanceOf(this.constructor.#MARE_BITS_VAULT_ADDRESS.ETHEREUM),
mareBits.polygon.balanceOf(this.constructor.#MARE_BITS_VAULT_ADDRESS.POLYGON)
]);
this.data.attributes.circulatingSupply = fromWei(nums.reduce((result, num) => result.sub(toBN(num)), toBN(this.#web3.ethereum.utils.toWei(this.data.attributes.totalSupply))));
}
#errorHandler(err) {
if (err instanceof globalThis.Error)
this.addError(new APIError({ detail: err.message, title: err.name }));
else
this.addError(new APIError({ detail: err.toString() }));
throw err;
}
#end() {
this.#writeHead();
if (this.#request.method === "GET")
this.#response.write(this.#message);
this.#response.end();
if (!this.#isCached)
this.constructor.#cache.set(this.#cacheKey, { message: this.#message, status: this.#status });
}
#getAddresses() { return (new Addresses(this.#requestUrl.searchParams.getAll("address"))).normalize(this.#web3.ethereum); }
async #totalSupply() {
const mareBits = {
ethereum: new MareBits(this.constructor.#MARE_BITS_CONTRACT_ADDRESS.ETHEREUM, this.#web3.ethereum),
polygon: new MareBits(this.constructor.#MARE_BITS_CONTRACT_ADDRESS.POLYGON, this.#web3.polygon)
};
const { fromWei, toBN } = this.#web3.ethereum.utils;
const nums = await globalThis.Promise.all([mareBits.ethereum.totalSupply(), mareBits.ethereum.balanceOf("0x0000000000000000000000000000000000000001")]);
const response = new APIResource({ id: "ethereum:contract.marebits.eth", attributes: {}, type: "MareBits" });
response.attributes.totalSupply = fromWei(toBN(nums[0]).sub(toBN(nums[1])));
this.addData(response);
return { fromWei, mareBits, toBN };
}
#writeHead() {
if (this.#isHeadWritten)
return;
this.#response.writeHead(this.#status, {
"Access-Control-Allow-Origin": "*",
"Content-Length": (new globalThis.TextEncoder().encode(this.#message)).length,
"Content-Type": "application/json",
ETag: this.#messageHash,
Server: "api.mare.biz/1.0.0",
"X-Best-Pony": "Twilight Sparkle"
});
this.#isHeadWritten = true;
}
}
MareBitsAPI.startListening();