@eternl/cardano-dapp-connector-bridge
Version:
A postMessage bridge to connect dApps to the Eternl DApp Browser loading apps into an iframe.
2 lines (1 loc) • 2.4 kB
JavaScript
function initCardanoDAppConnectorBridge(e){var n="DAppConnectorBridge: ",a=null,r=null,t={type:"cardano-dapp-connector-bridge",source:null,origin:null},o={},i={connect:"connect",handshake:"handshake",enable:"enable",isEnabled:"isEnabled"};function d(e){var n=[...arguments];return n.length>0&&n.shift(),new Promise((r,i)=>{var d={payload:{type:t.type,to:a,uid:("000"+(46656*Math.random()|0).toString(36)).slice(-3)+("000"+(46656*Math.random()|0).toString(36)).slice(-3),method:e,args:n},resolve:r,reject:i};o[d.payload.uid]=d,t.source.postMessage(d.payload,t.origin)})}function c(e){return function(){return d(e,...arguments)}}function s(e){var n={};for(var a in e){var r=e[a];"string"==typeof r?"feeAddress"===a?n[a]=r:(n[a]=c(r),i[r]=r):n[a]="object"==typeof r?s(r):r}return n}function l(e){if(!r){if(e.data.method!==i.connect)return console.error("Error: "+n+"send 'connect' first."),!1;var o=e.data.initialApi;if(!(o&&o.isBridge&&o.apiVersion&&o.name))return console.error("Error: "+n+"'connect' is missing correct initialApi.",o),!1;if(!e.data.walletNamespace)return console.error("Error: "+n+"'connect' is missing walletNamespace.",e.data.walletNamespace),!1;r=function(e,r,o,i){if(window.hasOwnProperty("cardano")||(window.cardano={}),window.cardano.hasOwnProperty(o))return console.warn("Warn: "+n+"window.cardano."+o+" already present, skipping initialApi creation."),null;t.source=e,t.origin=r,a=o;var c={isBridge:!0,isEnabled:function(){return d("isEnabled")},enable:function(){return d("enable")},apiVersion:i.apiVersion,name:i.name,icon:i.icon?i.icon:null,experimental:{}};return window.cardano[o]=c,i.experimental&&(c.experimental={...s(i.experimental)}),window.cardano[o]}(e.source,e.origin,e.data.walletNamespace,o)}return!(!r||!window.hasOwnProperty("cardano")||window.cardano[e.data.walletNamespace]!==r)||(console.warn("Warn: "+n+"bridge not set up correctly:",t,r,a),!1)}window.addEventListener("message",async function(n){if(function(e){return!(!(e.data&&e.origin&&e.source)||e.data.type!==t.type||!i.hasOwnProperty(e.data.method)||a&&e.data.walletNamespace!==a)}(n)&&l(n))if(n.data.method!==i.connect){if(n.data.uid){var c=o[n.data.uid];if(c){var u=n.data.response,p=n.data.error;if(p)return c.reject(p),void delete o[n.data.uid];n.data.method===i.enable&&(null,"object"==typeof u&&(u={...s(u)})),c.resolve(u),delete o[n.data.uid]}}}else await d("handshake")&&r&&e&&e(r)},!1)}