UNPKG

squarelink

Version:
414 lines 19.6 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(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 }); var squarelink_provider_engine_1 = require("squarelink-provider-engine"); var cache_1 = require("squarelink-provider-engine/subproviders/cache"); var fixture_1 = require("squarelink-provider-engine/subproviders/fixture"); var filters_1 = require("squarelink-provider-engine/subproviders/filters"); var gasprice_1 = require("squarelink-provider-engine/subproviders/gasprice"); var hooked_wallet_1 = require("squarelink-provider-engine/subproviders/hooked-wallet"); var nonce_tracker_1 = require("squarelink-provider-engine/subproviders/nonce-tracker"); var rpc_1 = require("squarelink-provider-engine/subproviders/rpc"); var subscriptions_1 = require("squarelink-provider-engine/subproviders/subscriptions"); var websocket_1 = require("squarelink-provider-engine/subproviders/websocket"); var config_1 = require("./config"); var util_1 = require("./util"); var networks_1 = require("./networks"); var walletMethods_1 = require("./walletMethods"); var error_1 = require("./error"); var Squarelink = /** @class */ (function () { /** * @param {string} clientId - Squarelink Client ID * @param {string} [network] - name of the network * @param {object} [network] * @param {string} [network.url] - the RPC Endpoint * @param {string} [network.chainId] */ function Squarelink(client_id, network, opts) { if (network === void 0) { network = 'mainnet'; } if (opts === void 0) { opts = {}; } if (opts.useSync) { this.NETWORKS = networks_1._availableAsSync; this.useSync = true; } else { networks_1._loadNetworks.call(this); } this.client_id = client_id; this.network = network; this.token = opts.token; this.scope = opts.scope || []; } /** * @returns { Web3Provider } a Web3Provider for use in web3.js */ Squarelink.prototype.getProvider = function (cb) { return __awaiter(this, void 0, void 0, function () { var _a, client_id, network, scope, err_1; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, , 3]); if (this.useSync) throw new error_1.SqlkError('Please set `useSync` to false'); return [4 /*yield*/, networks_1._waitForNetworks.call(this)]; case 1: _b.sent(); _a = this, client_id = _a.client_id, network = _a.network, scope = _a.scope; util_1._validateSecureOrigin(); util_1._validateParams.call(this, { client_id: client_id, network: network, scope: scope }); this.changeNetwork(network); // Support callbacks over promises if (cb) return [2 /*return*/, cb(this.engine, null)]; return [2 /*return*/, Promise.resolve(this.engine)]; case 2: err_1 = _b.sent(); if (cb) return [2 /*return*/, cb(null, err_1)]; return [2 /*return*/, Promise.reject(err_1)]; case 3: return [2 /*return*/]; } }); }); }; Squarelink.prototype.getProviderSync = function () { console.warn('[Squarelink]: getProviderSync is not recommended as we cannot ensure uptime of RPC providers.'); if (!this.useSync) throw new error_1.SqlkError('Please set `useSync` to true'); var _a = this, client_id = _a.client_id, network = _a.network, scope = _a.scope; util_1._validateSecureOrigin(); util_1._validateParams.call(this, { client_id: client_id, network: network, scope: scope }); this.changeNetwork(network); return this.engine; }; /** * Change the connected network * @param {string} network * @param {object} network * @param {string} network.url * @param {string} network.chainId */ Squarelink.prototype.changeNetwork = function (network) { var client_id = this.client_id; util_1._validateParams.call(this, { client_id: client_id, network: network }); this.network = network; this.net_version = util_1._getNetVersion.call(this, network); var _a = util_1._getRPCInfo.call(this, network), rpcUrl = _a.rpcUrl, connectionType = _a.connectionType, skipCache = _a.skipCache; this.connectionType = connectionType; this.rpcUrl = rpcUrl; this._initEngine(skipCache); }; /* END CUSTOM SQUARELINK METHODS */ Squarelink.prototype._initEngine = function (skipCache) { var _this = this; var self = this; this.accounts = []; var engine = new squarelink_provider_engine_1.default({ setSkipCacheFlag: skipCache, }); engine.isSquarelink = true; engine.isConnected = function () { return true; }; engine.send = function (payload, callback) { if (typeof payload === 'string') { return new Promise(function (resolve, reject) { engine.sendAsync({ jsonrpc: '2.0', id: 42, method: payload, params: callback || [], }, function (error, response) { if (error) { reject(error); } else { resolve(response.result); } }); }); } if (callback) { engine.sendAsync(payload, callback); return; } var result = null; switch (payload.method) { case 'eth_accounts': result = _this.accounts.length ? _this.accounts : []; break; case 'eth_coinbase': result = _this.accounts.length ? _this.accounts[0] : undefined; break; case 'net_version': result = _this.net_version || null; break; default: var message = "The Squarelink Web3 object does not support synchronous methods like " + payload.method + " without a callback parameter."; throw new error_1.SqlkError(message); } return { id: payload.id, jsonrpc: payload.jsonrpc, result: result, }; }; /** * START OF MIDDLEWARE DECLARATIONS */ var fixtureSubprovider = new fixture_1.default({ web3_clientVersion: "Squarelink/v" + config_1.VERSION + "/javascript", net_listening: true, eth_hashrate: '0x00', eth_mining: false, eth_syncing: true, }); var nonceSubprovider = new nonce_tracker_1.default(); var cacheSubprovider = new cache_1.default(); var gasPriceSubprovider = new gasprice_1.default(); /* Squarelink ID/Wallet Management */ var walletSubprovider = new hooked_wallet_1.default({ getAccounts: function (cb) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { cb(null, self.accounts); return [2 /*return*/]; }); }); }, getCoinbase: function (cb) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this.getAccounts() .then(function (accounts) { return cb(null, accounts[0]); }) .catch(function (err) { return cb(err, null); }); return [2 /*return*/]; }); }); }, signTransaction: function (payload, cb) { return __awaiter(this, void 0, void 0, function () { var from; return __generator(this, function (_a) { if (!self.accounts.length) { cb(new error_1.SqlkError('No accounts available'), null); return [2 /*return*/]; } from = payload.from; if (typeof from === 'number') from = self.accounts[from]; walletMethods_1._signTx(__assign({}, payload, { from: from, method: 'eth_signTransaction', client_id: self.client_id, network: self.network })) .then(function (res) { cb(null, res); }) .catch(function (err) { cb(err, null); }); return [2 /*return*/]; }); }); }, signMessage: function (payload, cb) { return __awaiter(this, void 0, void 0, function () { var from, data, method; return __generator(this, function (_a) { if (!self.accounts.length) { cb(new error_1.SqlkError('No accounts available'), null); return [2 /*return*/]; } from = payload.from, data = payload.data, method = payload.method; if (typeof from === 'number') from = self.accounts[from]; walletMethods_1._signMsg({ client_id: self.client_id, method: method || 'eth_sign', message: data, account: from, }) .then(function (res) { return cb(null, res); }) .catch(function (err) { return cb(err, null); }); return [2 /*return*/]; }); }); }, signPersonalMessage: function (payload, cb) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { if (!self.accounts.length) { cb(new error_1.SqlkError('No accounts available'), null); return [2 /*return*/]; } this.signMessage(__assign({}, payload, { method: 'eth_personalSign' }), function (err, res) { if (err) cb(err, null); else cb(null, res); }); return [2 /*return*/]; }); }); }, signTypedMessage: function (payload, cb) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { if (!self.accounts.length) { cb(new error_1.SqlkError('No accounts available'), null); return [2 /*return*/]; } this.signMessage(__assign({}, payload, { method: 'eth_signTypedData' }), function (err, res) { if (err) cb(err, null); else cb(null, res); }); return [2 /*return*/]; }); }); }, signTypedMessageV3: function (payload, cb) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { if (!self.accounts.length) { cb(new error_1.SqlkError('No accounts available'), null); return [2 /*return*/]; } this.signMessage(__assign({}, payload, { method: 'eth_signTypedData_v3' }), function (err, res) { if (err) cb(err, null); else cb(null, res); }); return [2 /*return*/]; }); }); }, }); /* ADD MIDDELWARE (PRESERVE ORDER) */ engine.addProvider(fixtureSubprovider); engine.addProvider(nonceSubprovider); engine.addProvider(cacheSubprovider); engine.addProvider(gasPriceSubprovider); engine.addProvider(walletSubprovider, 0); var _a = this, rpcUrl = _a.rpcUrl, connectionType = _a.connectionType; if (connectionType === 'http') { engine.addProvider(new rpc_1.default({ rpcUrl: rpcUrl })); engine.addProvider(new subscriptions_1.default(), 2); engine.addProvider(new filters_1.default(), 1); } else if (connectionType === 'ws') { engine.addProvider(new websocket_1.default({ rpcUrl: rpcUrl })); } /* END OF MIDDLEWARE */ engine.on('error', function (err) { console.error(err.stack); }); engine.enable = function () { return new Promise(function (resolve, reject) { if (self.token) { walletMethods_1._callAPI(self.token, { scope: self.scope }).then(function (_a) { var email = _a.email, name = _a.name, securitySettings = _a.securitySettings, accounts = _a.accounts; self.accounts = accounts; self.defaultEmail = email; self.defaultName = name; self.defaultSecuritySettings = securitySettings; resolve(accounts); }).catch(function (err) { return reject(err, null); }); } else { walletMethods_1._getAccounts(self.client_id, { scope: self.scope }).then(function (_a) { var email = _a.email, name = _a.name, securitySettings = _a.securitySettings, accounts = _a.accounts; self.accounts = accounts; self.defaultEmail = email; self.defaultName = name; self.defaultSecuritySettings = securitySettings; resolve(accounts); }).catch(function (err) { return reject(err); }); } }); }; engine.start(); this.engine = engine; }; /* CUSTOM SQUARELINK METHODS */ /** * @returns {string} the user's email */ Squarelink.prototype.getEmail = function () { if (!this.scope.includes('user') && !this.scope.includes('user:email')) throw new error_1.SqlkError("Please enable the user:email scope when initializing Squarelink"); return this.defaultEmail; }; /** * Returns the name of the authenticated user * @returns {string} the user's name */ Squarelink.prototype.getName = function () { if (!this.scope.includes('user') && !this.scope.includes('user:name')) throw new error_1.SqlkError("Please enable the user:name scope when initializing Squarelink"); return this.defaultName; }; /** * @typedef {Object} SquarelinkSecurity * @property {string} has2fa * @property {string} hasRecovery * @property {string} emailVerified */ /** * Returns the security settings of the authenticated user * @returns {SquarelinkSecurity} security settings */ Squarelink.prototype.getSecuritySettings = function () { if (!this.scope.includes('user') && !this.scope.includes('user:security')) throw new error_1.SqlkError("Please enable the user:security scope when initializing Squarelink"); return this.defaultSecuritySettings; }; return Squarelink; }()); exports.default = Squarelink; //# sourceMappingURL=index.js.map