centrix-sdk
Version:
A SDK used to interact with the centrix API in a simple way.
67 lines (66 loc) • 3.25 kB
JavaScript
import EC from "elliptic";
import SHA256 from "crypto-js/sha256.js";
const ec = new EC.ec("secp256k1");
class CentrixClient {
constructor(server = "https://clc.ix.tc") {
this.server = server;
}
randomKey() {
return ec.genKeyPair().getPrivate().toString("hex");
}
publicKey(priv) {
return ec.keyFromPrivate(priv).getPublic().encode("hex", false);
}
async transact(priv, cid, addr) {
const kp = ec.keyFromPrivate(priv);
const sign = kp.sign(SHA256(addr).toString()).toDER("hex");
const res = await fetch(this.server + `/transaction?cid=${cid}&newholder=${addr}&sign=${sign}`);
if (!res.ok && res.status !== 500)
return `Could not transact coin ${cid} (failed to fetch, status code: ${res.status})`;
const data = await res.json();
if (data.error)
return `Could not transact coin ${cid} (Centrix server (${this.server}) responded with error: ${data.error})`;
return null;
}
async getCoin(cid) {
const res = await fetch(this.server + `/coin/${cid}`);
if (!res.ok && res.status !== 500)
return `Could not fertch coin ${cid} (failed to fetch, status code: ${res.status})`;
const data = await res.json();
if (data.error)
return `Could not fetch coin ${cid} (Centrix server (${this.server}) responded with error: ${data.error})`;
return data.coin;
}
async merge(origin, target, vol, priv) {
const originCoin = await this.getCoin(origin);
const targetCoin = await this.getCoin(target);
if (typeof originCoin === "string")
return originCoin;
if (typeof targetCoin === "string")
return targetCoin;
const kp = ec.keyFromPrivate(priv);
const sign = ec.sign(SHA256(target + " " + targetCoin.transactions.length + " " + vol).toString(), kp).toDER("hex");
const res = await fetch(this.server + `/merge?origin=${origin}&target=${target}&sign=${sign}&vol=${vol}`);
if (!res.ok && res.status !== 500)
return `Could not merge coin ${origin} into coin ${target} (failed to fetch, status code: ${res.status})`;
const data = await res.json();
if (data.error)
return `Could not merge coin ${origin} into coin ${target} (Centrix server (${this.server}) responded with error: ${data.error})`;
return null;
}
async split(origin, vol, priv) {
const originCoin = await this.getCoin(origin);
if (typeof originCoin === "string")
return originCoin;
const kp = ec.keyFromPrivate(priv);
const sign = ec.sign(SHA256("split " + originCoin.transactions.length + " 0 " + vol).toString(), kp).toDER("hex");
const res = await fetch(this.server + `/split?origin=${origin}&sign=${sign}&vol=${vol}`);
if (!res.ok && res.status !== 500)
return `Could not split coin ${origin} (failed to fetch, status code: ${res.status})`;
const data = await res.json();
if (data.error)
return `Could not split coin ${origin} (Centrix server (${this.server}) responded with error: ${data.error})`;
return data.id;
}
}
export default CentrixClient;