squarelink
Version:
Squarelink's Web3 library
258 lines • 11.2 kB
JavaScript
;
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 });
/* eslint-disable */
var config_1 = require("./config");
var error_1 = require("./error");
var popup_1 = require("./popup");
var SCOPES = [
'wallets:admin',
'wallets:edit',
'wallets:create',
'wallets:remove',
'wallets:read',
'user',
'user:name',
'user:email',
'user:security'
];
/**
* URL-encodes a request object
* @param {object} obj
*/
exports._serialize = function (obj) {
return encodeURIComponent(JSON.stringify(obj));
};
/**
* Creates and executes GET Request
* @param {string} url
*/
exports._fetch = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send();
xhr.onload = function () {
if (xhr.status === 403) {
reject(new error_1.SqlkError("You are not authorized to access that resource"));
}
else if (xhr.status !== 200) {
reject(new error_1.SqlkError("Issue connecting to Squarelink servers"));
}
else {
resolve(JSON.parse(xhr.response));
}
};
xhr.onerror = function () {
reject(new error_1.SqlkError("Issue connecting to Squarelink servers"));
};
});
};
/**
* Creates Squarelink popup and returns posted result
* @param {string} url
*/
exports._popup = function (url) {
var _this = this;
return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var _a, popup, iframe, error, result, popupTick;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, popup_1.default(url)];
case 1:
_a = _b.sent(), popup = _a.popup, iframe = _a.iframe, error = _a.error;
if (error)
return [2 /*return*/, resolve({ error: 'Window closed' })];
result = false;
if (popup) {
popupTick = setInterval(function () {
if (result) {
clearInterval(popupTick);
}
else if (popup.closed) {
result = true;
window.removeEventListener('message', function () { });
clearInterval(popupTick);
resolve({ error: 'Window closed' });
var preloader = document.getElementById('squarelink-preloader-container');
preloader.parentNode.removeChild(preloader);
}
}, 1);
}
if (iframe) {
iframe.onClosed = function (error) {
if (!result) {
result = true;
window.removeEventListener('message', function () { });
resolve({ error: error || 'Window closed' });
}
};
}
window.addEventListener('message', function (e) {
var _a = e.data, origin = _a.origin, height = _a.height, type = _a.type;
if (type === 'onload')
return;
if (origin === 'squarelink' && !result) {
result = true;
window.removeEventListener('message', function () { });
if (popup) {
popup.close();
var preloader = document.getElementById('squarelink-preloader-container');
preloader.parentNode.removeChild(preloader);
}
else {
iframe.close();
}
resolve(__assign({}, e.data, { origin: undefined, height: undefined }));
}
}, false);
return [2 /*return*/];
}
});
}); });
};
/**
* Validates Squarelink inputs
* @param {string} client_id
* @param {string|object} [network]
* @param {array} [scope]
*/
exports._validateParams = function (_a) {
var client_id = _a.client_id, network = _a.network, scope = _a.scope;
if (scope) {
if (!Array.isArray(scope))
throw new error_1.SqlkError("'scope' must be an Array");
for (var i in scope) {
if (!SCOPES.includes(scope[i]))
throw new error_1.SqlkError("We do not support the " + scope[i] + " scope");
}
}
if (typeof network === 'object') {
if (!network.url)
throw new error_1.SqlkError('Please provide an RPC endpoint for your custom network');
else if (!network.url.match(/(wss|https){1}?:(\/?\/?)[^\s]+/))
throw new error_1.SqlkError('We do not currently support insecure (http://, ws://) RPC connections. Try updating squarelink to its latest version!');
else if (network.chainId && (network.chainId !== parseInt(network.chainId) || network.chainId < 0 || network.chainId > 500000))
throw new error_1.SqlkError('Please provide a valid Chain ID');
else if (network.skipCache !== undefined && typeof network.skipCache !== 'boolean')
throw new error_1.SqlkError('the `skipCache` paramter must be a boolean');
}
else if (!this.NETWORKS[network]) {
throw new error_1.SqlkError('Invalid network provided');
}
else if (!!this.NETWORKS[network].sdkVersion) {
var sdkVersion = this.NETWORKS[network].sdkVersion;
var sdkParts = config_1.VERSION.split('.');
var netParts = sdkVersion.split('.');
for (var i = 0; i < 3; i++) {
if (parseInt(sdkParts[i]) > parseInt(netParts[i]))
return;
if (parseInt(sdkParts[i]) < parseInt(netParts[i])) {
throw new error_1.SqlkError("You need to update Squarelink to squarelink@" + sdkVersion + " to use that network");
}
}
}
};
/**
* Notifies developer that their app won't work if on an insecure origin
*/
exports._validateSecureOrigin = function () {
var isLocalhost = location.hostname === 'localhost' || location.hostname === '127.0.0.1';
var isSecureOrigin = location.protocol === 'https:';
var isChromeExt = location.protocol === 'chrome-extension:';
var isSecure = isLocalhost || isSecureOrigin || isChromeExt;
if (!isSecure) {
throw new error_1.SqlkError("Access to the Squarelink Web3 Engine is restricted to secure origins.\nIf this is a development environment please use http://localhost:" + location.port + " instead.\nOtherwise, please use an SSL certificate.");
}
};
/**
* Gets RPC info from network parameter
* @param {string|object} network
*/
exports._getRPCInfo = function (network) {
var rpcUrl;
var skipCache = true;
if (typeof network === 'object') {
rpcUrl = network.url;
skipCache = network.skipCache !== undefined ? network.skipCache : true;
}
else {
var netInfo = this.NETWORKS[network];
rpcUrl = netInfo.rpcUrl;
skipCache = netInfo.skipCache !== undefined ? netInfo.skipCache : true;
}
var protocol = rpcUrl.split(':')[0].toLowerCase();
switch (protocol) {
case 'http':
case 'https':
return {
rpcUrl: rpcUrl,
skipCache: skipCache,
connectionType: 'http'
};
case 'ws':
case 'wss':
return {
rpcUrl: rpcUrl,
skipCache: skipCache,
connectionType: 'ws'
};
default:
throw new error_1.SqlkError("Unrecognized protocol in \"" + rpcUrl + "\"");
}
};
/**
* Get the current network version
* @param {string|object} network
*/
exports._getNetVersion = function (network) {
if (typeof network === 'object')
return network.chainId || null;
return this.NETWORKS[network].chainId;
};
//# sourceMappingURL=util.js.map