@custonomy/community-sdk
Version:
Custonomy Lib for Community
404 lines • 18.8 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const consts_1 = require("./consts");
const common_1 = require("./common");
const events_1 = require("events");
const hmac_auth_express_1 = require("hmac-auth-express");
const uuid_1 = require("uuid");
const utils_1 = require("./utils");
const EventSourcePolyfill = require('event-source-polyfill').EventSourcePolyfill;
class Community extends events_1.EventEmitter {
constructor(option) {
var _a;
super();
this.MAX_COUNT = 60;
this._es = null;
this._esRequests = [];
this._esRequestShowHex = new Map();
this._endPoint = option.endPoint;
this._apiKey = option.apiKey;
this._apiSecret = option.apiSecret;
this._eventDrivenMode = (_a = option.eventDrivenMode) !== null && _a !== void 0 ? _a : false;
}
_callApi(path, params, action) {
let option = {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
Object.assign(option.headers, { "x-api-key": `${this._apiKey}` });
if (params) {
Object.assign(option, { body: JSON.stringify(params) });
}
Object.assign(option, { method: action });
return (0, common_1.fetchURL)(path, option);
}
_callHMACApi(path, request_body, action) {
let option = {};
if (this._apiSecret == null)
throw new Error('apiSecret is required');
let _path = path.startsWith('/') ? path : '/' + path;
_path = _path.indexOf('?') < 0 ? `${_path}?requestId=${(0, uuid_1.v4)()}` : (_path.endsWith('&') ? `${_path}requestId=${(0, uuid_1.v4)()}` : `${path}&requestId=${(0, uuid_1.v4)()}`);
const time = Date.now().toString();
const digest = (0, hmac_auth_express_1.generate)(this._apiSecret, 'sha512', time, action, _path, request_body !== null && request_body !== void 0 ? request_body : {}).digest('hex');
const hmac = `HMAC ${time}:${digest}`;
Object.assign(option, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'api-key': this._apiKey,
'Authorization': hmac,
},
'method': action
});
if (request_body && Object.keys(request_body).length > 0)
Object.assign(option, { body: JSON.stringify(request_body) });
return (0, common_1.fetchURL)(this._endPoint + _path, option);
}
signalPull(requestId) {
this.emit(`ready-to-pull-${requestId}`);
}
setEventDrivenMode(mode) {
this._eventDrivenMode = mode;
}
async registerEventListener(projectId, session) {
if (this._eventDrivenMode) {
var _es;
if (this._es == null) {
if ((0, utils_1.isNativeEventSourceAvailable)()) {
_es = new EventSource(this._endPoint + `/v0/community2/events?session=${session}&projectId=${projectId}`);
}
else {
_es = new EventSourcePolyfill(this._endPoint + `/v0/community2/events?session=${session}&projectId=${projectId}`);
}
if (_es) {
_es.onmessage = (e) => {
var _a, _b;
try {
console.log("EventSource message:", e.data);
let requestDone = true;
let data = JSON.parse(e.data);
let showHex = this._esRequestShowHex.get(data.id);
if (["completed"].includes(data.txnStatus)) {
this.emit("completed", data.id, showHex ? data.hex : data.txnId);
}
else if (["sent"].includes(data.txnStatus)) {
this.emit("sent", data.id, showHex ? data.hex : data.txnId);
}
else if (["error", "sent_error"].includes(data.txnStatus)) {
this.emit("error", data.id, (_a = data.errorReason) !== null && _a !== void 0 ? _a : data.txnErrorReason);
}
else if (data.status === "cancelled") {
this.emit("cancelled", data.id);
}
else if (["warning", "error"].includes(data.status)) {
this.emit("error", data.id, (_b = data.errorReason) !== null && _b !== void 0 ? _b : data.txnErrorReason);
}
else if (data.address) {
this.emit("address_generated", data.id, data.address);
}
else if (data.newAddress) {
this.emit("new_address_generated", data.id, data.newAddress);
}
else {
requestDone = false;
}
if (requestDone) {
this._esRequests = this._esRequests.filter((id) => id !== data.id);
this._esRequestShowHex.delete(data.id);
}
if (this._esRequests.length === 0) {
_es.close();
this._es = null;
}
}
catch (ex) {
console.error(ex);
}
};
this._es = _es;
}
}
}
}
_pull(requestId, session, showHex = false) {
if (this._eventDrivenMode) {
this._esRequests.push(requestId);
this._esRequestShowHex.set(requestId, showHex);
var _es;
if (this._es == null) {
if ((0, utils_1.isNativeEventSourceAvailable)()) {
_es = new EventSource(this._endPoint + `/v0/community2/events?session=${session}&requestId=${requestId}`);
}
else {
_es = new EventSourcePolyfill(this._endPoint + `/v0/community2/events?session=${session}&requestId=${requestId}`);
}
if (_es) {
_es.onmessage = (e) => {
var _a, _b;
try {
console.log("EventSource message:", e.data);
let requestDone = true;
let data = JSON.parse(e.data);
if (["completed"].includes(data.txnStatus)) {
this.emit("completed", data.id, showHex ? data.hex : data.txnId);
}
else if (["sent"].includes(data.txnStatus)) {
this.emit("sent", data.id, showHex ? data.hex : data.txnId);
}
else if (["error", "sent_error"].includes(data.txnStatus)) {
this.emit("error", data.id, (_a = data.errorReason) !== null && _a !== void 0 ? _a : data.txnErrorReason);
}
else if (data.status === "cancelled") {
this.emit("cancelled", data.id);
}
else if (["warning", "error"].includes(data.status)) {
this.emit("error", data.id, (_b = data.errorReason) !== null && _b !== void 0 ? _b : data.txnErrorReason);
}
else if (data.address) {
this.emit("address_generated", data.id, data.address);
}
else if (data.newAddress) {
this.emit("new_address_generated", data.id, data.newAddress);
}
else {
requestDone = false;
}
if (requestDone) {
this._esRequests = this._esRequests.filter((id) => id !== data.id);
this._esRequestShowHex.delete(data.id);
}
if (this._esRequests.length === 0) {
_es.close();
this._es = null;
}
}
catch (ex) {
console.error(ex);
}
};
this._es = _es;
}
}
}
else {
this._pullRequest(requestId, session, showHex);
}
}
_pullRequest(requestId, session, showHex) {
let count = 0;
const interval = setInterval(() => {
if (count >= this.MAX_COUNT) {
clearInterval(interval);
}
count++;
this._callApi(this._endPoint + `/v0/community2/status_pull/requests/${requestId}?session=${session}`, null, consts_1.ACTION.GET)
.then((res2) => {
var _a, _b;
if (["completed"].includes(res2.body.txnStatus)) {
this.emit("completed", res2.body.id, showHex ? res2.body.hex : res2.body.txnId);
clearInterval(interval);
}
else if (["error", "sent_error"].includes(res2.body.txnStatus)) {
this.emit("error", res2.body.id, (_a = res2.body.errorReason) !== null && _a !== void 0 ? _a : res2.body.txnErrorReason);
clearInterval(interval);
}
else if (res2.body.status === "cancelled") {
this.emit("cancelled", res2.body.id);
clearInterval(interval);
}
else if (["warning", "error"].includes(res2.body.status)) {
this.emit("error", res2.body.id, (_b = res2.body.errorReason) !== null && _b !== void 0 ? _b : res2.body.txnErrorReason);
clearInterval(interval);
}
else if (res2.body.address) {
this.emit("address_generated", res2.body.id, res2.body.address);
clearInterval(interval);
}
else if (res2.body.newAddress) {
this.emit("new_address_generated", res2.body.id, res2.body.newAddress);
clearInterval(interval);
}
})
.catch((ex) => {
console.error(ex);
});
}, 3000);
}
createUser(projectId, session, chain = "ETH") {
return this._callApi(this._endPoint + "/v0/community2/requests", {
projectId: projectId,
session: session,
type: "createaccount",
params: { chain: chain }
}, consts_1.ACTION.POST).then((response) => {
let count = 0;
const { body, status } = response;
if (status != 200) {
throw new Error(JSON.stringify(Object.assign(Object.assign({}, body), { status })));
}
else {
this._pull(body.id, session);
return {
id: body.id,
status: body.status,
callbackURL: body.callbackURL,
};
}
});
}
getUserInfo(projectId, session, chain) {
return this._callApi(this._endPoint + `/v0/community2/users?projectId=${projectId}&session=${session}${chain ? `&chain=${chain}` : ''}`, null, consts_1.ACTION.GET).then((response) => {
var _a;
if (((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.error) != null)
throw new Error(JSON.stringify(response.body));
if (response == null)
return null;
let user = response.body;
return user;
});
}
getAddress(projectId, session, chain) {
return this._callApi(this._endPoint + `/v0/community2/users?projectId=${projectId}&session=${session}${chain ? `&chain=${chain}` : ''}`, null, consts_1.ACTION.GET).then((response) => {
var _a, _b, _c;
if (((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.error) != null)
throw new Error(JSON.stringify(response.body));
if (response == null)
return null;
let user = response.body;
return ((_b = user.addresses) === null || _b === void 0 ? void 0 : _b.length) > 0 ? (_c = user.addresses[0]) === null || _c === void 0 ? void 0 : _c.address : null;
});
}
getAddressWithPubkey(projectId, session, chain) {
return this._callApi(this._endPoint + `/v0/community2/users?projectId=${projectId}&session=${session}${chain ? `&chain=${chain}` : ''}`, null, consts_1.ACTION.GET).then((response) => {
var _a, _b, _c, _d;
if (((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.error) != null)
throw new Error(JSON.stringify(response.body));
if (response == null)
return null;
let user = response.body;
return ((_b = user.addresses) === null || _b === void 0 ? void 0 : _b.length) > 0 ? { address: (_c = user.addresses[0]) === null || _c === void 0 ? void 0 : _c.address, pubkey: (_d = user.addresses[0]) === null || _d === void 0 ? void 0 : _d.pubkey } : null;
});
}
submitTransaction(projectId, session, transaction, showHex = false) {
return this._callApi(this._endPoint + "/v0/community2/requests", {
projectId: projectId,
session: session,
type: "createtxn",
params: transaction,
}, consts_1.ACTION.POST)
.then((response) => {
const { body, status } = response;
let count = 0;
if (status != 200) {
throw new Error(JSON.stringify(Object.assign(Object.assign({}, body), { status })));
}
else {
this._pull(body.id, session, showHex);
return {
id: body.id,
status: body.status,
callbackURL: body.callbackURL,
};
}
});
}
async signTransaction(projectId, session, data) {
var _a;
let txn = data;
if (txn.gas)
txn.gasLimit = txn.gas;
let obj = txn;
return this._callApi(this._endPoint + "/v0/community2/requests", {
projectId: projectId,
session: session,
type: "createtxn",
params: Object.assign(Object.assign({}, obj), { method: (_a = obj.method) !== null && _a !== void 0 ? _a : "eth_signTransaction" }),
}, consts_1.ACTION.POST).then((response) => {
const { body, status } = response;
let count = 0;
if (status != 200) {
throw new Error(JSON.stringify(Object.assign(Object.assign({}, body), { status })));
}
else {
this._pull(body.id, session, true);
return {
id: body.id,
status: body.status,
callbackURL: body.callbackURL,
};
}
});
}
async signData(projectId, session, data) {
return this.signTransaction(projectId, session, {
type: 9999,
chainId: data.chainId,
from: data.from,
method: data.method,
data: data.data,
sourceImage: data.sourceImage,
sourceName: data.sourceName,
sourceUrl: data.sourceUrl,
});
}
async listNetworks(projectId, session) {
return this._callApi(this._endPoint + `/v0/community2/networks?projectId=${projectId}&session=${session}`, null, consts_1.ACTION.GET).then((response) => {
var _a;
if (((_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.error) != null)
throw new Error(JSON.stringify(response.body));
if (response == null)
return null;
let networks = response.body;
return (networks === null || networks === void 0 ? void 0 : networks.length) > 0 ? networks : [];
});
}
async submitGenPasskeyOptRequest(projectId, session) {
return this._callApi(this._endPoint + "/v0/community2/requests", {
projectId: projectId,
session: session,
type: "genpasskeyopt",
}, consts_1.ACTION.POST)
.then((response) => {
const { body, status } = response;
if (status != 200) {
throw new Error(JSON.stringify(Object.assign(Object.assign({}, body), { status })));
}
else {
return {
id: body.id,
status: body.status,
callbackURL: body.callbackURL,
};
}
})
.catch((ex) => {
console.error(ex);
throw ex;
});
}
submitAPITransaction(projectId, session, data) {
return this._callHMACApi("/v0/community2/apirequests", {
projectId: projectId,
session: session,
type: "createtxn",
params: Object.assign({ type: 9999 }, data),
}, consts_1.ACTION.POST).then((response) => {
const { body, status } = response;
let count = 0;
if (status != 200) {
throw new Error(JSON.stringify(Object.assign(Object.assign({}, body), { status })));
}
else {
this._pull(body.id, session, data.type == 9999 || data.method == 'eth_signTransaction');
return {
id: body.id,
status: body.status,
};
}
});
}
}
exports.default = Community;
//# sourceMappingURL=community.js.map