@arcana/auth
Version:
Arcana Auth
1,308 lines (1,264 loc) • 156 kB
JavaScript
import require$$0 from 'events';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(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());
});
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var dist = {};
var classes = {};
var fastSafeStringify = stringify;
stringify.default = stringify;
stringify.stable = deterministicStringify;
stringify.stableStringify = deterministicStringify;
var LIMIT_REPLACE_NODE = '[...]';
var CIRCULAR_REPLACE_NODE = '[Circular]';
var arr = [];
var replacerStack = [];
function defaultOptions () {
return {
depthLimit: Number.MAX_SAFE_INTEGER,
edgesLimit: Number.MAX_SAFE_INTEGER
}
}
// Regular stringify
function stringify (obj, replacer, spacer, options) {
if (typeof options === 'undefined') {
options = defaultOptions();
}
decirc(obj, '', 0, [], undefined, 0, options);
var res;
try {
if (replacerStack.length === 0) {
res = JSON.stringify(obj, replacer, spacer);
} else {
res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
}
} catch (_) {
return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
} finally {
while (arr.length !== 0) {
var part = arr.pop();
if (part.length === 4) {
Object.defineProperty(part[0], part[1], part[3]);
} else {
part[0][part[1]] = part[2];
}
}
}
return res
}
function setReplace (replace, val, k, parent) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
if (propertyDescriptor.get !== undefined) {
if (propertyDescriptor.configurable) {
Object.defineProperty(parent, k, { value: replace });
arr.push([parent, k, val, propertyDescriptor]);
} else {
replacerStack.push([val, k, replace]);
}
} else {
parent[k] = replace;
arr.push([parent, k, val]);
}
}
function decirc (val, k, edgeIndex, stack, parent, depth, options) {
depth += 1;
var i;
if (typeof val === 'object' && val !== null) {
for (i = 0; i < stack.length; i++) {
if (stack[i] === val) {
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);
return
}
}
if (
typeof options.depthLimit !== 'undefined' &&
depth > options.depthLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return
}
if (
typeof options.edgesLimit !== 'undefined' &&
edgeIndex + 1 > options.edgesLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return
}
stack.push(val);
// Optimize for Arrays. Big arrays could kill the performance otherwise!
if (Array.isArray(val)) {
for (i = 0; i < val.length; i++) {
decirc(val[i], i, i, stack, val, depth, options);
}
} else {
var keys = Object.keys(val);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
decirc(val[key], key, i, stack, val, depth, options);
}
}
stack.pop();
}
}
// Stable-stringify
function compareFunction (a, b) {
if (a < b) {
return -1
}
if (a > b) {
return 1
}
return 0
}
function deterministicStringify (obj, replacer, spacer, options) {
if (typeof options === 'undefined') {
options = defaultOptions();
}
var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj;
var res;
try {
if (replacerStack.length === 0) {
res = JSON.stringify(tmp, replacer, spacer);
} else {
res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);
}
} catch (_) {
return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
} finally {
// Ensure that we restore the object as it was.
while (arr.length !== 0) {
var part = arr.pop();
if (part.length === 4) {
Object.defineProperty(part[0], part[1], part[3]);
} else {
part[0][part[1]] = part[2];
}
}
}
return res
}
function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) {
depth += 1;
var i;
if (typeof val === 'object' && val !== null) {
for (i = 0; i < stack.length; i++) {
if (stack[i] === val) {
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);
return
}
}
try {
if (typeof val.toJSON === 'function') {
return
}
} catch (_) {
return
}
if (
typeof options.depthLimit !== 'undefined' &&
depth > options.depthLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return
}
if (
typeof options.edgesLimit !== 'undefined' &&
edgeIndex + 1 > options.edgesLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent);
return
}
stack.push(val);
// Optimize for Arrays. Big arrays could kill the performance otherwise!
if (Array.isArray(val)) {
for (i = 0; i < val.length; i++) {
deterministicDecirc(val[i], i, i, stack, val, depth, options);
}
} else {
// Create a temporary object in the required way
var tmp = {};
var keys = Object.keys(val).sort(compareFunction);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
deterministicDecirc(val[key], key, i, stack, val, depth, options);
tmp[key] = val[key];
}
if (typeof parent !== 'undefined') {
arr.push([parent, k, val]);
parent[k] = tmp;
} else {
return tmp
}
}
stack.pop();
}
}
// wraps replacer function to handle values we couldn't replace
// and mark them as replaced value
function replaceGetterValues (replacer) {
replacer =
typeof replacer !== 'undefined'
? replacer
: function (k, v) {
return v
};
return function (key, val) {
if (replacerStack.length > 0) {
for (var i = 0; i < replacerStack.length; i++) {
var part = replacerStack[i];
if (part[1] === key && part[0] === val) {
val = part[2];
replacerStack.splice(i, 1);
break
}
}
}
return replacer.call(this, key, val)
}
}
Object.defineProperty(classes, "__esModule", { value: true });
classes.EthereumProviderError = classes.EthereumRpcError = void 0;
const fast_safe_stringify_1 = fastSafeStringify;
/**
* Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors
* per EIP-1474.
* Permits any integer error code.
*/
class EthereumRpcError extends Error {
constructor(code, message, data) {
if (!Number.isInteger(code)) {
throw new Error('"code" must be an integer.');
}
if (!message || typeof message !== 'string') {
throw new Error('"message" must be a nonempty string.');
}
super(message);
this.code = code;
if (data !== undefined) {
this.data = data;
}
}
/**
* Returns a plain object with all public class properties.
*/
serialize() {
const serialized = {
code: this.code,
message: this.message,
};
if (this.data !== undefined) {
serialized.data = this.data;
}
if (this.stack) {
serialized.stack = this.stack;
}
return serialized;
}
/**
* Return a string representation of the serialized error, omitting
* any circular references.
*/
toString() {
return fast_safe_stringify_1.default(this.serialize(), stringifyReplacer, 2);
}
}
classes.EthereumRpcError = EthereumRpcError;
/**
* Error subclass implementing Ethereum Provider errors per EIP-1193.
* Permits integer error codes in the [ 1000 <= 4999 ] range.
*/
class EthereumProviderError extends EthereumRpcError {
/**
* Create an Ethereum Provider JSON-RPC error.
* `code` must be an integer in the 1000 <= 4999 range.
*/
constructor(code, message, data) {
if (!isValidEthProviderCode(code)) {
throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');
}
super(code, message, data);
}
}
classes.EthereumProviderError = EthereumProviderError;
// Internal
function isValidEthProviderCode(code) {
return Number.isInteger(code) && code >= 1000 && code <= 4999;
}
function stringifyReplacer(_, value) {
if (value === '[Circular]') {
return undefined;
}
return value;
}
var utils = {};
var errorConstants = {};
Object.defineProperty(errorConstants, "__esModule", { value: true });
errorConstants.errorValues = errorConstants.errorCodes = void 0;
errorConstants.errorCodes = {
rpc: {
invalidInput: -32000,
resourceNotFound: -32001,
resourceUnavailable: -32002,
transactionRejected: -32003,
methodNotSupported: -32004,
limitExceeded: -32005,
parse: -32700,
invalidRequest: -32600,
methodNotFound: -32601,
invalidParams: -32602,
internal: -32603,
},
provider: {
userRejectedRequest: 4001,
unauthorized: 4100,
unsupportedMethod: 4200,
disconnected: 4900,
chainDisconnected: 4901,
},
};
errorConstants.errorValues = {
'-32700': {
standard: 'JSON RPC 2.0',
message: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',
},
'-32600': {
standard: 'JSON RPC 2.0',
message: 'The JSON sent is not a valid Request object.',
},
'-32601': {
standard: 'JSON RPC 2.0',
message: 'The method does not exist / is not available.',
},
'-32602': {
standard: 'JSON RPC 2.0',
message: 'Invalid method parameter(s).',
},
'-32603': {
standard: 'JSON RPC 2.0',
message: 'Internal JSON-RPC error.',
},
'-32000': {
standard: 'EIP-1474',
message: 'Invalid input.',
},
'-32001': {
standard: 'EIP-1474',
message: 'Resource not found.',
},
'-32002': {
standard: 'EIP-1474',
message: 'Resource unavailable.',
},
'-32003': {
standard: 'EIP-1474',
message: 'Transaction rejected.',
},
'-32004': {
standard: 'EIP-1474',
message: 'Method not supported.',
},
'-32005': {
standard: 'EIP-1474',
message: 'Request limit exceeded.',
},
'4001': {
standard: 'EIP-1193',
message: 'User rejected the request.',
},
'4100': {
standard: 'EIP-1193',
message: 'The requested account and/or method has not been authorized by the user.',
},
'4200': {
standard: 'EIP-1193',
message: 'The requested method is not supported by this Ethereum provider.',
},
'4900': {
standard: 'EIP-1193',
message: 'The provider is disconnected from all chains.',
},
'4901': {
standard: 'EIP-1193',
message: 'The provider is disconnected from the specified chain.',
},
};
(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.serializeError = exports.isValidCode = exports.getMessageFromCode = exports.JSON_RPC_SERVER_ERROR_MESSAGE = void 0;
const error_constants_1 = errorConstants;
const classes_1 = classes;
const FALLBACK_ERROR_CODE = error_constants_1.errorCodes.rpc.internal;
const FALLBACK_MESSAGE = 'Unspecified error message. This is a bug, please report it.';
const FALLBACK_ERROR = {
code: FALLBACK_ERROR_CODE,
message: getMessageFromCode(FALLBACK_ERROR_CODE),
};
exports.JSON_RPC_SERVER_ERROR_MESSAGE = 'Unspecified server error.';
/**
* Gets the message for a given code, or a fallback message if the code has
* no corresponding message.
*/
function getMessageFromCode(code, fallbackMessage = FALLBACK_MESSAGE) {
if (Number.isInteger(code)) {
const codeString = code.toString();
if (hasKey(error_constants_1.errorValues, codeString)) {
return error_constants_1.errorValues[codeString].message;
}
if (isJsonRpcServerError(code)) {
return exports.JSON_RPC_SERVER_ERROR_MESSAGE;
}
}
return fallbackMessage;
}
exports.getMessageFromCode = getMessageFromCode;
/**
* Returns whether the given code is valid.
* A code is only valid if it has a message.
*/
function isValidCode(code) {
if (!Number.isInteger(code)) {
return false;
}
const codeString = code.toString();
if (error_constants_1.errorValues[codeString]) {
return true;
}
if (isJsonRpcServerError(code)) {
return true;
}
return false;
}
exports.isValidCode = isValidCode;
/**
* Serializes the given error to an Ethereum JSON RPC-compatible error object.
* Merely copies the given error's values if it is already compatible.
* If the given error is not fully compatible, it will be preserved on the
* returned object's data.originalError property.
*/
function serializeError(error, { fallbackError = FALLBACK_ERROR, shouldIncludeStack = false, } = {}) {
var _a, _b;
if (!fallbackError ||
!Number.isInteger(fallbackError.code) ||
typeof fallbackError.message !== 'string') {
throw new Error('Must provide fallback error with integer number code and string message.');
}
if (error instanceof classes_1.EthereumRpcError) {
return error.serialize();
}
const serialized = {};
if (error &&
typeof error === 'object' &&
!Array.isArray(error) &&
hasKey(error, 'code') &&
isValidCode(error.code)) {
const _error = error;
serialized.code = _error.code;
if (_error.message && typeof _error.message === 'string') {
serialized.message = _error.message;
if (hasKey(_error, 'data')) {
serialized.data = _error.data;
}
}
else {
serialized.message = getMessageFromCode(serialized.code);
serialized.data = { originalError: assignOriginalError(error) };
}
}
else {
serialized.code = fallbackError.code;
const message = (_a = error) === null || _a === void 0 ? void 0 : _a.message;
serialized.message = (message && typeof message === 'string'
? message
: fallbackError.message);
serialized.data = { originalError: assignOriginalError(error) };
}
const stack = (_b = error) === null || _b === void 0 ? void 0 : _b.stack;
if (shouldIncludeStack && error && stack && typeof stack === 'string') {
serialized.stack = stack;
}
return serialized;
}
exports.serializeError = serializeError;
// Internal
function isJsonRpcServerError(code) {
return code >= -32099 && code <= -32000;
}
function assignOriginalError(error) {
if (error && typeof error === 'object' && !Array.isArray(error)) {
return Object.assign({}, error);
}
return error;
}
function hasKey(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
} (utils));
var errors = {};
Object.defineProperty(errors, "__esModule", { value: true });
errors.ethErrors = void 0;
const classes_1 = classes;
const utils_1 = utils;
const error_constants_1 = errorConstants;
errors.ethErrors = {
rpc: {
/**
* Get a JSON RPC 2.0 Parse (-32700) error.
*/
parse: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.parse, arg),
/**
* Get a JSON RPC 2.0 Invalid Request (-32600) error.
*/
invalidRequest: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.invalidRequest, arg),
/**
* Get a JSON RPC 2.0 Invalid Params (-32602) error.
*/
invalidParams: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.invalidParams, arg),
/**
* Get a JSON RPC 2.0 Method Not Found (-32601) error.
*/
methodNotFound: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.methodNotFound, arg),
/**
* Get a JSON RPC 2.0 Internal (-32603) error.
*/
internal: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.internal, arg),
/**
* Get a JSON RPC 2.0 Server error.
* Permits integer error codes in the [ -32099 <= -32005 ] range.
* Codes -32000 through -32004 are reserved by EIP-1474.
*/
server: (opts) => {
if (!opts || typeof opts !== 'object' || Array.isArray(opts)) {
throw new Error('Ethereum RPC Server errors must provide single object argument.');
}
const { code } = opts;
if (!Number.isInteger(code) || code > -32005 || code < -32099) {
throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');
}
return getEthJsonRpcError(code, opts);
},
/**
* Get an Ethereum JSON RPC Invalid Input (-32000) error.
*/
invalidInput: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.invalidInput, arg),
/**
* Get an Ethereum JSON RPC Resource Not Found (-32001) error.
*/
resourceNotFound: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.resourceNotFound, arg),
/**
* Get an Ethereum JSON RPC Resource Unavailable (-32002) error.
*/
resourceUnavailable: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.resourceUnavailable, arg),
/**
* Get an Ethereum JSON RPC Transaction Rejected (-32003) error.
*/
transactionRejected: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.transactionRejected, arg),
/**
* Get an Ethereum JSON RPC Method Not Supported (-32004) error.
*/
methodNotSupported: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.methodNotSupported, arg),
/**
* Get an Ethereum JSON RPC Limit Exceeded (-32005) error.
*/
limitExceeded: (arg) => getEthJsonRpcError(error_constants_1.errorCodes.rpc.limitExceeded, arg),
},
provider: {
/**
* Get an Ethereum Provider User Rejected Request (4001) error.
*/
userRejectedRequest: (arg) => {
return getEthProviderError(error_constants_1.errorCodes.provider.userRejectedRequest, arg);
},
/**
* Get an Ethereum Provider Unauthorized (4100) error.
*/
unauthorized: (arg) => {
return getEthProviderError(error_constants_1.errorCodes.provider.unauthorized, arg);
},
/**
* Get an Ethereum Provider Unsupported Method (4200) error.
*/
unsupportedMethod: (arg) => {
return getEthProviderError(error_constants_1.errorCodes.provider.unsupportedMethod, arg);
},
/**
* Get an Ethereum Provider Not Connected (4900) error.
*/
disconnected: (arg) => {
return getEthProviderError(error_constants_1.errorCodes.provider.disconnected, arg);
},
/**
* Get an Ethereum Provider Chain Not Connected (4901) error.
*/
chainDisconnected: (arg) => {
return getEthProviderError(error_constants_1.errorCodes.provider.chainDisconnected, arg);
},
/**
* Get a custom Ethereum Provider error.
*/
custom: (opts) => {
if (!opts || typeof opts !== 'object' || Array.isArray(opts)) {
throw new Error('Ethereum Provider custom errors must provide single object argument.');
}
const { code, message, data } = opts;
if (!message || typeof message !== 'string') {
throw new Error('"message" must be a nonempty string');
}
return new classes_1.EthereumProviderError(code, message, data);
},
},
};
// Internal
function getEthJsonRpcError(code, arg) {
const [message, data] = parseOpts(arg);
return new classes_1.EthereumRpcError(code, message || utils_1.getMessageFromCode(code), data);
}
function getEthProviderError(code, arg) {
const [message, data] = parseOpts(arg);
return new classes_1.EthereumProviderError(code, message || utils_1.getMessageFromCode(code), data);
}
function parseOpts(arg) {
if (arg) {
if (typeof arg === 'string') {
return [arg];
}
else if (typeof arg === 'object' && !Array.isArray(arg)) {
const { message, data } = arg;
if (message && typeof message !== 'string') {
throw new Error('Must specify string message.');
}
return [message || undefined, data];
}
}
return [];
}
(function (exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMessageFromCode = exports.serializeError = exports.EthereumProviderError = exports.EthereumRpcError = exports.ethErrors = exports.errorCodes = void 0;
const classes_1 = classes;
Object.defineProperty(exports, "EthereumRpcError", { enumerable: true, get: function () { return classes_1.EthereumRpcError; } });
Object.defineProperty(exports, "EthereumProviderError", { enumerable: true, get: function () { return classes_1.EthereumProviderError; } });
const utils_1 = utils;
Object.defineProperty(exports, "serializeError", { enumerable: true, get: function () { return utils_1.serializeError; } });
Object.defineProperty(exports, "getMessageFromCode", { enumerable: true, get: function () { return utils_1.getMessageFromCode; } });
const errors_1 = errors;
Object.defineProperty(exports, "ethErrors", { enumerable: true, get: function () { return errors_1.ethErrors; } });
const error_constants_1 = errorConstants;
Object.defineProperty(exports, "errorCodes", { enumerable: true, get: function () { return error_constants_1.errorCodes; } });
} (dist));
var safeEventEmitter = {};
Object.defineProperty(safeEventEmitter, "__esModule", { value: true });
const events_1 = require$$0;
function safeApply(handler, context, args) {
try {
Reflect.apply(handler, context, args);
}
catch (err) {
// Throw error after timeout so as not to interrupt the stack
setTimeout(() => {
throw err;
});
}
}
function arrayClone(arr) {
const n = arr.length;
const copy = new Array(n);
for (let i = 0; i < n; i += 1) {
copy[i] = arr[i];
}
return copy;
}
class SafeEventEmitter extends events_1.EventEmitter {
emit(type, ...args) {
let doError = type === 'error';
const events = this._events;
if (events !== undefined) {
doError = doError && events.error === undefined;
}
else if (!doError) {
return false;
}
// If there is no 'error' event listener then throw.
if (doError) {
let er;
if (args.length > 0) {
[er] = args;
}
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
const err = new Error(`Unhandled error.${er ? ` (${er.message})` : ''}`);
err.context = er;
throw err; // Unhandled 'error' event
}
const handler = events[type];
if (handler === undefined) {
return false;
}
if (typeof handler === 'function') {
safeApply(handler, this, args);
}
else {
const len = handler.length;
const listeners = arrayClone(handler);
for (let i = 0; i < len; i += 1) {
safeApply(listeners[i], this, args);
}
}
return true;
}
}
var _default = safeEventEmitter.default = SafeEventEmitter;
class ArcanaAuthError extends Error {
constructor(code, message) {
super(code);
this.message = message;
this.message = `[XAR_AUTH_SDK] error: [${code}] ${message}`;
}
}
class ArcanaAuthWarning {
constructor(code, message) {
this.message = `[XAR_AUTH_SDK] warning: [${code}] ${message}`;
}
log() {
console.warn(this.message);
}
}
const ErrorNotLoggedIn = new ArcanaAuthError('user_not_logged_in', 'User is not logged in');
const ErrorNotInitialized = new ArcanaAuthError('wallet_not_initialized', 'AuthProvider is not initialized. Please run `await auth.init(...)` before calling functions');
const WarningDupeIframe = new ArcanaAuthWarning('duplicate_iframe', 'Duplicate iframe detected, please keep a single instance of AuthProvider');
const LOG_LEVEL = {
DEBUG: 1,
INFO: 2,
WARNING: 3,
ERROR: 4,
NOLOGS: 5,
};
const setExceptionReporter = (reporter) => {
state.exceptionReporter = reporter;
};
const sendException = (msg) => {
if (state.exceptionReporter) {
state.exceptionReporter(msg);
}
};
const setLogLevel = (level) => {
state.logLevel = level;
};
const getLogger = () => {
return state.logger;
};
class Logger {
constructor() {
this.prefix = '[XAR_AUTH_SDK]';
}
info(message, params = {}) {
this.internalLog(LOG_LEVEL.INFO, message, params);
}
debug(message, params = {}) {
this.internalLog(LOG_LEVEL.DEBUG, message, params);
}
warn(message, params = {}) {
this.internalLog(LOG_LEVEL.WARNING, message, params);
}
error(message, err) {
if (err instanceof Error) {
this.internalLog(LOG_LEVEL.ERROR, message, err.message);
sendException(JSON.stringify({ message, error: err.message }));
return;
}
if (typeof err == 'string') {
this.internalLog(LOG_LEVEL.ERROR, message, err);
sendException(JSON.stringify({ message, error: err }));
}
}
internalLog(level, message, params) {
const logMessage = `${this.prefix}\nMessage: ${message} \nParams: ${JSON.stringify(params)}`;
this.consoleLog(level, logMessage);
}
consoleLog(level, message) {
if (level < state.logLevel) {
return;
}
switch (level) {
case LOG_LEVEL.DEBUG:
console.debug(message);
break;
case LOG_LEVEL.WARNING:
console.warn(message);
break;
case LOG_LEVEL.ERROR:
console.error(message);
break;
case LOG_LEVEL.INFO:
console.info(message);
break;
default:
console.log(message);
}
}
}
const state = {
logger: new Logger(),
logLevel: LOG_LEVEL.NOLOGS,
exceptionReporter: null,
};
class Popup {
constructor(url) {
this.url = url;
this.requestHandler = () => {
return new Promise((resolve) => {
let cleanExit = false;
const id = window.setInterval(() => {
var _a;
try {
if (!cleanExit && ((_a = this.window) === null || _a === void 0 ? void 0 : _a.closed)) {
return resolve({
id: 1,
jsonrpc: '2.0',
error: 'user_closed_popup',
});
}
// eslint-disable-next-line no-empty
}
catch (e) { }
}, 500);
const handler = (event) => __awaiter(this, void 0, void 0, function* () {
var _a;
if (event.data.type == 'json_rpc_response') {
cleanExit = true;
this.clear(handler, id);
(_a = this.window) === null || _a === void 0 ? void 0 : _a.close();
return resolve(event.data.response);
}
});
window.addEventListener('message', handler, false);
});
};
}
open() {
const windowFeatures = getWindowFeatures();
this.window = window.open(this.url, '_blank', windowFeatures);
return this.getWindowResponse();
}
getWindowResponse() {
return new Promise((resolve, reject) => {
let cleanExit = false;
const id = window.setInterval(() => {
var _a;
if (!cleanExit && ((_a = this.window) === null || _a === void 0 ? void 0 : _a.closed)) {
reject('User closed the popup');
}
}, 500);
const handler = (event) => __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
if (!((_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.status)) {
return;
}
const data = event.data;
cleanExit = true;
this.clear(handler, id);
if (data.status === 'success') {
(_b = this.window) === null || _b === void 0 ? void 0 : _b.close();
return resolve('success');
}
else if (data.status == 'error') {
(_c = this.window) === null || _c === void 0 ? void 0 : _c.close();
return reject(data.error);
}
else if (data.status === 'done') {
return resolve('done');
}
else {
console.log('Unexpected event');
}
});
window.addEventListener('message', handler, false);
});
}
clear(handler, id) {
window.removeEventListener('message', handler);
window.clearInterval(id);
}
}
const popupFeatures = {
titlebar: 0,
toolbar: 0,
status: 0,
menubar: 0,
resizable: 0,
height: 1200,
width: 700,
popup: 1,
};
const getWindowFeatures = () => {
const f = [];
for (const feature in popupFeatures) {
f.push(`${feature}=${popupFeatures[feature]}`);
}
return f.join(',');
};
class RequestPopupHandler {
constructor(url) {
this.url = url;
this.requestCount = 0;
this.emitter = new _default();
this.ready = false;
this.cleanExit = false;
this.requestHandler = (requestId) => {
return new Promise((resolve) => {
this.cleanExit = false;
const id = window.setInterval(() => {
var _a;
try {
if ((_a = this.window) === null || _a === void 0 ? void 0 : _a.closed) {
if (!this.cleanExit) {
this.emitter.emit(requestId, {
id: requestId,
jsonrpc: '2.0',
error: 'user_closed_popup',
});
}
window.clearInterval(id);
resolve('ok');
}
// eslint-disable-next-line no-empty
}
catch (e) { }
}, 500);
});
};
this.handler = (event) => __awaiter(this, void 0, void 0, function* () {
if (event.data.type == 'json_rpc_response') {
this.cleanExit = true;
this.emitter.emit(event.data.response.id, event.data.response);
}
});
}
sendRequest(r) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.window) {
this.ready = false;
this.requestCount = 0;
this.window = window.open(this.url, '_blank', getWindowFeatures());
yield waitForLoad();
window.addEventListener('message', this.handler, false);
}
if (this.window) {
this.requestCount++;
this.window.postMessage({ type: 'json_rpc_request', data: r }, this.url);
this.window.focus();
this.requestHandler(String(r.request.id));
const response = yield new Promise((resolve) => this.emitter.once(String(r.request.id), (response) => {
var _a;
this.requestCount--;
if (this.requestCount <= 0) {
window.removeEventListener('message', this.handler);
(_a = this.window) === null || _a === void 0 ? void 0 : _a.close();
this.window = null;
}
return resolve(response);
}));
return response;
}
else {
throw Error('error while opening popup');
}
});
}
}
const waitForLoad = () => {
return new Promise((resolve) => {
const handler = (ev) => {
if (ev.data.type === 'READY_TO_RECEIVE') {
window.removeEventListener('message', handler);
resolve('ok');
}
};
window.addEventListener('message', handler, false);
});
};
const ICONS = {
success: "data:image/svg+xml,%3Csvg width='151' height='147' viewBox='0 0 151 147' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cg opacity='0.419035'%3E%3Cpath d='M94.3585 4.39385C94.3585 6.8206 92.3736 8.78798 89.9253 8.78798C87.477 8.78798 85.4922 6.8206 85.4922 4.39385C85.4922 1.96723 87.477 0 89.9253 0C92.3736 0 94.3585 1.96723 94.3585 4.39385Z' fill='%233CA6FA'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M59.4441 15.3287L56.8114 16.8352C56.3347 17.108 55.7253 16.9461 55.4501 16.4737L50.6962 8.31243C50.421 7.84009 50.5844 7.23603 51.0609 6.96337L53.6938 5.45667C54.1703 5.184 54.7797 5.34582 55.055 5.81815L59.8088 13.9795C60.0841 14.452 59.9207 15.0559 59.4441 15.3287Z' fill='%233CA6FA'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M15.0339 32.3637L15.6261 32.5628C16.2975 32.7886 17.0381 32.6722 17.6065 32.2519L18.1077 31.8812C19.5388 30.8226 21.5735 31.8501 21.5507 33.6199L21.5427 34.2397C21.5336 34.9425 21.8739 35.6047 22.4528 36.0106L22.9635 36.3685C24.4215 37.3904 24.0642 39.6257 22.359 40.1512L21.7618 40.3352C21.0846 40.5438 20.5546 41.0694 20.3442 41.7405L20.1584 42.3325C19.6284 44.0226 17.3731 44.3766 16.342 42.9315L15.9807 42.4255C15.5713 41.8517 14.9032 41.5142 14.1942 41.5233L13.5688 41.5311C11.7833 41.5537 10.7467 39.5372 11.8147 38.1186L12.1888 37.6218C12.613 37.0586 12.7302 36.3245 12.5024 35.6589L12.3015 35.0719C11.7281 33.3957 13.3427 31.7954 15.0339 32.3637Z' fill='%233CA6FA'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M11.2466 63.5287L11.9116 66.4689C12.032 67.0012 11.6943 67.5295 11.1572 67.6487L1.87966 69.7101C1.34269 69.8293 0.809791 69.4946 0.689237 68.9623L0.0243071 66.0219C-0.0959554 65.4897 0.241739 64.9615 0.778708 64.8423L10.0564 62.7809C10.5933 62.6617 11.1262 62.9964 11.2466 63.5287Z' fill='%239DE000'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M20.6082 100.625C20.6082 103.052 18.6234 105.019 16.1752 105.019C13.7268 105.019 11.7422 103.052 11.7422 100.625C11.7422 98.1987 13.7268 96.2314 16.1752 96.2314C18.6234 96.2314 20.6082 98.1987 20.6082 100.625Z' fill='%23F23D3D'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M15.0339 122.725L15.6261 122.924C16.2975 123.15 17.0381 123.034 17.6065 122.613L18.1077 122.242C19.5388 121.184 21.5735 122.211 21.5507 123.981L21.5427 124.601C21.5336 125.304 21.8739 125.966 22.4528 126.372L22.9635 126.73C24.4215 127.752 24.0642 129.987 22.359 130.513L21.7618 130.697C21.0846 130.905 20.5546 131.431 20.3442 132.102L20.1584 132.694C19.6284 134.384 17.3731 134.738 16.342 133.293L15.9807 132.787C15.5713 132.213 14.9032 131.876 14.1942 131.885L13.5688 131.893C11.7833 131.915 10.7467 129.899 11.8147 128.48L12.1888 127.983C12.613 127.42 12.7302 126.686 12.5024 126.02L12.3015 125.433C11.7281 123.757 13.3427 122.157 15.0339 122.725Z' fill='%23FAEE3D'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M129.132 28.1704C127.789 26.435 128.205 23.8499 130.054 22.4436C131.903 21.0374 134.53 21.3082 135.873 23.0437C135.876 23.047 135.878 23.0503 135.881 23.0535' stroke='%23F23D3D' stroke-width='1.98137' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M140.862 52.2221L141.454 52.4212C142.126 52.647 142.866 52.5306 143.435 52.1103L143.936 51.7396C145.367 50.681 147.402 51.7085 147.379 53.4783L147.371 54.0981C147.362 54.8009 147.702 55.4631 148.281 55.869L148.792 56.2269C150.25 57.2488 149.893 59.4841 148.187 60.0096L147.59 60.1936C146.913 60.4022 146.383 60.9278 146.172 61.5989L145.986 62.1909C145.456 63.881 143.201 64.235 142.17 62.7899L141.809 62.2839C141.399 61.7101 140.732 61.3726 140.022 61.3817L139.397 61.3896C137.612 61.4121 136.575 59.3956 137.643 57.9771L138.017 57.4803C138.441 56.917 138.558 56.1829 138.33 55.5173L138.13 54.9303C137.556 53.2541 139.171 51.6538 140.862 52.2221Z' fill='%23FAEE3D'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M145.217 104.171C148.232 104.564 150.367 107.485 149.948 110.64C149.529 113.795 146.703 116.068 143.689 115.674C143.683 115.674 143.678 115.673 143.672 115.672' stroke='%23F23D3D' stroke-width='1.48603' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M135.718 141.235L133.085 142.742C132.608 143.014 131.999 142.852 131.724 142.38L126.97 134.219C126.694 133.746 126.858 133.142 127.334 132.87L129.967 131.363C130.444 131.09 131.053 131.252 131.328 131.724L136.082 139.886C136.357 140.358 136.194 140.962 135.718 141.235Z' fill='%233CA6FA'/%3E%3C/g%3E%3Cg opacity='0.796078'%3E%3Cpath d='M49.4302 146.001C47.5793 143.61 48.1523 140.048 50.6998 138.111C53.2472 136.174 56.8664 136.547 58.7173 138.938L58.7279 138.951' stroke='%233CA6FA' stroke-width='1.98137' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/g%3E%3Cpath d='M133.141 69.8273C133.141 98.8525 109.4 122.382 80.1137 122.382C50.8274 122.382 27.0859 98.8525 27.0859 69.8273C27.0859 40.802 50.8274 17.2725 80.1137 17.2725C109.4 17.2725 133.141 40.802 133.141 69.8273Z' fill='%239DE000'/%3E%3Cpath d='M56.6641 69.9175L72.2097 85.3247L103.481 54.332' stroke='white' stroke-width='5.7388' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E%0A",
fail: "data:image/svg+xml,%3Csvg width='116' height='116' viewBox='0 0 116 116' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M115.341 58.0094C115.341 89.6796 89.6673 115.354 57.9967 115.354C26.3265 115.354 0.652344 89.6796 0.652344 58.0094C0.652344 26.3392 26.3265 0.665039 57.9967 0.665039C89.6673 0.665039 115.341 26.3392 115.341 58.0094Z' fill='%23B43030'/%3E%3Cpath d='M78.7969 37.2041L37.1953 78.8057' stroke='white' stroke-width='5.74' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M78.7969 78.8057L37.1953 37.2041' stroke='white' stroke-width='5.74' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E%0A",
};
const createDomElement = (type, props, ...children) => {
const dom = document.createElement(type);
if (props) {
Object.assign(dom, props);
if (props.style)
Object.assign(dom.style, props.style);
}
for (const child of children) {
if (typeof child != 'string')
dom.appendChild(child);
else
dom.appendChild(document.createTextNode(child));
}
return dom;
};
const getErrorReporter = () => {
return (msg) => {
console.error(msg);
};
};
const isDefined = (arg) => arg !== undefined && arg !== null;
const isValidString = (arg) => typeof arg === 'string' && arg.trim().length > 0;
const isAddressLike = (arg) => removeHexPrefix(arg).length === 40;
const validateAppAddress = (arg) => {
if (!isDefined(arg)) {
throw new Error('appAddress is required');
}
if (!isValidString(arg)) {
throw new Error('appAddress is required to be a non-empty string');
}
if (!isAddressLike(arg)) {
throw new Error('appAddress is required to be an ethereum address');
}
};
const CLIENT_ID_SEPERATOR = '_';
const isClientId = (id) => {
if (!isValidString(id)) {
throw new ArcanaAuthError('invalid_client_id', 'Invalid Client ID');
}
const parts = id.split(CLIENT_ID_SEPERATOR);
return parts.length == 3;
};
const getParamsFromClientId = (id) => {
const parts = id.split(CLIENT_ID_SEPERATOR);
const [, networkHint, address] = parts;
if (!isAddressLike(address)) {
throw new Error(`Invalid ClientId`);
}
if (networkHint == 'live') {
return { network: 'mainnet', address };
}
else if (networkHint == 'test') {
return { network: 'testnet', address };
}
else if (networkHint == 'dev') {
return { network: 'dev', address };
}
else {
throw new Error(`Invalid ClientId`);
}
};
const HEX_PREFIX = '0x';
const addHexPrefix = (i) => i.startsWith(HEX_PREFIX) ? i : HEX_PREFIX + i;
const removeHexPrefix = (i) => i.startsWith(HEX_PREFIX) ? i.substring(2) : i;
const getHexFromNumber = (n, prefix = true) => {
const h = n.toString(16);
return prefix ? addHexPrefix(h) : removeHexPrefix(h);
};
const getCurrentUrl = () => {
const url = window.location.origin + window.location.pathname;
return url;
};
const getConstructorParams = (initParams) => {
var _a;
const p = {
network: 'testnet',
debug: false,
position: 'right',
theme: 'dark',
alwaysVisible: true,
setWindowProvider: false,
useEIP6963: false,
connectOptions: {
compact: false,
},
};
if (initParams === null || initParams === void 0 ? void 0 : initParams.network) {
p.network = initParams.network;
}
if ((initParams === null || initParams === void 0 ? void 0 : initParams.debug) !== undefined) {
p.debug = initParams.debug;
}
if (initParams === null || initParams === void 0 ? void 0 : initParams.theme) {
p.theme = initParams.theme;
}
if (initParams === null || initParams === void 0 ? void 0 : initParams.position) {
p.position = initParams.position;
}
if ((initParams === null || initParams === void 0 ? void 0 : initParams.alwaysVisible) !== undefined) {
p.alwaysVisible = initParams.alwaysVisible;
}
if (((_a = initParams === null || initParams === void 0 ? void 0 : initParams.connectOptions) === null || _a === void 0 ? void 0 : _a.compact) !== undefined) {
p.connectOptions.compact = initParams.connectOptions.compact;
}
if ((initParams === null || initParams === void 0 ? void 0 : initParams.useEIP6963) !== undefined) {
p.useEIP6963 = initParams.useEIP6963;
}
if (p.network == 'testnet' || p.network == 'dev') {
console.log(`%c[XAR_AUTH_SDK] You are currently on ${p.network} network.`, 'color: red');
}
return p;
};
const MAX = 4294967295;
let idCounter = Math.floor(Math.random() * MAX);
const getUniqueId = () => {
idCounter = (idCounter + 1) % MAX;
return idCounter;
};
function preLoadIframe(url, appId) {
try {
if (typeof document === 'undefined')
return;
const iframeLink = document.createElement('link');
iframeLink.href = `${url}/${appId}/v2/login`;
iframeLink.type = 'text/html';
iframeLink.rel = 'prefetch';
document.head.appendChild(iframeLink);
}
catch (error) {
console.warn(error);
}
}
/**
* @source https://github.com/blakeembrey/universal-base64/blob/master/src/browser.ts
*/
function btoaUTF8(str) {
return window.btoa(encodeURIComponent(str).replace(/%[0-9A-F]{2}/g, percentToByte));
}
function percentToByte(p) {
return String.fromCharCode(parseInt(p.slice(1), 16));
}
function encodeJSON(options) {
return btoaUTF8(JSON.stringify(options));
}
function onWindowReady(fn) {
if (document.readyState === 'complete') {
fn();
}
else {
window.addEventListener('load', fn);
}
}
class ProviderError extends Error {
constructor(code, message, data = '') {
super(message);
this.code = code;
this.message = message;
this.data = data;
}
}
class ArcanaProvider extends _default {
constructor(authUrl) {
super();
this.authUrl = authUrl;
this.connected = false;
this.logger = getLogger();
this.onResponse = (method, response) => {
this.subscriber.emit(`result:${method}:${response.id}`, response);
};
this.handleEvents = (t, val) => {
switch (t) {
case EVENTS.ACCOUNTS_CHANGED:
this.emit(t, [val]);
break;
case EVENTS.CHAIN_CHANGED:
this.setChainId(val);
this.emit(t, getHexFromNumber(val.chainId));
break;
case EVENTS.CONNECT:
this.chainId =
typeof val === 'object' ? val.chainId : '';
this.connected = true;
this.emit(t, val);
break;
case EVENTS.DISCONNECT:
this.iframe.handleDisconnect();
this.connected = false;
this.emit(t, val);
break;
case EVENTS.MESSAGE:
console.log({ t, val });
this.emit(t, val);
break;
}
};
this.subscriber = new _default();
}
isArcana() {
return true;
}
init(iframe, auth) {
return __awaiter(this, void 0, void 0, function* () {
this.auth = auth;
this.popup = new RequestPopupHandler(this.createRequestUrl(auth.appId));
this.iframe = iframe;
const { communication } = yield this.iframe.setConnectionMethods({
onEvent: this.handleEvents,
onMethodResponse: this.onResponse,
getParentUrl: getCurrentUrl,
getAppMode: () => this.iframe.appMode,
getAppConfig: this.iframe.getAppConfig,
getWalletPosition: this.iframe.getWalletPlace,
getRpcConfig: () => undefined,
sendPendingRequestCount: this.iframe.onReceivingPendingRequestCount,
triggerSocialLogin: auth.loginWithSocial,
triggerPasswordlessLogin: auth.loginWithLink,
getPopupState: () => this.iframe.getState(),
setIframeStyle: this.iframe.setIframeStyle,
setSessionID: this.iframe.setSessionID,
getSDKVersion: () => 'v3',
});
this.communication = communication;
});
}
isLoggedIn() {
return __awaiter(this, void 0, void 0, function* () {
try {
const c = yield this.getCommunication('isLoggedIn');
return c.isLoggedIn();
}
catch (e) {
this.logger.error('isLoggedIn', e);
return false;
}
});
}
connect() {
return this.auth.connect();
}
isConnected() {
return __awaiter(this, void 0, void 0, function* () {
return this.connected;
});
}
isLoginAvailable(type) {
return __awaiter(this, void 0, void 0, function* () {
const c = yield this.getCommunication('isLoginAvailable');
const available = yield c.isLoginAvailable(type);
this.logger.debug('loginAvailable', { [type]: available });
return available;
});
}
initCustomLogin(params) {
return __awaiter(this, void 0, void 0, function* () {
const c = yield this.getCommunication('triggerCustomLogin');
return yield c.triggerCustomLogin(params);
});