@sixnetwork/klip-connector
Version:
A simple, maximally extensible, dependency minimized framework for building modern Klaytn dApps
724 lines (589 loc) • 19.8 kB
JavaScript
import { AbstractConnector } from '@sixnetwork/caverjs-react-abstract-connector';
import QRcode from 'qrcode';
import axios from 'axios';
import { isMobile } from 'react-device-detect';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var KlipProvider = /*#__PURE__*/function () {
function KlipProvider() {
var _this2 = this,
_this3 = this;
var _this = this;
this.account = "";
this.initData = function () {
_this.requestKey = "";
_this.responseData = undefined;
};
this.login = function () {
_this.isAuth = true;
};
this.logout = function () {
_this.isAuth = false;
};
this.getAuth = function () {
return _this.isAuth;
};
this.genQRcode = function (showModal) {
_this.initData();
var mockData = {
bapp: {
name: 'definix'
},
type: 'auth'
};
axios.post('https://a2a-api.klipwallet.com/v2/a2a/prepare', mockData).then(function (response) {
try {
_this.requestKey = response.data.request_key;
var _temp2 = function () {
if (isMobile) {
_this.intervalCheckResult = setInterval(_this.getResult, 1000);
_this.openDeeplink("https://klipwallet.com/?target=/a2a?request_key=" + response.data.request_key);
} else {
return Promise.resolve(showModal()).then(function () {
return Promise.resolve(QRcode.toCanvas(document.getElementById('qrcode'), "https://klipwallet.com/?target=/a2a?request_key=" + response.data.request_key, function () {
_this.intervalCheckResult = setInterval(_this.getResult, 1000);
})).then(function () {});
});
}
}();
return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(function () {}) : void 0);
} catch (e) {
return Promise.reject(e);
}
});
};
this.getResult = function () {
try {
var url = "https://a2a-api.klipwallet.com/v2/a2a/result?request_key=" + _this2.requestKey;
return Promise.resolve(axios.get(url)).then(function (res) {
if (res.data.status == "completed") {
_this2.account = res.data.result.klaytn_address;
_this2.responseData = res.data.result.klaytn_address;
if (_this2.intervalCheckResult) clearInterval(_this2.intervalCheckResult);
}
});
} catch (e) {
return Promise.reject(e);
}
};
this.getAccount = function () {
return _this.account;
};
this.getRequestKey = function () {
return _this.requestKey;
};
this.checkResponse = function () {
try {
return Promise.resolve(new Promise(function (resolve) {
var interCheck = setInterval(function () {
if (_this3.responseData != undefined) {
clearInterval(interCheck);
resolve(_this3.responseData);
}
}, 1000);
}));
} catch (e) {
return Promise.reject(e);
}
};
this.genQRcodeContactInteract = function (contractAddress, abi, input) {
_this.initData();
var mockData = {
"bapp": {
"name": "definix"
},
"type": "execute_contract",
"transaction": {
"to": contractAddress,
"value": "0",
"abi": abi,
"params": input
}
};
axios.post('https://a2a-api.klipwallet.com/v2/a2a/prepare', mockData).then(function (response) {
_this.requestKey = response.data.request_key;
QRcode.toCanvas(document.getElementById('qrcode'), "https://klipwallet.com/?target=/a2a?request_key=" + response.data.request_key, function () {
_this.intervalCheckResult = setInterval(_this.getResult, 1000);
});
});
};
this.openDeeplink = function (url) {
var checkRedirect = window.open(url, "_blank");
if (checkRedirect === null) {
window.location.href = "kakaotalk://klipwallet/open?url=" + url;
setTimeout(function () {
if (document.hasFocus()) {
window.location.replace("https://apps.apple.com/kr/app/%EC%B9%B4%EC%B9%B4%EC%98%A4%ED%86%A1-kakaotalk/id362057947");
}
}, 4500);
}
};
this.isAuth = false;
this.requestKey = '';
this.responseData = undefined;
}
var _proto = KlipProvider.prototype;
_proto.Popup = function Popup() {
var myDialog = document.createElement("dialog");
document.body.appendChild(myDialog);
var text = document.createTextNode("This is a dialog window");
myDialog.appendChild(text);
myDialog.showModal();
};
return KlipProvider;
}();
// A type of promise-like that resolves synchronously and supports only one observer
var _Pact = /*#__PURE__*/function () {
function _Pact() {}
_Pact.prototype.then = function (onFulfilled, onRejected) {
var result = new _Pact();
var state = this.s;
if (state) {
var callback = state & 1 ? onFulfilled : onRejected;
if (callback) {
try {
_settle(result, 1, callback(this.v));
} catch (e) {
_settle(result, 2, e);
}
return result;
} else {
return this;
}
}
this.o = function (_this) {
try {
var value = _this.v;
if (_this.s & 1) {
_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
} else if (onRejected) {
_settle(result, 1, onRejected(value));
} else {
_settle(result, 2, value);
}
} catch (e) {
_settle(result, 2, e);
}
};
return result;
};
return _Pact;
}(); // Settles a pact synchronously
function _settle(pact, state, value) {
if (!pact.s) {
if (value instanceof _Pact) {
if (value.s) {
if (state & 1) {
state = value.s;
}
value = value.v;
} else {
value.o = _settle.bind(null, pact, state);
return;
}
}
if (value && value.then) {
value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
return;
}
pact.s = state;
pact.v = value;
var observer = pact.o;
if (observer) {
observer(pact);
}
}
}
function _isSettledPact(thenable) {
return thenable instanceof _Pact && thenable.s & 1;
} // Converts argument to a function that always returns a Promise
function _forTo(array, body, check) {
var i = -1,
pact,
reject;
function _cycle(result) {
try {
while (++i < array.length && (!check || !check())) {
result = body(i);
if (result && result.then) {
if (_isSettledPact(result)) {
result = result.v;
} else {
result.then(_cycle, reject || (reject = _settle.bind(null, pact = new _Pact(), 2)));
return;
}
}
}
if (pact) {
_settle(pact, 1, result);
} else {
pact = result;
}
} catch (e) {
_settle(pact || (pact = new _Pact()), 2, e);
}
}
_cycle();
return pact;
} // Asynchronously iterate through an object's properties (including properties inherited from the prototype)
var _iteratorSymbol = /*#__PURE__*/typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = /*#__PURE__*/Symbol("Symbol.iterator")) : "@@iterator"; // Asynchronously iterate through an object's values
// Uses for...of if the runtime supports it, otherwise iterates until length on a copy
function _forOf(target, body, check) {
if (typeof target[_iteratorSymbol] === "function") {
var _cycle = function _cycle(result) {
try {
while (!(step = iterator.next()).done && (!check || !check())) {
result = body(step.value);
if (result && result.then) {
if (_isSettledPact(result)) {
result = result.v;
} else {
result.then(_cycle, reject || (reject = _settle.bind(null, pact = new _Pact(), 2)));
return;
}
}
}
if (pact) {
_settle(pact, 1, result);
} else {
pact = result;
}
} catch (e) {
_settle(pact || (pact = new _Pact()), 2, e);
}
};
var iterator = target[_iteratorSymbol](),
step,
pact,
reject;
_cycle();
if (iterator["return"]) {
var _fixup = function _fixup(value) {
try {
if (!step.done) {
iterator["return"]();
}
} catch (e) {}
return value;
};
if (pact && pact.then) {
return pact.then(_fixup, function (e) {
throw _fixup(e);
});
}
_fixup();
}
return pact;
} // No support for Symbol.iterator
if (!("length" in target)) {
throw new TypeError("Object is not iterable");
} // Handle live collections properly
var values = [];
for (var i = 0; i < target.length; i++) {
values.push(target[i]);
}
return _forTo(values, function (i) {
return body(values[i]);
}, check);
}
var _asyncIteratorSymbol = /*#__PURE__*/typeof Symbol !== "undefined" ? Symbol.asyncIterator || (Symbol.asyncIterator = /*#__PURE__*/Symbol("Symbol.asyncIterator")) : "@@asyncIterator"; // Asynchronously iterate on a value using it's async iterator if present, or its synchronous iterator if missing
function _catch(body, recover) {
try {
var result = body();
} catch (e) {
return recover(e);
}
if (result && result.then) {
return result.then(void 0, recover);
}
return result;
} // Asynchronously await a promise and pass the result to a finally continuation
var RPCS = ["https://klaytn-en.sixnetwork.io:8651/", "https://kaikas.cypress.klaytn.net:8651/", "https://kaikas.cypress.klaytn.net:8651/"];
var checkHeartBeat = function checkHeartBeat(rpc) {
try {
return Promise.resolve(new Promise(function (reslove) {
axios.get(rpc).then(function (res) {
reslove(res.status);
})["catch"](function (error) {
if (error.response) {
reslove(error.response.status);
}
});
}));
} catch (e) {
return Promise.reject(e);
}
};
var checkHeartBeatStatue = function checkHeartBeatStatue(status) {
return status === 200;
};
var getRPCurlIsWorking = function getRPCurlIsWorking() {
try {
var _exit2 = false;
var _temp2 = _forOf(RPCS, function (rpc) {
return Promise.resolve(checkHeartBeat(rpc)).then(function (status) {
if (checkHeartBeatStatue(status)) {
_exit2 = true;
return rpc;
}
});
}, function () {
return _exit2;
});
return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(function (_result) {
return _exit2 ? _result : "all node rpc not work";
}) : _exit2 ? _temp2 : "all node rpc not work");
} catch (e) {
return Promise.reject(e);
}
};
var getRPCurl = function getRPCurl() {
return Promise.resolve(_catch(getRPCurlIsWorking, function () {
return ""; // all rpc is die
}));
};
var Caver = /*#__PURE__*/require("caver-js");
var NoKlaytnProviderError = /*#__PURE__*/function (_Error) {
_inheritsLoose(NoKlaytnProviderError, _Error);
function NoKlaytnProviderError() {
var _this;
_this = _Error.call(this) || this;
_this.name = _this.constructor.name;
_this.message = 'No Klaytn provider was found on window.klaytn.';
return _this;
}
return NoKlaytnProviderError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
var UserRejectedRequestError = /*#__PURE__*/function (_Error2) {
_inheritsLoose(UserRejectedRequestError, _Error2);
function UserRejectedRequestError() {
var _this2;
_this2 = _Error2.call(this) || this;
_this2.name = _this2.constructor.name;
_this2.message = 'The user rejected the request.';
return _this2;
}
return UserRejectedRequestError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
var KlipConnector = /*#__PURE__*/function (_AbstractConnector) {
_inheritsLoose(KlipConnector, _AbstractConnector);
function KlipConnector(kwargs) {
var _this3;
_this3 = _AbstractConnector.call(this, kwargs) || this;
_this3.showModal = kwargs.showModal;
_this3.closeModal = kwargs.closeModal;
_this3.handleNetworkChanged = _this3.handleNetworkChanged.bind(_assertThisInitialized(_this3));
_this3.handleChainChanged = _this3.handleChainChanged.bind(_assertThisInitialized(_this3));
_this3.handleAccountsChanged = _this3.handleAccountsChanged.bind(_assertThisInitialized(_this3));
_this3.handleClose = _this3.handleClose.bind(_assertThisInitialized(_this3)); // provider
// this.providerCaver = window.klaytn
return _this3;
}
var _proto = KlipConnector.prototype;
_proto.handleChainChanged = function handleChainChanged(chainId) {
if (process.env.NODE_ENV !== "production") {
console.log("Handling 'chainChanged' event with payload", chainId);
}
this.emitUpdate({
chainId: chainId,
provider: this.providerCaver
});
};
_proto.handleAccountsChanged = function handleAccountsChanged(accounts) {
if (process.env.NODE_ENV !== "production") {
console.log("Handling 'accountsChanged' event with payload", accounts);
}
if (accounts.length === 0) {
this.emitDeactivate();
} else {
this.emitUpdate({
account: accounts[0]
});
}
};
_proto.handleClose = function handleClose(code, reason) {
if (process.env.NODE_ENV !== "production") {
console.log("Handling 'close' event with payload", code, reason);
}
this.emitDeactivate();
};
_proto.handleNetworkChanged = function handleNetworkChanged(networkId) {
if (process.env.NODE_ENV !== "production") {
console.log("Handling 'networkChanged' event with payload", networkId);
}
this.emitUpdate({
chainId: networkId,
provider: this.providerCaver
});
};
_proto.activate = function activate() {
try {
var _this5 = this;
// if (window.klaytn.on) {
// window.klaytn.on('chainChanged', this.handleChainChanged)
// window.klaytn.on('accountsChanged', this.handleAccountsChanged)
// window.klaytn.on('close', this.handleClose)
// window.klaytn.on('networkChanged', this.handleNetworkChanged)
// }
return Promise.resolve(getRPCurl()).then(function (_getRPCHelper) {
function _temp3() {
return _extends({
provider: _this5.providerCaver
}, account ? {
account: account
} : {});
}
_this5.providerCaver = new Caver(_getRPCHelper).currentProvider;
_this5.KlipConnectorProvider = new KlipProvider();
var account;
if (localStorage.getItem("connector") == "klip" && localStorage.getItem("userAccount")) {
account = localStorage.getItem("userAccount");
_this5.KlipConnectorProvider.login();
}
var _temp2 = function () {
if (localStorage.getItem("connector")) {
var _temp4 = function () {
if (!account) {
_this5.KlipConnectorProvider.genQRcode(_this5.showModal);
return Promise.resolve(_this5.KlipConnectorProvider.checkResponse()).then(function (_this4$KlipConnectorP) {
account = _this4$KlipConnectorP;
localStorage.setItem("userAccount", account);
_this5.closeModal();
_this5.KlipConnectorProvider.login();
});
}
}();
if (_temp4 && _temp4.then) return _temp4.then(function () {});
}
}();
return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2);
});
} catch (e) {
return Promise.reject(e);
}
};
_proto.getProvider = function getProvider() {
try {
var _this7 = this;
return Promise.resolve(_this7.providerCaver);
} catch (e) {
return Promise.reject(e);
}
};
_proto.getChainId = function getChainId() {
return Promise.resolve(8217);
};
_proto.getAccount = function getAccount() {
try {
var _this9 = this;
return Promise.resolve(_this9.KlipConnectorProvider.getAccount());
} catch (e) {
return Promise.reject(e);
}
};
_proto.deactivate = function deactivate() {
this.KlipConnectorProvider.logout();
};
_proto.isAuthorized = function isAuthorized() {
try {
var _this11 = this;
return Promise.resolve(_this11.KlipConnectorProvider.getAuth());
} catch (e) {
return Promise.reject(e);
}
};
return KlipConnector;
}(AbstractConnector);
export { KlipConnector, NoKlaytnProviderError, UserRejectedRequestError };
//# sourceMappingURL=klip-connector.esm.js.map