UNPKG

glip-wallet-sdk

Version:

Guide for installation and usage of Glip's Web3 Wallet.\ Glip Wallet through its SDK provides a signer using which a user's transaction can be signed.\ It also contains a iframe based UI element which can be embedded into any webpage.\ The UI contains

325 lines (324 loc) 13.2 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getGlipWallet = exports.glipWalletSDK = void 0; const react_1 = __importDefault(require("react")); const client_1 = require("react-dom/client"); const socket_io_client_1 = require("socket.io-client"); const Main_1 = __importDefault(require("./components/Main")); const Signer_1 = __importDefault(require("./sub_modules/Signer")); const internalProviderService_1 = require("./internalProviderService"); const uuid_1 = require("uuid"); const WEB_SOCKET_URI = 'https://be.namasteapis.com/wallet'; function createLoginModal(glipWallet) { const root = (0, client_1.createRoot)(document.getElementById("glip-wallet")); root.render(react_1.default.createElement(react_1.default.StrictMode, null, react_1.default.createElement(Main_1.default, { glipWallet: glipWallet }))); } const GLIP_WALLET_BASE_URL = `https://glip.gg/wallet-host/`; const GLIP_WALLET_IFRAME_URL = `https://glip.gg/wallet-host/`; const GLIP_WALLET_LOGIN_URL = `https://glip.gg/wallet-login/`; class GlipWallet { constructor() { this.chainId = 1; this.authNetwork = ''; this.clientIdentifier = ''; this.onLoginChange = () => { }; this.iWin = false; this.iframeInitialized = false; this.initOngoing = false; this.socketUUID = ''; this.createWalletDiv(); window.onmessage = (e) => { this.handleMessage(e); }; this.initializeWebSocket(); // first just set to null // initialize when signer first requested and only // if user is loggedin. this.glipSigner = null; } initializeWebSocket() { // create a new uuid const uuid = (0, uuid_1.v4)(); this.socketUUID = uuid; const socket = (0, socket_io_client_1.io)(WEB_SOCKET_URI, { transports: ['websocket'], query: { roomId: uuid } }); this.connectedSocket = socket; socket.on('connect', () => { socket.on('message', async (data) => { let parsedData = JSON.parse(data.data); if (parsedData.type === "signedTransactionRetVal") { (await this.getSigner()).handleTransactionResponse(parsedData); } if (parsedData.type === "signedMessageRetVal") { (await this.getSigner()).handleMessageResponse(parsedData); } if (parsedData.type === "loginDone") { this.loginDoneCB(parsedData.address); } }); socket.on('data', (data) => { console.log('data', data); }); socket.on('error', function (data) { console.log('socket error', data); }); socket.on('close', function (data) { console.log('socket close', data); }); socket.on('connect_error', function (err) { console.log("socket connect_error: ", err); }); socket.on('connect_timeout', function (err) { console.log("socket connect_timeout: ", err); }); }); } init({ chainId, authNetwork, clientIdentifier }) { //init could be called before iframe has full loaded if (this.initOngoing) { return this.globalInitPromise; } this.chainId = chainId; this.authNetwork = authNetwork; this.clientIdentifier = clientIdentifier; this.initOngoing = true; const that = this; let initPromise = new Promise(function (resolve, reject) { that.initCB = resolve; that.initRejectCB = reject; that.initInternal(); }); this.globalInitPromise = initPromise; return this.globalInitPromise; } initInternal() { if (this.iframeInitialized) { this.iWin.postMessage({ call: 'init', params: { chain: this.chainId, authNetwork: this.authNetwork, clientIdentifier: this.clientIdentifier } }, '*'); } } async getAddress() { let userInfo = await this.getUserInfo(); return userInfo.publicAddress; } async getBalance() { if (!this.provider) { this.provider = await this.getProvider(); } if (await this.isConnected()) { console.log('getBalance', this.provider); return this.provider.getBalance(await this.getAddress()); } return 0; } _createIframe(iframeContainerDiv) { this.walletIframe = document.createElement('iframe'); this.walletIframe.style.display = "none"; this.walletIframe.style.display = "relative"; this.walletIframe.src = GLIP_WALLET_IFRAME_URL; const that = this; this.walletIframe.onload = () => { that.iWin = this.walletIframe.contentWindow || this.walletIframe; that.iframeInitialized = true; if (that.initOngoing) { that.initInternal(); } }; iframeContainerDiv.appendChild(this.walletIframe); } createWalletDiv() { //create a fixed div into html but keep it hidden initially const walletDiv = document.createElement('div'); walletDiv.id = "glip-wallet-container"; walletDiv.style.display = "none"; walletDiv.style.position = "fixed"; walletDiv.style.top = "0"; walletDiv.style.right = "0"; walletDiv.style.zIndex = "2323123"; this.walletDiv = walletDiv; // insert div into top of body. document.body.insertBefore(walletDiv, document.body.firstChild); this.walletDiv.innerHTML = "<img src='https://live-nft-hosted-assets.s3.ap-south-1.amazonaws.com/cancel_icon.svg' style='position:absolute;left: -20px;background: black;padding: 3px;border-radius:50%' onclick='window.glipWalletSDK.hideWallet()'/>"; this._createIframe(walletDiv); } showWallet() { this.walletDiv.style.display = "block"; this.walletIframe.style.display = "block"; // Set height and width of the iframe to 600x341 this.walletIframe.style.height = "600px"; this.walletIframe.style.width = "341px"; this.walletIframe.style.border = "0px"; this.walletIframe.style.borderRadius = "3%"; } ; hideWallet() { console.log('hide wallet'); this.walletDiv.style.display = "none"; this.walletIframe.style.display = "none"; } ; showConnectModal() { createLoginModal(this); } login(loginType, lastLocation, opts) { if (!opts) { opts = {}; } if (loginType === 'google') { const glipRedirectURL = `https://glip.gg/wallet-login/`; const glipGoogleOpts = { 'scope': 'https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email', 'redirect_uri': glipRedirectURL, client_id: '373196446500-ojt3ko1ghis9pritfhhogohlotut2hv6.apps.googleusercontent.com', }; const currState = { lastLocation: lastLocation, clientIdentifier: this.clientIdentifier, socketUUID: this.socketUUID }; if (opts.isMobileSDK) { //delete socketUUID from currState delete currState['socketUUID']; } const currOpts = glipGoogleOpts; let currStateString = JSON.stringify(currState); //url encode the state currStateString = encodeURIComponent(currStateString); const GOOGLE_OAUTH_URL = `https://accounts.google.com/o/oauth2/v2/auth?scope=${currOpts['scope']}&response_type=code&redirect_uri=${currOpts.redirect_uri}&client_id=${glipGoogleOpts.client_id}&access_type=offline&state=${currStateString}`; return new Promise((resolve, reject) => { this.loginDoneCB = resolve; this.loginDoneCBRejected = reject; if (opts.isMobileSDK) { window.open(GOOGLE_OAUTH_URL, '_self'); return; } window.open(GOOGLE_OAUTH_URL, '_blank').focus(); }); //window.location.href = GOOGLE_OAUTH_URL; } return; } getUserInfo() { const that = this; return new Promise(function (resolve, reject) { that.getUserInfoCB = resolve; that.getUserInfoRejectCB = reject; that.iWin.postMessage({ call: 'getUserInfo', params: {} }, '*'); }); } isConnected() { const that = this; return new Promise(function (resolve, reject) { that.isConnectedCB = resolve; that.isConnectedRejectedCB = reject; that.iWin.postMessage({ call: 'isConnected', params: {} }, '*'); }); } getWalletID() { const that = this; return new Promise(function (resolve, reject) { that.getWalletIDCB = resolve; that.getWalletIdRejectCB = reject; that.iWin.postMessage({ call: 'getWalletID', params: {} }, '*'); }); } logout() { const that = this; return new Promise(function (resolve, reject) { that.logoutCB = resolve; that.logoutRejectedCB = reject; that.iWin.postMessage({ call: 'logout', params: {} }, '*'); }); } _loginWithIdToken({ loginType, userInfo, verifier }) { let GLIP_WALLET_BASE_URL = 'http://127.0.0.1:8080/'; window.location = `${GLIP_WALLET_BASE_URL}#loginType=${loginType}&chain=${this.chainId}&verifier=${verifier}&id=${userInfo.id}&idToken=${userInfo.idToken}&clientIdentifier=${this.clientIdentifier}&accessToken=${userInfo.accessToken}`; } // handles messages from the iFrame handleMessage(event) { if (event.data.call === "getUserInfo") { if (event.data.errorVal) { this.getUserInfoRejectCB(event.data.errorVal); } this.getUserInfoCB(event.data.retVal); } else if (event.data.call === "init") { // resetting initcalled this.initOngoing = false; this.initCB(event.data.retVal); } else if (event.data.call === "getWalletID") { this.getWalletIDCB(event.data.retVal); } else if (event.data.call === "isConnected") { this.isConnectedCB(event.data.retVal); } else if (event.data.call === "logout") { this.logoutCB(event.data.retVal); } } async getProvider() { const provider = await (0, internalProviderService_1.getInternalProvider)(this.chainId); return provider; } async getSigner(provider) { if (this.glipSigner) { return this.glipSigner; } let isConnected = await this.isConnected(); console.log('provider1', provider); if (!provider) { provider = await this.getProvider(); if (!this.provider) { this.provider = provider; } console.log('provider2', provider); } console.log('provider3', provider); if (isConnected) { let userInfo = await this.getUserInfo(); this.glipSigner = new Signer_1.default(userInfo.publicAddress, GLIP_WALLET_BASE_URL, false, this.chainId, this.socketUUID, provider); return this.glipSigner; } else { throw ("Need to be signed in to get signer"); } } async getSignedTransaction() { const urlParams = new URLSearchParams(window.location.search); let signedTransactionApproved = urlParams.get('action'); if (signedTransactionApproved === 'approve') { let signedTransaction = urlParams.get('signedTransaction'); return signedTransaction; } else { return false; } } } let initializedGlipWallet = false; const getGlipWallet = async (chainId, authNetwork, clientIdentifier) => { if (initializedGlipWallet) { return initializedGlipWallet; } await glipWalletSDK.init({ chainId: chainId, authNetwork: authNetwork, clientIdentifier: clientIdentifier, }); initializedGlipWallet = glipWalletSDK; return glipWalletSDK; }; exports.getGlipWallet = getGlipWallet; let glipWalletSDK = new GlipWallet(); exports.glipWalletSDK = glipWalletSDK; window.glipWalletSDK = glipWalletSDK;