@cruxpay/js-sdk
Version:
CruxPay Javascript SDK
358 lines (357 loc) • 18.5 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { BaseError, ErrorHelper, PackageError, PackageErrorCode } from "../../packages/error";
import { getLogger } from "../../packages/logger";
import { cachedFunctionCall, httpJSONRequest, trimTrailingSlash } from "../../packages/utils";
var log = getLogger(__filename);
export var UPLOADABLE_JSON_FILES;
(function (UPLOADABLE_JSON_FILES) {
UPLOADABLE_JSON_FILES["CRUXPAY"] = "cruxpay.json";
UPLOADABLE_JSON_FILES["CLIENT_CONFIG"] = "client-config.json";
})(UPLOADABLE_JSON_FILES || (UPLOADABLE_JSON_FILES = {}));
var GaiaServiceApiClient = /** @class */ (function () {
function GaiaServiceApiClient() {
}
GaiaServiceApiClient.getHubInfo = function (gaiaHub, cacheStorage) { return __awaiter(void 0, void 0, void 0, function () {
var options;
return __generator(this, function (_a) {
options = {
baseUrl: trimTrailingSlash(gaiaHub),
url: "/hub_info",
};
return [2 /*return*/, cachedFunctionCall(cacheStorage, "" + options.baseUrl + options.url, 3600, httpJSONRequest, [options])];
});
}); };
GaiaServiceApiClient.store = function (gaiaHub, filename, address, authToken, contents, contentType) {
if (contentType === void 0) { contentType = "application/octet-stream"; }
return __awaiter(void 0, void 0, void 0, function () {
var options, response, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options = {
baseUrl: trimTrailingSlash(gaiaHub),
body: JSON.parse(contents),
headers: {
"Authorization": "bearer " + authToken,
"Content-Type": contentType,
},
method: "POST",
url: "/store/" + address + "/" + filename,
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, httpJSONRequest(options)];
case 2:
response = _a.sent();
return [2 /*return*/, response];
case 3:
error_1 = _a.sent();
throw new BaseError(error_1, "Error when uploading to Gaia hub");
case 4: return [2 /*return*/];
}
});
});
};
GaiaServiceApiClient.retrieve = function (readURLPrefix, filename, address, cacheStorage) { return __awaiter(void 0, void 0, void 0, function () {
var options, cacheTTL, responseBody, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options = {
baseUrl: trimTrailingSlash(readURLPrefix),
json: true,
method: "GET",
url: "/" + address + "/" + filename,
};
cacheTTL = filename === UPLOADABLE_JSON_FILES.CLIENT_CONFIG ? 3600 : undefined;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, cachedFunctionCall(cacheStorage, "" + options.baseUrl + options.url, cacheTTL, httpJSONRequest, [options], function (data) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, Boolean(filename !== UPLOADABLE_JSON_FILES.CLIENT_CONFIG || data.indexOf("BlobNotFound") > 0 || data.indexOf("NoSuchKey") > 0)];
});
}); })];
case 2:
responseBody = _a.sent();
return [3 /*break*/, 4];
case 3:
error_2 = _a.sent();
if (error_2 instanceof PackageError && error_2.errorCode === PackageErrorCode.Response404) {
throw ErrorHelper.getPackageError(null, PackageErrorCode.GaiaEmptyResponse);
}
throw ErrorHelper.getPackageError(null, PackageErrorCode.GaiaGetFileFailed, filename);
case 4: return [2 /*return*/, responseBody];
}
});
}); };
return GaiaServiceApiClient;
}());
export { GaiaServiceApiClient };
var BlockstackNamingServiceApiClient = /** @class */ (function () {
function BlockstackNamingServiceApiClient() {
}
BlockstackNamingServiceApiClient.getNamesByAddress = function (bnsNode, address, cacheStorage) { return __awaiter(void 0, void 0, void 0, function () {
var options, namesData, error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options = {
baseUrl: trimTrailingSlash(bnsNode),
json: true,
method: "GET",
url: "/v1/addresses/bitcoin/" + address,
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, httpJSONRequest(options)];
case 2:
namesData = (_a.sent());
return [2 /*return*/, namesData];
case 3:
error_3 = _a.sent();
throw ErrorHelper.getPackageError(error_3, PackageErrorCode.GetNamesByAddressFailed, "" + options.baseUrl + options.url, error_3);
case 4: return [2 /*return*/];
}
});
}); };
BlockstackNamingServiceApiClient.getNameDetails = function (bnsNode, blockstackName, tag, cacheStorage) { return __awaiter(void 0, void 0, void 0, function () {
var options, nameData, error_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options = {
baseUrl: trimTrailingSlash(bnsNode),
json: true,
method: "GET",
qs: null,
url: "/v1/names/" + blockstackName,
};
if (tag) {
options.qs = {
"x-tag": tag,
};
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, cachedFunctionCall(cacheStorage, "" + options.baseUrl + options.url + "?" + (options.qs ? Object.keys(options.qs).map(function (key) { return key + "=" + options.qs[key]; }).join("&") : ""), 3600, httpJSONRequest, [options], function (data) { return __awaiter(void 0, void 0, void 0, function () {
var skipCache;
return __generator(this, function (_a) {
skipCache = true;
if (data && data.status && data.status === "registered_subdomain") {
skipCache = false;
}
return [2 /*return*/, skipCache];
});
}); })];
case 2:
nameData = _a.sent();
return [3 /*break*/, 4];
case 3:
error_4 = _a.sent();
if (error_4 instanceof PackageError && error_4.errorCode === PackageErrorCode.Response404) {
return [2 /*return*/, {
more: "failed to find parent domain's resolver",
status: "available",
}];
}
throw ErrorHelper.getPackageError(error_4, PackageErrorCode.BnsResolutionFailed, options.baseUrl, error_4);
case 4: return [2 /*return*/, nameData];
}
});
}); };
return BlockstackNamingServiceApiClient;
}());
export { BlockstackNamingServiceApiClient };
var BlockstackSubdomainRegistrarApiClient = /** @class */ (function () {
function BlockstackSubdomainRegistrarApiClient(baseUrl, blockstackDomainId) {
var _this = this;
this.getSubdomainStatus = function (subdomainString) { return __awaiter(_this, void 0, void 0, function () {
var options, statusResponse, error_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initPromise];
case 1:
_a.sent();
options = {
baseUrl: trimTrailingSlash(this.baseUrl),
headers: {
"x-domain-name": this.blockstackDomainId.components.domain,
},
json: true,
method: "GET",
url: "/status/" + subdomainString,
};
log.debug("registration query params", options);
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, httpJSONRequest(options)];
case 3:
statusResponse = (_a.sent());
return [3 /*break*/, 5];
case 4:
error_5 = _a.sent();
if (error_5 instanceof PackageError && error_5.errorCode === PackageErrorCode.Response404) {
statusResponse = { status: "Not registered!" };
}
else {
throw error_5;
}
return [3 /*break*/, 5];
case 5: return [2 /*return*/, statusResponse];
}
});
}); };
this.registerSubdomain = function (name, gaiaHubUrl, ownerAdderss) { return __awaiter(_this, void 0, void 0, function () {
var options, registrationAcknowledgement, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initPromise];
case 1:
_a.sent();
options = {
baseUrl: trimTrailingSlash(this.baseUrl),
body: {
name: name,
owner_address: ownerAdderss,
zonefile: "$ORIGIN " + name + "\n$TTL 3600\n_https._tcp URI 10 1 " + gaiaHubUrl,
},
headers: {
"Content-Type": "application/json",
"x-domain-name": this.blockstackDomainId.components.domain,
},
json: true,
method: "POST",
strictSSL: false,
url: "/register",
};
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, httpJSONRequest(options)];
case 3:
registrationAcknowledgement = _a.sent();
return [3 /*break*/, 5];
case 4:
err_1 = _a.sent();
throw ErrorHelper.getPackageError(err_1, PackageErrorCode.SubdomainRegistrationFailed, err_1);
case 5:
log.debug("Subdomain registration acknowledgement:", registrationAcknowledgement);
if (registrationAcknowledgement && registrationAcknowledgement.status === true) {
return [2 /*return*/];
}
else {
throw ErrorHelper.getPackageError(null, PackageErrorCode.SubdomainRegistrationAcknowledgementFailed, JSON.stringify(registrationAcknowledgement));
}
return [2 /*return*/];
}
});
}); };
this.getSubdomainRegistrarEntriesByAddress = function (address) { return __awaiter(_this, void 0, void 0, function () {
var url, options, registrationsArray, error_6;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.initPromise];
case 1:
_a.sent();
url = "/subdomain/" + address;
options = {
baseUrl: trimTrailingSlash(this.baseUrl),
headers: {
"x-domain-name": this.blockstackDomainId.components.domain,
},
json: true,
method: "GET",
url: url,
};
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, httpJSONRequest(options)];
case 3:
registrationsArray = (_a.sent());
return [2 /*return*/, registrationsArray];
case 4:
error_6 = _a.sent();
throw ErrorHelper.getPackageError(error_6, PackageErrorCode.FetchPendingRegistrationsByAddressFailed, "" + options.baseUrl + options.url, error_6);
case 5: return [2 /*return*/];
}
});
}); };
this.getIndex = function () { return __awaiter(_this, void 0, void 0, function () {
var options;
return __generator(this, function (_a) {
options = {
baseUrl: trimTrailingSlash(this.baseUrl),
headers: {
"x-domain-name": this.blockstackDomainId.components.domain,
},
json: true,
method: "GET",
url: "/index",
};
log.debug("registration query params", options);
return [2 /*return*/, httpJSONRequest(options)];
});
}); };
this.init = function () { return __awaiter(_this, void 0, void 0, function () {
var indexFromUrl, domainFromUrl;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getIndex()];
case 1:
indexFromUrl = _a.sent();
domainFromUrl = indexFromUrl.domainName;
if (domainFromUrl !== this.blockstackDomainId.toString()) {
throw new BaseError(null, "Unexpected Domain from registrar " + domainFromUrl + " should be " + this.blockstackDomainId.toString());
}
return [2 /*return*/];
}
});
}); };
this.baseUrl = baseUrl;
this.blockstackDomainId = blockstackDomainId;
this.initPromise = this.init();
}
return BlockstackSubdomainRegistrarApiClient;
}());
export { BlockstackSubdomainRegistrarApiClient };