UNPKG

zumokit

Version:

ZumoKit is a Wallet as a Service SDK

319 lines (318 loc) 14.4 kB
"use strict"; 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 }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ZumoKit = void 0; var node_fetch_1 = require("node-fetch"); var ws_1 = require("ws"); var utility_1 = require("./utility"); var models_1 = require("./models"); var User_1 = require("./User"); var Utils_1 = require("./Utils"); var ZumoKitError_1 = require("./ZumoKitError"); /** * ZumoKit instance. Refer to <a href="https://developers.zumo.money/docs/guides/initialize-zumokit">documentation</a> for usage details. * */ var ZumoKit = /** @class */ (function () { /** @internal */ function ZumoKit(zumoCoreModule, apiKey, apiUrl, transactionServiceUrl, cardServiceUrl, notificationServiceUrl, exchangeServiceUrl, custodyServiceUrl) { var _this = this; this.socket = null; this.wsListener = null; this.changeListeners = []; this.changeListenersImpl = []; this.disconnected = false; /** Currently signed-in user or null. */ this.currentUser = null; /** Mapping between currency pairs and available exchange rates. */ this.exchangeRates = {}; /** Mapping between cryptocurrencies and available transaction fee rates. */ this.transactionFeeRates = {}; this.zumoCoreModule = zumoCoreModule; this.version = zumoCoreModule.ZumoCore.getVersion(); var boundedRequest = this.request.bind(this); var httpImpl = new zumoCoreModule.HttpProviderWrapper({ request: function (url, method, headers, data, callback) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { boundedRequest(url, method, headers, data, callback); return [2 /*return*/]; }); }); }, }); var boundedCreateWebSocket = this.createWebSocket.bind(this); var wsFactory = new zumoCoreModule.WebSocketFactoryWrapper({ createWebSocket: function (url) { return boundedCreateWebSocket(url); }, }); this.zumoCore = new zumoCoreModule.ZumoCore(httpImpl, wsFactory, apiKey, apiUrl, transactionServiceUrl, cardServiceUrl, notificationServiceUrl, exchangeServiceUrl, custodyServiceUrl); this.utils = new Utils_1.Utils(this.zumoCoreModule, this.zumoCore.getUtils()); this.addChangeListener(function () { _this.exchangeRates = models_1.ExchangeRates(JSON.parse(_this.zumoCore.getExchangeRates())); _this.transactionFeeRates = models_1.TransactionFeeRates(JSON.parse(_this.zumoCore.getTransactionFeeRates())); }); } ZumoKit.prototype.request = function (url, method, headers, data, callback) { return __awaiter(this, void 0, void 0, function () { var requestHeaders, mapKeys, i, key, response, result, exception_1, error, message; return __generator(this, function (_a) { switch (_a.label) { case 0: requestHeaders = {}; mapKeys = headers.keys(); for (i = 0; i < mapKeys.size(); i++) { key = mapKeys.get(i); requestHeaders[key] = headers.get(key); } _a.label = 1; case 1: _a.trys.push([1, 4, , 5]); return [4 /*yield*/, node_fetch_1.default(url, { method: method, headers: requestHeaders, body: data, })]; case 2: response = _a.sent(); return [4 /*yield*/, response.text()]; case 3: result = _a.sent(); callback.onSuccess(response.status, result); return [3 /*break*/, 5]; case 4: exception_1 = _a.sent(); if (typeof exception_1 === 'number') { error = new ZumoKitError_1.ZumoKitError(this.zumoCoreModule.getException(exception_1)); callback.onNetworkError(error.message); } else { message = exception_1.message; callback.onNetworkError(message); } return [3 /*break*/, 5]; case 5: return [2 /*return*/]; } }); }); }; ZumoKit.prototype.connectWebSocket = function (url) { var _this = this; this.socket = new ws_1.WebSocket(url); this.socket.on('open', function () { var _a; (_a = _this.wsListener) === null || _a === void 0 ? void 0 : _a.onOpen(url); }); this.socket.on('message', function (event) { var _a; (_a = _this.wsListener) === null || _a === void 0 ? void 0 : _a.onMessage(event.toString()); }); this.socket.on('error', function () { var _a, _b; if (_this.disconnected) { return; } (_a = _this.wsListener) === null || _a === void 0 ? void 0 : _a.onError('WebSocket error observed'); (_b = _this.socket) === null || _b === void 0 ? void 0 : _b.close(); }); this.socket.on('close', function (event) { var _a; if (_this.disconnected) { return; } (_a = _this.wsListener) === null || _a === void 0 ? void 0 : _a.onClose("WebSocket connection closed with exit code " + event.code + ", additional info: " + event.reason); // TODO: Reconnect via fuzzing back off generator setTimeout(function () { _this.connectWebSocket(url); }, 5000); }); }; ZumoKit.prototype.subscribe = function (listener) { this.wsListener = listener; }; ZumoKit.prototype.send = function (message) { var _a; (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(message); }; ZumoKit.prototype.createWebSocket = function (url) { var boundedConnectWebSocket = this.connectWebSocket.bind(this); var boundedSend = this.send.bind(this); var boundedSubscribe = this.subscribe.bind(this); return new this.zumoCoreModule.WebSocketWrapper({ connect: function () { boundedConnectWebSocket(url); }, send: function (message) { boundedSend(message); }, subscribe: function (listener) { boundedSubscribe(listener); }, }); }; /** * Sets log level for current logger. * * @param logLevel log level, e.g. 'debug' or 'info' */ ZumoKit.prototype.setLogLevel = function (logLevel) { this.zumoCoreModule.ZumoCore.setLogLevel(logLevel); }; /** * Sets log handler for all ZumoKit related logs. * * @param listener interface to listen to changes * @param logLevel log level, e.g. 'debug' or 'info' */ ZumoKit.prototype.onLog = function (listener, logLevel) { this.zumoCoreModule.ZumoCore.onLog(new this.zumoCoreModule.LogListenerWrapper({ onLog: function (message) { listener(message); }, }), logLevel); }; /** * Signs in user corresponding to user token set. Sets current user to the newly signed in user. * Refer to <a href="https://developers.zumo.money/docs/setup/server#get-zumokit-user-token">Server</a> guide for details on how to get user token set. * * @param tokenSet user token set */ ZumoKit.prototype.signIn = function (userTokenSet) { var _this = this; return utility_1.errorProxy(this.zumoCoreModule, function (resolve, reject) { _this.zumoCore.signIn(JSON.stringify(userTokenSet), new _this.zumoCoreModule.UserCallbackWrapper({ onError: function (error) { reject(new ZumoKitError_1.ZumoKitError(error)); }, onSuccess: function (user) { _this.currentUser = new User_1.User(_this.zumoCoreModule, user); resolve(_this.currentUser); }, })); }); }; /** Signs out current user. */ ZumoKit.prototype.signOut = function () { this.zumoCore.signOut(); this.currentUser = null; }; /** * Get exchange rate for selected currency pair. * * @param fromCurrency currency code * @param toCurrency currency code * * @return exchange rate or null */ ZumoKit.prototype.getExchangeRate = function (fromCurrency, toCurrency) { var exchangeRate = this.zumoCore.getExchangeRate(fromCurrency, toCurrency); if (exchangeRate.hasValue()) return new models_1.ExchangeRate(JSON.parse(exchangeRate.get())); return null; }; /** * Get transaction fee rate for selected crypto currency. * * @param currency currency code * * @return transaction fee rate or null */ ZumoKit.prototype.getTransactionFeeRate = function (currency) { var feeRate = this.zumoCore.getTransactionFeeRate(currency); if (feeRate.hasValue()) return new models_1.TransactionFeeRate(JSON.parse(feeRate.get())); return null; }; /** * Fetch historical exchange rates for supported time intervals. * * @return historical exchange rates */ ZumoKit.prototype.fetchHistoricalExchangeRates = function () { var _this = this; return utility_1.errorProxy(this.zumoCoreModule, function (resolve, reject) { _this.zumoCore.fetchHistoricalExchangeRates(new _this.zumoCoreModule.HistoricalExchangeRatesCallbackWrapper({ onError: function (error) { reject(new ZumoKitError_1.ZumoKitError(error)); }, onSuccess: function (json) { var historicalExchangeRatesJSON = JSON.parse(json); resolve(models_1.HistoricalExchangeRates(historicalExchangeRatesJSON)); }, })); }); }; /** * Listen to changes in current user’s sign in state, exchange rates, exchange settings or transaction fee rates. * * @param listener interface to listen to changes */ ZumoKit.prototype.addChangeListener = function (listener) { var listenerImpl = new this.zumoCoreModule.ChangeListenerWrapper({ onChange: function () { listener(); }, }); this.zumoCore.addChangeListener(listenerImpl); this.changeListeners.push(listener); this.changeListenersImpl.push(listenerImpl); }; /** * Remove change listener. * * @param listener interface to listen to changes */ ZumoKit.prototype.removeChangeListener = function (listener) { var index; // eslint-disable-next-line no-cond-assign while ((index = this.changeListeners.indexOf(listener)) !== -1) { this.changeListeners.splice(index, 1); this.zumoCore.removeChangeListener(this.changeListenersImpl.splice(index, 1)[0]); } }; /** * Stops WebSocket connection to Zumo Enterprise services. */ ZumoKit.prototype.disconnect = function () { var _a; this.disconnected = true; (_a = this.socket) === null || _a === void 0 ? void 0 : _a.terminate(); }; return ZumoKit; }()); exports.ZumoKit = ZumoKit;