@frak-labs/core-sdk 0.0.17 → 0.0.18-beta.e43e855e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
- "use strict";let __rslib_import_meta_url__="undefined"==typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,r)=>{for(var t in r)__webpack_require__.o(r,t)&&!__webpack_require__.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},__webpack_require__.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{decompressJsonFromB64:()=>decompressJsonFromB64,locales:()=>locales,productTypesMask:()=>productTypesMask,interactionTypes:()=>interactionTypes,createIFrameFrakClient:()=>createIFrameFrakClient,decompressJson:()=>decompressJson,getCurrencyAmountKey:()=>getCurrencyAmountKey,getSupportedCurrency:()=>getSupportedCurrency,hashAndCompressData:()=>hashAndCompressData,FrakContextManager:()=>FrakContextManager,formatAmount:()=>formatAmount,getSupportedLocale:()=>getSupportedLocale,trackEvent:()=>trackEvent,compressJsonToB64:()=>compressJsonToB64,RpcErrorCodes:()=>RpcErrorCodes,ClientNotFound:()=>ClientNotFound,base64urlDecode:()=>base64urlDecode,baseIframeProps:()=>baseIframeProps,DebugInfoGatherer:()=>DebugInfoGatherer,base64urlEncode:()=>base64urlEncode,Deferred:()=>Deferred,compressJson:()=>compressJson,productTypes:()=>productTypes,setupClient:()=>setupClient,createIframe:()=>createIframe,FrakRpcError:()=>FrakRpcError,decompressDataAndCheckHash:()=>decompressDataAndCheckHash});let web_namespaceObject=require("@openpanel/web");class FrakRpcError extends Error{code;data;constructor(e,r,t){super(r),this.code=e,this.data=t}}class MethodNotFoundError extends FrakRpcError{constructor(e,r){super(RpcErrorCodes.methodNotFound,e,{method:r})}}class InternalError extends FrakRpcError{constructor(e){super(RpcErrorCodes.internalError,e)}}class ClientNotFound extends FrakRpcError{constructor(){super(RpcErrorCodes.clientNotConnected,"Client not found")}}let RpcErrorCodes={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603,serverError:-32e3,clientNotConnected:-32001,configError:-32002,corruptedResponse:-32003,clientAborted:-32004,walletNotConnected:-32005,serverErrorForInteractionDelegation:-32006};class Deferred{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,r)=>{this._resolve=e,this._reject=r})}get promise(){return this._promise}resolve=e=>{this._resolve?.(e)};reject=e=>{this._reject?.(e)}}let index_js_namespaceObject=require("@jsonjoy.com/json-pack/lib/cbor/index.js");function base64urlEncode(e){return btoa(Array.from(e,e=>String.fromCharCode(e)).join("")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function base64urlDecode(e){let r=e.length%4;return Uint8Array.from(atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(0===r?0:4-r),"=")),e=>e.charCodeAt(0))}let external_viem_namespaceObject=require("viem"),encoder=new index_js_namespaceObject.CborEncoder;function hashAndCompressData(e){let r={...e,validationHash:hashJson(e)};return encoder.encode(r)}function compressJson(e){return encoder.encode(e)}function compressJsonToB64(e){return base64urlEncode(compressJson(e))}function hashJson(e){return(0,external_viem_namespaceObject.sha256)(encoder.encode(e))}let decoder=new index_js_namespaceObject.CborDecoder;function decompressDataAndCheckHash(e){if(!e.length)throw new FrakRpcError(RpcErrorCodes.corruptedResponse,"Missing compressed data");let r=decompressJson(e);if(!r)throw new FrakRpcError(RpcErrorCodes.corruptedResponse,"Invalid compressed data");if(!r?.validationHash)throw new FrakRpcError(RpcErrorCodes.corruptedResponse,"Missing validation hash");let{validationHash:t,...o}=r;if(hashJson(o)!==r.validationHash)throw new FrakRpcError(RpcErrorCodes.corruptedResponse,"Invalid data validation hash");return r}function decompressJson(e){try{return decoder.decode(e)}catch(r){return console.error("Invalid compressed data",{e:r,data:e}),null}}function decompressJsonFromB64(e){return decompressJson(base64urlDecode(e))}let BACKUP_KEY="nexus-wallet-backup";class DebugInfoGatherer{config;iframe;isSetupDone=!1;lastResponse=null;lastRequest=null;constructor(e,r){this.config=e,this.iframe=r,this.lastRequest=null,this.lastResponse=null}setLastResponse(e){this.lastResponse={event:e.data,origin:e.origin,timestamp:Date.now()}}setLastRequest(e,r){this.lastRequest={event:e,target:r,timestamp:Date.now()}}updateSetupStatus(e){this.isSetupDone=e}base64Encode(e){try{return btoa(JSON.stringify(e))}catch(e){return console.warn("Failed to encode debug data",e),btoa("Failed to encode data")}}getIframeStatus(){return this.iframe?{loading:this.iframe.hasAttribute("loading"),url:this.iframe.src,readyState:this.iframe.contentDocument?.readyState?+("complete"===this.iframe.contentDocument.readyState):-1,contentWindow:!!this.iframe.contentWindow,isConnected:this.iframe.isConnected}:null}getNavigatorInfo(){return navigator?{userAgent:navigator.userAgent,language:navigator.language,onLine:navigator.onLine,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}:null}gatherDebugInfo(e){let r=this.getIframeStatus(),t=this.getNavigatorInfo(),o="Unknown";return e instanceof FrakRpcError?o=`FrakRpcError: ${e.code} '${e.message}'`:e instanceof Error?o=e.message:"string"==typeof e&&(o=e),{timestamp:new Date().toISOString(),encodedUrl:btoa(window.location.href),encodedConfig:this.config?this.base64Encode(this.config):"no-config",navigatorInfo:t?this.base64Encode(t):"no-navigator",iframeStatus:r?this.base64Encode(r):"not-iframe",lastRequest:this.lastRequest?this.base64Encode(this.lastRequest):"No Frak request logged",lastResponse:this.lastResponse?this.base64Encode(this.lastResponse):"No Frak response logged",clientStatus:this.isSetupDone?"setup":"not-setup",error:o}}static empty(){return new DebugInfoGatherer}formatDebugInfo(e){let r=this.gatherDebugInfo(e);return`
1
+ "use strict";let __rslib_import_meta_url__="undefined"==typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var __webpack_require__={};__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{decompressJsonFromB64:()=>decompressJsonFromB64,productTypesMask:()=>productTypesMask,interactionTypes:()=>interactionTypes,createIFrameFrakClient:()=>createIFrameFrakClient,getCurrencyAmountKey:()=>getCurrencyAmountKey,getSupportedCurrency:()=>getSupportedCurrency,FrakContextManager:()=>FrakContextManager,formatAmount:()=>formatAmount,getSupportedLocale:()=>getSupportedLocale,trackEvent:()=>trackEvent,compressJsonToB64:()=>compressJsonToB64,base64urlDecode:()=>base64urlDecode,baseIframeProps:()=>baseIframeProps,DebugInfoGatherer:()=>DebugInfoGatherer,base64urlEncode:()=>base64urlEncode,productTypes:()=>productTypes,setupClient:()=>setupClient,createIframe:()=>createIframe,locales:()=>locales});let frame_connector_namespaceObject=require("@frak-labs/frame-connector"),middleware_namespaceObject=require("@frak-labs/frame-connector/middleware"),web_namespaceObject=require("@openpanel/web"),BACKUP_KEY="nexus-wallet-backup";function setupSsoUrlListener(e,t){if("undefined"==typeof window)return;let r=new URL(window.location.href),a=r.searchParams.get("sso");a&&(t.then(()=>{e.sendLifecycle({clientLifecycle:"sso-redirect-complete",data:{compressed:a}}),console.log("[SSO URL Listener] Forwarded compressed SSO data to iframe")}).catch(e=>{console.error("[SSO URL Listener] Failed to forward SSO data:",e)}),r.searchParams.delete("sso"),window.history.replaceState({},"",r.toString()),console.log("[SSO URL Listener] SSO parameter detected and URL cleaned"))}class DebugInfoGatherer{config;iframe;isSetupDone=!1;lastResponse=null;lastRequest=null;constructor(e,t){this.config=e,this.iframe=t,this.lastRequest=null,this.lastResponse=null}setLastResponse(e,t){this.lastResponse={message:e,response:t,timestamp:Date.now()}}setLastRequest(e){this.lastRequest={event:e,timestamp:Date.now()}}updateSetupStatus(e){this.isSetupDone=e}base64Encode(e){try{return btoa(JSON.stringify(e))}catch(e){return console.warn("Failed to encode debug data",e),btoa("Failed to encode data")}}getIframeStatus(){return this.iframe?{loading:this.iframe.hasAttribute("loading"),url:this.iframe.src,readyState:this.iframe.contentDocument?.readyState?+("complete"===this.iframe.contentDocument.readyState):-1,contentWindow:!!this.iframe.contentWindow,isConnected:this.iframe.isConnected}:null}getNavigatorInfo(){return navigator?{userAgent:navigator.userAgent,language:navigator.language,onLine:navigator.onLine,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}:null}gatherDebugInfo(e){let t=this.getIframeStatus(),r=this.getNavigatorInfo(),a="Unknown";return e instanceof frame_connector_namespaceObject.FrakRpcError?a=`FrakRpcError: ${e.code} '${e.message}'`:e instanceof Error?a=e.message:"string"==typeof e&&(a=e),{timestamp:new Date().toISOString(),encodedUrl:btoa(window.location.href),encodedConfig:this.config?this.base64Encode(this.config):"no-config",navigatorInfo:r?this.base64Encode(r):"no-navigator",iframeStatus:t?this.base64Encode(t):"not-iframe",lastRequest:this.lastRequest?this.base64Encode(this.lastRequest):"No Frak request logged",lastResponse:this.lastResponse?this.base64Encode(this.lastResponse):"No Frak response logged",clientStatus:this.isSetupDone?"setup":"not-setup",error:a}}static empty(){return new DebugInfoGatherer}formatDebugInfo(e){let t=this.gatherDebugInfo(e);return`
2
2
  Debug Information:
3
3
  -----------------
4
- Timestamp: ${r.timestamp}
5
- URL: ${r.encodedUrl}
6
- Config: ${r.encodedConfig}
7
- Navigator Info: ${r.navigatorInfo}
8
- IFrame Status: ${r.iframeStatus}
9
- Last Request: ${r.lastRequest}
10
- Last Response: ${r.lastResponse}
11
- Client Status: ${r.clientStatus}
12
- Error: ${r.error}
13
- `.trim()}}function createIFrameChannelManager(){let e=new Map;return{createChannel:r=>{let t=Math.random().toString(36).substring(7);return e.set(t,r),t},getRpcResolver:r=>e.get(r),removeChannel:r=>e.delete(r),destroy:()=>e.clear()}}let baseIframeProps={id:"frak-wallet",name:"frak-wallet",title:"Frak Wallet",allow:"publickey-credentials-get *; clipboard-write; web-share *",style:{width:"0",height:"0",border:"0",position:"absolute",zIndex:2000001,top:"-1000px",left:"-1000px",colorScheme:"auto"}};function createIframe({walletBaseUrl:e,config:r}){let t=document.querySelector("#frak-wallet");t&&t.remove();let o=document.createElement("iframe");return o.id=baseIframeProps.id,o.name=baseIframeProps.name,o.allow=baseIframeProps.allow,o.style.zIndex=baseIframeProps.style.zIndex.toString(),changeIframeVisibility({iframe:o,isVisible:!1}),document.body.appendChild(o),new Promise(t=>{o?.addEventListener("load",()=>t(o)),o.src=`${r?.walletUrl??e??"https://wallet.frak.id"}/listener`})}function changeIframeVisibility({iframe:e,isVisible:r}){if(!r){e.style.width="0",e.style.height="0",e.style.border="0",e.style.position="fixed",e.style.top="-1000px",e.style.left="-1000px";return}e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.pointerEvents="auto"}function createIFrameLifecycleManager({iframe:e}){let r=new Deferred;return{handleEvent:async t=>{switch(t.iframeLifecycle){case"connected":r.resolve(!0);break;case"do-backup":t.data.backup?localStorage.setItem(BACKUP_KEY,t.data.backup):localStorage.removeItem(BACKUP_KEY);break;case"remove-backup":localStorage.removeItem(BACKUP_KEY);break;case"show":case"hide":changeIframeVisibility({iframe:e,isVisible:"show"===t.iframeLifecycle});break;case"handshake":e.contentWindow?.postMessage({clientLifecycle:"handshake-response",data:{token:t.data.token,currentUrl:window.location.href}},"*");break;case"redirect":window.location.href=`${t.data.baseRedirectUrl}${encodeURIComponent(window.location.href)}`}},isConnected:r.promise}}function createIFrameMessageHandler({frakWalletUrl:e,iframe:r,channelManager:t,iframeLifecycleManager:o,debugInfo:n}){if("undefined"==typeof window)throw new FrakRpcError(RpcErrorCodes.configError,"iframe client should be used in the browser");if(!r.contentWindow)throw new FrakRpcError(RpcErrorCodes.configError,"The iframe does not have a product window");let a=r.contentWindow;async function s(r){if(!r.origin)return;try{if(new URL(r.origin).origin.toLowerCase()!==new URL(e).origin.toLowerCase())return}catch(e){console.log("Unable to check frak msg origin",e);return}if("object"!=typeof r.data)return;if(n.setLastResponse(r),"iframeLifecycle"in r.data)return void await o.handleEvent(r.data);if("clientLifecycle"in r.data)return void console.error("Client lifecycle event received on the client side, dismissing it");let a=r.data.id,s=t.getRpcResolver(a);s&&s(r.data)}return window.addEventListener("message",s),{sendEvent:function(r){a.postMessage(r,{targetOrigin:e}),n.setLastRequest(r,e)},cleanup:function(){window.removeEventListener("message",s)}}}function createIFrameFrakClient({config:e,iframe:r}){let t,o=createIFrameChannelManager(),n=createIFrameLifecycleManager({iframe:r}),a=new DebugInfoGatherer(e,r),s=createIFrameMessageHandler({frakWalletUrl:e?.walletUrl??"https://wallet.frak.id",iframe:r,channelManager:o,iframeLifecycleManager:n,debugInfo:a}),c=async e=>{if(!await n.isConnected)throw new FrakRpcError(RpcErrorCodes.clientNotConnected,"The iframe provider isn't connected yet");let r=new Deferred,t=o.createChannel(e=>{let n=decompressDataAndCheckHash(e.data);n.error?r.reject(new FrakRpcError(n.error.code,n.error.message,n.error?.data)):r.resolve(n.result),o.removeChannel(t)}),a=hashAndCompressData(e);return s.sendEvent({id:t,topic:e.method,data:a}),r.promise},i=async(e,r)=>{if(!await n.isConnected)throw new FrakRpcError(RpcErrorCodes.clientNotConnected,"The iframe provider isn't connected yet");let t=o.createChannel(e=>{let t=decompressDataAndCheckHash(e.data);if(t.result)r(t.result);else throw new InternalError("No valid result in the response")}),a=hashAndCompressData(e);s.sendEvent({id:t,topic:e.method,data:a})},p=setupHeartbeat(s,n),l=async()=>{p(),o.destroy(),s.cleanup(),r.remove()};console.log("[Frak SDK] Initializing OpenPanel"),(t=new web_namespaceObject.OpenPanel({apiUrl:"https://op-api.gcp.frak.id",clientId:"f305d11d-b93b-487c-80d4-92deb7903e98",trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:e,payload:r})=>!("track"===e&&r?.properties)||("sdkVersion"in r.properties||(r.properties={...r.properties,sdkVersion:"0.0.17"}),!0)})).setGlobalProperties({sdkVersion:"0.0.17"}),t.init();let d=postConnectionSetup({config:e,messageHandler:s,lifecycleManager:n}).then(()=>a.updateSetupStatus(!0));return{config:e,debugInfo:a,waitForConnection:n.isConnected,waitForSetup:d,request:c,listenerRequest:i,destroy:l,openPanel:t}}function setupHeartbeat(e,r){let t,o,n=()=>e.sendEvent({clientLifecycle:"heartbeat"});function a(){t&&clearInterval(t),o&&clearTimeout(o)}return async function(){n(),t=setInterval(n,100),o=setTimeout(()=>{a(),console.log("Heartbeat timeout: connection failed")},3e4),await r.isConnected,a()}(),a}async function postConnectionSetup({config:e,messageHandler:r,lifecycleManager:t}){async function o(){let t=e.customizations?.css;t&&r.sendEvent({clientLifecycle:"modal-css",data:{cssLink:t}})}async function n(){let t=e.customizations?.i18n;t&&r.sendEvent({clientLifecycle:"modal-i18n",data:{i18n:t}})}async function a(){if("undefined"==typeof window)return;let e=window.localStorage.getItem(BACKUP_KEY);e&&r.sendEvent({clientLifecycle:"restore-backup",data:{backup:e}})}await t.isConnected,await Promise.allSettled([o(),n(),a()])}let locales={eur:"fr-FR",usd:"en-US",gbp:"en-GB"};function getSupportedCurrency(e){return e&&e in locales?e:"eur"}async function setupClient({config:e}){let r=prepareConfig(e),t=await createIframe({config:r});if(!t)return void console.error("Failed to create iframe");let o=createIFrameFrakClient({config:r,iframe:t});return(await o.waitForSetup,await o.waitForConnection)?o:void console.error("Failed to connect to client")}function prepareConfig(e){let r=getSupportedCurrency(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:r}}}let contextKey="fCtx";function compress(e){if(e?.r)try{let r=(0,external_viem_namespaceObject.hexToBytes)(e.r);return base64urlEncode(r)}catch(r){console.error("Error compressing Frak context",{e:r,context:e})}}function decompress(e){if(e&&0!==e.length)try{let r=base64urlDecode(e);return{r:(0,external_viem_namespaceObject.bytesToHex)(r,{size:20})}}catch(r){console.error("Error decompressing Frak context",{e:r,context:e})}}function parse({url:e}){if(!e)return null;let r=new URL(e).searchParams.get(contextKey);return r?decompress(r):null}function update({url:e,context:r}){if(!e)return null;let t=parse({url:e}),o=t?{...t,...r}:r;if(!o.r)return null;let n=compress(o);if(!n)return null;let a=new URL(e);return a.searchParams.set(contextKey,n),a.toString()}function remove(e){let r=new URL(e);return r.searchParams.delete(contextKey),r.toString()}function replaceUrl({url:e,context:r}){let t;if(!window.location?.href||"undefined"==typeof window)return void console.error("No window found, can't update context");let o=e??window.location.href;(t=null!==r?update({url:o,context:r}):remove(o))&&window.history.replaceState(null,"",t.toString())}let FrakContextManager={compress,decompress,parse,update,remove,replaceUrl};function getSupportedLocale(e){return e?locales[e]??locales.eur:locales.eur}function getCurrencyAmountKey(e){return e?`${e}Amount`:"eurAmount"}function formatAmount(e,r){let t=getSupportedLocale(r),o=getSupportedCurrency(r);return e.toLocaleString(t,{style:"currency",currency:o,minimumFractionDigits:0,maximumFractionDigits:2})}function trackEvent(e,r,t={}){if(!e)return void console.debug("[Frak] No client provided, skipping event tracking");try{e.openPanel?.track(r,t)}catch(e){console.debug("[Frak] Failed to track event:",r,e)}}let productTypes={dapp:1,press:2,webshop:3,retail:4,referral:30,purchase:31},productTypesMask=Object.entries(productTypes).reduce((e,[r,t])=>(e[r]=BigInt(1)<<BigInt(t),e),{}),interactionTypes={press:{openArticle:"0xc0a24ffb",readArticle:"0xd5bd0fbe"},dapp:{proofVerifiableStorageUpdate:"0x2ab2aeef",callableVerifiableStorageUpdate:"0xa07da986"},webshop:{open:"0xb311798f"},referral:{referred:"0x010cc3b9",createLink:"0xb2c0f17c"},purchase:{started:"0xd87e90c3",completed:"0x8403aeb4",unsafeCompleted:"0x4d5b14e0"},retail:{customerMeeting:"0x74489004"}};for(var __webpack_i__ in exports.ClientNotFound=__webpack_exports__.ClientNotFound,exports.DebugInfoGatherer=__webpack_exports__.DebugInfoGatherer,exports.Deferred=__webpack_exports__.Deferred,exports.FrakContextManager=__webpack_exports__.FrakContextManager,exports.FrakRpcError=__webpack_exports__.FrakRpcError,exports.RpcErrorCodes=__webpack_exports__.RpcErrorCodes,exports.base64urlDecode=__webpack_exports__.base64urlDecode,exports.base64urlEncode=__webpack_exports__.base64urlEncode,exports.baseIframeProps=__webpack_exports__.baseIframeProps,exports.compressJson=__webpack_exports__.compressJson,exports.compressJsonToB64=__webpack_exports__.compressJsonToB64,exports.createIFrameFrakClient=__webpack_exports__.createIFrameFrakClient,exports.createIframe=__webpack_exports__.createIframe,exports.decompressDataAndCheckHash=__webpack_exports__.decompressDataAndCheckHash,exports.decompressJson=__webpack_exports__.decompressJson,exports.decompressJsonFromB64=__webpack_exports__.decompressJsonFromB64,exports.formatAmount=__webpack_exports__.formatAmount,exports.getCurrencyAmountKey=__webpack_exports__.getCurrencyAmountKey,exports.getSupportedCurrency=__webpack_exports__.getSupportedCurrency,exports.getSupportedLocale=__webpack_exports__.getSupportedLocale,exports.hashAndCompressData=__webpack_exports__.hashAndCompressData,exports.interactionTypes=__webpack_exports__.interactionTypes,exports.locales=__webpack_exports__.locales,exports.productTypes=__webpack_exports__.productTypes,exports.productTypesMask=__webpack_exports__.productTypesMask,exports.setupClient=__webpack_exports__.setupClient,exports.trackEvent=__webpack_exports__.trackEvent,__webpack_exports__)-1===["ClientNotFound","DebugInfoGatherer","Deferred","FrakContextManager","FrakRpcError","RpcErrorCodes","base64urlDecode","base64urlEncode","baseIframeProps","compressJson","compressJsonToB64","createIFrameFrakClient","createIframe","decompressDataAndCheckHash","decompressJson","decompressJsonFromB64","formatAmount","getCurrencyAmountKey","getSupportedCurrency","getSupportedLocale","hashAndCompressData","interactionTypes","locales","productTypes","productTypesMask","setupClient","trackEvent"].indexOf(__webpack_i__)&&(exports[__webpack_i__]=__webpack_exports__[__webpack_i__]);Object.defineProperty(exports,"__esModule",{value:!0});
4
+ Timestamp: ${t.timestamp}
5
+ URL: ${t.encodedUrl}
6
+ Config: ${t.encodedConfig}
7
+ Navigator Info: ${t.navigatorInfo}
8
+ IFrame Status: ${t.iframeStatus}
9
+ Last Request: ${t.lastRequest}
10
+ Last Response: ${t.lastResponse}
11
+ Client Status: ${t.clientStatus}
12
+ Error: ${t.error}
13
+ `.trim()}}let baseIframeProps={id:"frak-wallet",name:"frak-wallet",title:"Frak Wallet",allow:"publickey-credentials-get *; clipboard-write; web-share *",style:{width:"0",height:"0",border:"0",position:"absolute",zIndex:2000001,top:"-1000px",left:"-1000px",colorScheme:"auto"}};function createIframe({walletBaseUrl:e,config:t}){let r=document.querySelector("#frak-wallet");r&&r.remove();let a=document.createElement("iframe");return a.id=baseIframeProps.id,a.name=baseIframeProps.name,a.allow=baseIframeProps.allow,a.style.zIndex=baseIframeProps.style.zIndex.toString(),changeIframeVisibility({iframe:a,isVisible:!1}),document.body.appendChild(a),new Promise(r=>{a?.addEventListener("load",()=>r(a)),a.src=`${t?.walletUrl??e??"https://wallet.frak.id"}/listener`})}function changeIframeVisibility({iframe:e,isVisible:t}){if(!t){e.style.width="0",e.style.height="0",e.style.border="0",e.style.position="fixed",e.style.top="-1000px",e.style.left="-1000px";return}e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.pointerEvents="auto"}function createIFrameLifecycleManager({iframe:e}){let t=new frame_connector_namespaceObject.Deferred;return{handleEvent:async r=>{if(!("iframeLifecycle"in r))return;let{iframeLifecycle:a,data:o}=r;switch(a){case"connected":t.resolve(!0);break;case"do-backup":o.backup?localStorage.setItem(BACKUP_KEY,o.backup):localStorage.removeItem(BACKUP_KEY);break;case"remove-backup":localStorage.removeItem(BACKUP_KEY);break;case"show":case"hide":changeIframeVisibility({iframe:e,isVisible:"show"===a});break;case"handshake":e.contentWindow?.postMessage({clientLifecycle:"handshake-response",data:{token:o.token,currentUrl:window.location.href}},"*");break;case"redirect":{let e=new URL(o.baseRedirectUrl);e.searchParams.has("u")?(e.searchParams.delete("u"),e.searchParams.append("u",window.location.href),window.location.href=e.toString()):window.location.href=o.baseRedirectUrl}}},isConnected:t.promise}}function createIFrameFrakClient({config:e,iframe:t}){let r,a=e?.walletUrl??"https://wallet.frak.id",o=createIFrameLifecycleManager({iframe:t}),n=new DebugInfoGatherer(e,t);if(!t.contentWindow)throw new frame_connector_namespaceObject.FrakRpcError(frame_connector_namespaceObject.RpcErrorCodes.configError,"The iframe does not have a content window");let s=(0,frame_connector_namespaceObject.createRpcClient)({emittingTransport:t.contentWindow,listeningTransport:window,targetOrigin:a,middleware:[{async onRequest(e,t){if(!await o.isConnected)throw new frame_connector_namespaceObject.FrakRpcError(frame_connector_namespaceObject.RpcErrorCodes.clientNotConnected,"The iframe provider isn't connected yet");return t}},(0,middleware_namespaceObject.createClientCompressionMiddleware)(),{onRequest:(e,t)=>(n.setLastRequest(e),t),onResponse:(e,t)=>(n.setLastResponse(e,t),t)}],lifecycleHandlers:{iframeLifecycle:async(e,t)=>{await o.handleEvent(e)}}}),c=setupHeartbeat(s,o),i=async()=>{c(),s.cleanup(),t.remove()};console.log("[Frak SDK] Initializing OpenPanel"),(r=new web_namespaceObject.OpenPanel({apiUrl:"https://op-api.gcp.frak.id",clientId:"6eacc8d7-49ac-4936-95e9-81ef29449570",trackScreenViews:!0,trackOutgoingLinks:!0,trackAttributes:!1,filter:({type:e,payload:t})=>!("track"===e&&t?.properties)||("sdkVersion"in t.properties||(t.properties={...t.properties,sdkVersion:"0.0.18"}),!0)})).setGlobalProperties({sdkVersion:"0.0.18"}),r.init();let l=postConnectionSetup({config:e,rpcClient:s,lifecycleManager:o}).then(()=>n.updateSetupStatus(!0));return{config:e,debugInfo:n,waitForConnection:o.isConnected,waitForSetup:l,request:s.request,listenerRequest:s.listen,destroy:i,openPanel:r}}function setupHeartbeat(e,t){let r,a,o=()=>e.sendLifecycle({clientLifecycle:"heartbeat"});function n(){r&&clearInterval(r),a&&clearTimeout(a)}return async function(){o(),r=setInterval(o,1e3),a=setTimeout(()=>{n(),console.log("Heartbeat timeout: connection failed")},3e4),await t.isConnected,n()}(),n}async function postConnectionSetup({config:e,rpcClient:t,lifecycleManager:r}){async function a(){let r=e.customizations?.css;r&&t.sendLifecycle({clientLifecycle:"modal-css",data:{cssLink:r}})}async function o(){let r=e.customizations?.i18n;r&&t.sendLifecycle({clientLifecycle:"modal-i18n",data:{i18n:r}})}async function n(){if("undefined"==typeof window)return;let e=window.localStorage.getItem(BACKUP_KEY);e&&t.sendLifecycle({clientLifecycle:"restore-backup",data:{backup:e}})}await r.isConnected,setupSsoUrlListener(t,r.isConnected),await Promise.allSettled([a(),o(),n()])}let locales={eur:"fr-FR",usd:"en-US",gbp:"en-GB"};function getSupportedCurrency(e){return e&&e in locales?e:"eur"}async function setupClient({config:e}){let t=prepareConfig(e),r=await createIframe({config:t});if(!r)return void console.error("Failed to create iframe");let a=createIFrameFrakClient({config:t,iframe:r});return(await a.waitForSetup,await a.waitForConnection)?a:void console.error("Failed to connect to client")}function prepareConfig(e){let t=getSupportedCurrency(e.metadata?.currency);return{...e,metadata:{...e.metadata,currency:t}}}function base64urlEncode(e){return btoa(Array.from(e,e=>String.fromCharCode(e)).join("")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function base64urlDecode(e){let t=e.length%4;return Uint8Array.from(atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(0===t?0:4-t),"=")),e=>e.charCodeAt(0))}function compressJsonToB64(e){return base64urlEncode((0,frame_connector_namespaceObject.compressJson)(e))}function decompressJsonFromB64(e){return(0,frame_connector_namespaceObject.decompressJson)(base64urlDecode(e))}let external_viem_namespaceObject=require("viem"),contextKey="fCtx";function compress(e){if(e?.r)try{let t=(0,external_viem_namespaceObject.hexToBytes)(e.r);return base64urlEncode(t)}catch(t){console.error("Error compressing Frak context",{e:t,context:e})}}function decompress(e){if(e&&0!==e.length)try{let t=base64urlDecode(e);return{r:(0,external_viem_namespaceObject.bytesToHex)(t,{size:20})}}catch(t){console.error("Error decompressing Frak context",{e:t,context:e})}}function parse({url:e}){if(!e)return null;let t=new URL(e).searchParams.get(contextKey);return t?decompress(t):null}function update({url:e,context:t}){if(!e)return null;let r=parse({url:e}),a=r?{...r,...t}:t;if(!a.r)return null;let o=compress(a);if(!o)return null;let n=new URL(e);return n.searchParams.set(contextKey,o),n.toString()}function remove(e){let t=new URL(e);return t.searchParams.delete(contextKey),t.toString()}function replaceUrl({url:e,context:t}){let r;if(!window.location?.href||"undefined"==typeof window)return void console.error("No window found, can't update context");let a=e??window.location.href;(r=null!==t?update({url:a,context:t}):remove(a))&&window.history.replaceState(null,"",r.toString())}let FrakContextManager={compress,decompress,parse,update,remove,replaceUrl};function getSupportedLocale(e){return e?locales[e]??locales.eur:locales.eur}function getCurrencyAmountKey(e){return e?`${e}Amount`:"eurAmount"}function formatAmount(e,t){let r=getSupportedLocale(t),a=getSupportedCurrency(t);return e.toLocaleString(r,{style:"currency",currency:a,minimumFractionDigits:0,maximumFractionDigits:2})}function trackEvent(e,t,r={}){if(!e)return void console.debug("[Frak] No client provided, skipping event tracking");try{e.openPanel?.track(t,r)}catch(e){console.debug("[Frak] Failed to track event:",t,e)}}let productTypes={dapp:1,press:2,webshop:3,retail:4,referral:30,purchase:31},productTypesMask=Object.entries(productTypes).reduce((e,[t,r])=>(e[t]=BigInt(1)<<BigInt(r),e),{}),interactionTypes={press:{openArticle:"0xc0a24ffb",readArticle:"0xd5bd0fbe"},dapp:{proofVerifiableStorageUpdate:"0x2ab2aeef",callableVerifiableStorageUpdate:"0xa07da986"},webshop:{open:"0xb311798f"},referral:{referred:"0x010cc3b9",createLink:"0xb2c0f17c"},purchase:{started:"0xd87e90c3",completed:"0x8403aeb4",unsafeCompleted:"0x4d5b14e0"},retail:{customerMeeting:"0x74489004"}};for(var __webpack_i__ in exports.DebugInfoGatherer=__webpack_exports__.DebugInfoGatherer,exports.FrakContextManager=__webpack_exports__.FrakContextManager,exports.base64urlDecode=__webpack_exports__.base64urlDecode,exports.base64urlEncode=__webpack_exports__.base64urlEncode,exports.baseIframeProps=__webpack_exports__.baseIframeProps,exports.compressJsonToB64=__webpack_exports__.compressJsonToB64,exports.createIFrameFrakClient=__webpack_exports__.createIFrameFrakClient,exports.createIframe=__webpack_exports__.createIframe,exports.decompressJsonFromB64=__webpack_exports__.decompressJsonFromB64,exports.formatAmount=__webpack_exports__.formatAmount,exports.getCurrencyAmountKey=__webpack_exports__.getCurrencyAmountKey,exports.getSupportedCurrency=__webpack_exports__.getSupportedCurrency,exports.getSupportedLocale=__webpack_exports__.getSupportedLocale,exports.interactionTypes=__webpack_exports__.interactionTypes,exports.locales=__webpack_exports__.locales,exports.productTypes=__webpack_exports__.productTypes,exports.productTypesMask=__webpack_exports__.productTypesMask,exports.setupClient=__webpack_exports__.setupClient,exports.trackEvent=__webpack_exports__.trackEvent,__webpack_exports__)-1===["DebugInfoGatherer","FrakContextManager","base64urlDecode","base64urlEncode","baseIframeProps","compressJsonToB64","createIFrameFrakClient","createIframe","decompressJsonFromB64","formatAmount","getCurrencyAmountKey","getSupportedCurrency","getSupportedLocale","interactionTypes","locales","productTypes","productTypesMask","setupClient","trackEvent"].indexOf(__webpack_i__)&&(exports[__webpack_i__]=__webpack_exports__[__webpack_i__]);Object.defineProperty(exports,"__esModule",{value:!0});
package/dist/index.d.cts CHANGED
@@ -1,8 +1,10 @@
1
1
  import type { Address } from 'viem';
2
2
  import type { Hex } from 'viem';
3
+ import type { LifecycleMessage } from '@frak-labs/frame-connector';
3
4
  import type { OpenPanel } from '@openpanel/web';
4
- import type { Prettify } from 'viem/chains';
5
- import type { RpcSchema } from 'viem';
5
+ import type { RpcClient } from '@frak-labs/frame-connector';
6
+ import { RpcMessage } from '@frak-labs/frame-connector';
7
+ import { RpcResponse } from '@frak-labs/frame-connector';
6
8
  import type { SiweMessage } from 'viem/siwe';
7
9
 
8
10
  /**
@@ -44,12 +46,7 @@ export declare const baseIframeProps: {
44
46
  * Event related to the iframe lifecycle
45
47
  * @ignore
46
48
  */
47
- export declare type ClientLifecycleEvent = CustomCssEvent | CustomI18nEvent | RestoreBackupEvent | HearbeatEvent | HandshakeResponse;
48
-
49
- /** @ignore */
50
- export declare class ClientNotFound extends FrakRpcError {
51
- constructor();
52
- }
49
+ export declare type ClientLifecycleEvent = CustomCssEvent | CustomI18nEvent | RestoreBackupEvent | HearbeatEvent | HandshakeResponse | SsoRedirectCompleteEvent;
53
50
 
54
51
  /**
55
52
  * Compress the current Frak context
@@ -65,13 +62,6 @@ declare function compress(context?: Partial<FrakContext>): string | undefined;
65
62
  */
66
63
  export declare type CompressedData = Uint8Array;
67
64
 
68
- /**
69
- * Compress json data
70
- * @param data
71
- * @ignore
72
- */
73
- export declare function compressJson(data: unknown): Uint8Array;
74
-
75
65
  /**
76
66
  * Compress json data
77
67
  * @param data
@@ -139,8 +129,8 @@ export declare class DebugInfoGatherer {
139
129
  private lastResponse;
140
130
  private lastRequest;
141
131
  constructor(config?: FrakWalletSdkConfig, iframe?: HTMLIFrameElement);
142
- setLastResponse(event: MessageEvent<IFrameEvent>): void;
143
- setLastRequest(event: IFrameEvent, target: string): void;
132
+ setLastResponse(message: RpcMessage, response: RpcResponse): void;
133
+ setLastRequest(event: RpcMessage): void;
144
134
  updateSetupStatus(status: boolean): void;
145
135
  private base64Encode;
146
136
  /**
@@ -163,20 +153,6 @@ export declare class DebugInfoGatherer {
163
153
  */
164
154
  declare function decompress(context?: string): FrakContext | undefined;
165
155
 
166
- /**
167
- * Decompress the given string
168
- * @param compressedData The params to encode
169
- * @ignore
170
- */
171
- export declare function decompressDataAndCheckHash<T>(compressedData: CompressedData): HashProtectedData<T>;
172
-
173
- /**
174
- * Decompress json data
175
- * @param data
176
- * @ignore
177
- */
178
- export declare function decompressJson<T>(data: Uint8Array): T | null;
179
-
180
156
  /**
181
157
  * Decompress json data
182
158
  * @param data
@@ -184,20 +160,6 @@ export declare function decompressJson<T>(data: Uint8Array): T | null;
184
160
  */
185
161
  export declare function decompressJsonFromB64<T>(data: string): T | null;
186
162
 
187
- /**
188
- * Simple deferred promise wrapper
189
- * @ignore
190
- */
191
- export declare class Deferred<T> {
192
- private readonly _promise;
193
- private _resolve;
194
- private _reject;
195
- constructor();
196
- get promise(): Promise<T>;
197
- resolve: (value: T | PromiseLike<T>) => void;
198
- reject: (reason?: unknown) => void;
199
- }
200
-
201
163
  /**
202
164
  * The params used to display the embedded wallet
203
165
  *
@@ -311,34 +273,6 @@ export declare type EmbeddedViewActionSharing = {
311
273
 
312
274
  declare type EventProps = Record<string, unknown>;
313
275
 
314
- /**
315
- * Type that extract the possible return type from a RPC Schema
316
- * @ignore
317
- */
318
- declare type ExtractedMethodFromRpc<TRpcSchema extends RpcSchema, TMethod extends ExtractedParametersFromRpc<TRpcSchema>["method"] = ExtractedParametersFromRpc<TRpcSchema>["method"]> = Extract<TRpcSchema[number], {
319
- Method: TMethod;
320
- }>;
321
-
322
- /**
323
- * Type that extract the possible parameters from a RPC Schema
324
- * @ignore
325
- */
326
- export declare type ExtractedParametersFromRpc<TRpcSchema extends RpcSchema> = {
327
- [K in keyof TRpcSchema]: Prettify<{
328
- method: TRpcSchema[K] extends TRpcSchema[number] ? TRpcSchema[K]["Method"] : string;
329
- } & (TRpcSchema[K] extends TRpcSchema[number] ? TRpcSchema[K]["Parameters"] extends undefined ? {
330
- params?: never;
331
- } : {
332
- params: TRpcSchema[K]["Parameters"];
333
- } : never)>;
334
- }[number];
335
-
336
- /**
337
- * Type that extract the possible return type from a RPC Schema
338
- * @ignore
339
- */
340
- export declare type ExtractedReturnTypeFromRpc<TRpcSchema extends RpcSchema, TParameters extends ExtractedParametersFromRpc<TRpcSchema> = ExtractedParametersFromRpc<TRpcSchema>> = ExtractedMethodFromRpc<TRpcSchema, TParameters["method"]>["ReturnType"];
341
-
342
276
  /**
343
277
  * The different types of final actions we can display in the final step
344
278
  * @group Modal Display
@@ -400,7 +334,7 @@ export declare type FrakContext = {
400
334
  };
401
335
 
402
336
  /**
403
- * Export our frak context "class"
337
+ * Export our frak context
404
338
  */
405
339
  export declare const FrakContextManager: {
406
340
  compress: typeof compress;
@@ -414,14 +348,9 @@ export declare const FrakContextManager: {
414
348
  declare type FrakEvent = "share_button_clicked" | "wallet_button_clicked" | "share_modal_error" | "user_referred";
415
349
 
416
350
  /**
417
- * Generic Frak RPC error
418
- * @ignore
351
+ * Represent an iframe event
419
352
  */
420
- export declare class FrakRpcError<T = undefined> extends Error {
421
- code: number;
422
- data?: T | undefined;
423
- constructor(code: number, message: string, data?: T | undefined);
424
- }
353
+ export declare type FrakLifecycleEvent = IFrameLifecycleEvent | ClientLifecycleEvent;
425
354
 
426
355
  /**
427
356
  * Configuration for the Frak Wallet SDK
@@ -581,13 +510,6 @@ declare type HandshakeResponse = {
581
510
  };
582
511
  };
583
512
 
584
- /**
585
- * Compress the given params, and add hash protection to (rapidly) prevent interception modification
586
- * @param data The params to encode
587
- * @ignore
588
- */
589
- export declare function hashAndCompressData<T>(data: T): CompressedData;
590
-
591
513
  /**
592
514
  * The encoded data to send to a client / received by a client
593
515
  * @ignore
@@ -598,6 +520,7 @@ export declare type HashProtectedData<DataType> = Readonly<DataType & {
598
520
 
599
521
  declare type HearbeatEvent = {
600
522
  clientLifecycle: "heartbeat";
523
+ data?: never;
601
524
  };
602
525
 
603
526
  /**
@@ -635,66 +558,63 @@ declare type HearbeatEvent = {
635
558
  */
636
559
  export declare type I18nConfig = Record<Language, LocalizedI18nConfig> | LocalizedI18nConfig;
637
560
 
638
- /**
639
- * Represent an iframe event
640
- */
641
- export declare type IFrameEvent = IFrameRpcEvent | IFrameLifecycleEvent | ClientLifecycleEvent;
642
-
643
561
  /**
644
562
  * Event related to the iframe lifecycle
645
563
  * @ignore
646
564
  */
647
565
  export declare type IFrameLifecycleEvent = {
648
- iframeLifecycle: "connected" | "show" | "hide";
566
+ iframeLifecycle: "connected" | "show" | "hide" | "remove-backup";
649
567
  data?: never;
650
- } | DoBackupEvent | RemoveBackupEvent | HandshakeRequestEvent | RedirectRequestEvent;
651
-
652
- /**
653
- * Represent an iframe rpc event
654
- */
655
- export declare type IFrameRpcEvent = {
656
- id: string;
657
- topic: ExtractedParametersFromRpc<IFrameRpcSchema>["method"];
658
- data: CompressedData;
659
- };
568
+ } | DoBackupEvent | HandshakeRequestEvent | RedirectRequestEvent;
660
569
 
661
570
  /**
662
571
  * RPC interface that's used for the iframe communication
663
572
  *
664
- * Define all the methods available within the iFrame RPC client
573
+ * Define all the methods available within the iFrame RPC client with response type annotations
665
574
  *
666
575
  * @group RPC Schema
667
576
  *
668
577
  * @remarks
669
- * Here is the list of methods available:
578
+ * Each method in the schema now includes a ResponseType field that indicates:
579
+ * - "promise": One-shot request that resolves once
580
+ * - "stream": Streaming request that can emit multiple values
581
+ *
582
+ * ### Methods:
670
583
  *
671
- * ### frak_listenToWalletStatus
584
+ * #### frak_listenToWalletStatus
672
585
  * - Params: None
673
586
  * - Returns: {@link WalletStatusReturnType}
587
+ * - Response Type: stream (emits updates when wallet status changes)
674
588
  *
675
- * ### frak_displayModal
676
- * - Params: [{@link ModalRpcStepsInput}, name: string, metadata?: {@link ModalRpcMetadata}]
589
+ * #### frak_displayModal
590
+ * - Params: [requests: {@link ModalRpcStepsInput}, metadata?: {@link ModalRpcMetadata}, configMetadata: {@link FrakWalletSdkConfig}["metadata"]]
677
591
  * - Returns: {@link ModalRpcStepsResultType}
592
+ * - Response Type: promise (one-shot)
678
593
  *
679
- * ### frak_sendInteraction
594
+ * #### frak_sendInteraction
680
595
  * - Params: [productId: Hex, interaction: {@link PreparedInteraction}, signature?: Hex]
681
596
  * - Returns: {@link SendInteractionReturnType}
597
+ * - Response Type: promise (one-shot)
682
598
  *
683
- * ### frak_sso
684
- * - Params [params: {@link OpenSsoParamsType}, name: string, customCss?: string]
685
- * - Returns: undefined
599
+ * #### frak_sso
600
+ * - Params: [params: {@link OpenSsoParamsType}, name: string, customCss?: string]
601
+ * - Returns: {@link OpenSsoReturnType}
602
+ * - Response Type: promise (one-shot)
686
603
  *
687
- * ### frak_getProductInformation
604
+ * #### frak_getProductInformation
688
605
  * - Params: None
689
606
  * - Returns: {@link GetProductInformationReturnType}
607
+ * - Response Type: promise (one-shot)
690
608
  *
691
- * ### frak_displayEmbeddedWallet
692
- * - Params: [{@link DisplayEmbeddedWalletParamsType}]
609
+ * #### frak_displayEmbeddedWallet
610
+ * - Params: [request: {@link DisplayEmbeddedWalletParamsType}, metadata: {@link FrakWalletSdkConfig}["metadata"]]
693
611
  * - Returns: {@link DisplayEmbeddedWalletResultType}
612
+ * - Response Type: promise (one-shot)
694
613
  */
695
614
  export declare type IFrameRpcSchema = [
696
615
  /**
697
616
  * Method used to listen to the wallet status
617
+ * This is a streaming method that emits updates when wallet status changes
698
618
  */
699
619
  {
700
620
  Method: "frak_listenToWalletStatus";
@@ -703,6 +623,7 @@ export declare type IFrameRpcSchema = [
703
623
  },
704
624
  /**
705
625
  * Method to display a modal with the provided steps
626
+ * This is a one-shot request
706
627
  */
707
628
  {
708
629
  Method: "frak_displayModal";
@@ -715,6 +636,7 @@ export declare type IFrameRpcSchema = [
715
636
  },
716
637
  /**
717
638
  * Method to transmit a user interaction
639
+ * This is a one-shot request
718
640
  */
719
641
  {
720
642
  Method: "frak_sendInteraction";
@@ -727,7 +649,7 @@ export declare type IFrameRpcSchema = [
727
649
  },
728
650
  /**
729
651
  * Method to start a SSO
730
- * todo: Should also support direct tracking via a consumeKey
652
+ * This is a one-shot request
731
653
  */
732
654
  {
733
655
  Method: "frak_sso";
@@ -736,13 +658,14 @@ export declare type IFrameRpcSchema = [
736
658
  name: string,
737
659
  customCss?: string
738
660
  ];
739
- ReturnType: undefined;
661
+ ReturnType: OpenSsoReturnType;
740
662
  },
741
663
  /**
742
664
  * Method to get current product information's
743
665
  * - Is product minted?
744
666
  * - Does it have running campaign?
745
667
  * - Estimated reward on actions
668
+ * This is a one-shot request
746
669
  */
747
670
  {
748
671
  Method: "frak_getProductInformation";
@@ -751,6 +674,7 @@ export declare type IFrameRpcSchema = [
751
674
  },
752
675
  /**
753
676
  * Method to show the embedded wallet, with potential customization
677
+ * This is a one-shot request
754
678
  */
755
679
  {
756
680
  Method: "frak_displayEmbeddedWallet";
@@ -777,11 +701,11 @@ export declare type IFrameTransport = {
777
701
  /**
778
702
  * Function used to perform a single request via the iframe transport
779
703
  */
780
- request: RequestFn<IFrameRpcSchema>;
704
+ request: RpcClient<IFrameRpcSchema, LifecycleMessage>["request"];
781
705
  /**
782
706
  * Function used to listen to a request response via the iframe transport
783
707
  */
784
- listenerRequest: ListenerRequestFn<IFrameRpcSchema>;
708
+ listenerRequest: RpcClient<IFrameRpcSchema, LifecycleMessage>["listen"];
785
709
  /**
786
710
  * Function used to destroy the iframe transport
787
711
  */
@@ -837,12 +761,6 @@ export declare type KeyProvider<DataType> = (value: DataType) => string[];
837
761
  */
838
762
  export declare type Language = "fr" | "en";
839
763
 
840
- /**
841
- * Type used for a listening request
842
- * @inline
843
- */
844
- declare type ListenerRequestFn<TRpcSchema extends RpcSchema> = <TParameters extends ExtractedParametersFromRpc<TRpcSchema> = ExtractedParametersFromRpc<TRpcSchema>, _ReturnType = ExtractedReturnTypeFromRpc<TRpcSchema, TParameters>>(args: TParameters, callback: (result: _ReturnType) => void) => Promise<void>;
845
-
846
764
  /**
847
765
  * Map the currency to the locale
848
766
  */
@@ -1057,6 +975,11 @@ export declare type OpenSsoParamsType = {
1057
975
  * @defaultValue true
1058
976
  */
1059
977
  directExit?: boolean;
978
+ /**
979
+ * If true, opens SSO in same window instead of popup
980
+ * Defaults to true when redirectUrl is provided, false otherwise
981
+ */
982
+ openInSameWindow?: boolean;
1060
983
  /**
1061
984
  * Language of the SSO page (optional)
1062
985
  * It will default to the current user language (or "en" if unsupported language)
@@ -1068,6 +991,17 @@ export declare type OpenSsoParamsType = {
1068
991
  metadata: SsoMetadata;
1069
992
  };
1070
993
 
994
+ /**
995
+ * Response after an SSO has been openned
996
+ */
997
+ export declare type OpenSsoReturnType = {
998
+ /**
999
+ * Optional wallet address, returned when SSO completes via postMessage
1000
+ * Note: Only present when SSO flow completes (not immediately on open)
1001
+ */
1002
+ wallet?: Hex;
1003
+ };
1004
+
1071
1005
  /**
1072
1006
  * Parse the current URL into a Frak Context
1073
1007
  * @param args
@@ -1113,7 +1047,8 @@ declare type RedirectRequestEvent = {
1113
1047
  iframeLifecycle: "redirect";
1114
1048
  data: {
1115
1049
  /**
1116
- * The base url to redirect to (contain a query param `u`, the client need to suffix the current url to the base url)
1050
+ * The base url to redirect to
1051
+ * If it contain a query param `u`, the client need will suffix the current url to the base url
1117
1052
  */
1118
1053
  baseRedirectUrl: string;
1119
1054
  };
@@ -1126,10 +1061,6 @@ declare type RedirectRequestEvent = {
1126
1061
  */
1127
1062
  declare function remove(url: string): string;
1128
1063
 
1129
- declare type RemoveBackupEvent = {
1130
- iframeLifecycle: "remove-backup";
1131
- };
1132
-
1133
1064
  /**
1134
1065
  * Replace the current url with the given Frak context
1135
1066
  * @param args
@@ -1141,12 +1072,6 @@ declare function replaceUrl({ url: baseUrl, context, }: {
1141
1072
  context: Partial<FrakContext> | null;
1142
1073
  }): void;
1143
1074
 
1144
- /**
1145
- * Type used for a one shot request function
1146
- * @inline
1147
- */
1148
- declare type RequestFn<TRpcSchema extends RpcSchema> = <TParameters extends ExtractedParametersFromRpc<TRpcSchema> = ExtractedParametersFromRpc<TRpcSchema>, _ReturnType = ExtractedReturnTypeFromRpc<TRpcSchema, TParameters>>(args: TParameters) => Promise<_ReturnType>;
1149
-
1150
1075
  declare type RestoreBackupEvent = {
1151
1076
  clientLifecycle: "restore-backup";
1152
1077
  data: {
@@ -1154,42 +1079,6 @@ declare type RestoreBackupEvent = {
1154
1079
  };
1155
1080
  };
1156
1081
 
1157
- /**
1158
- * The different Frak RPC error codes
1159
- */
1160
- export declare const RpcErrorCodes: {
1161
- readonly parseError: -32700;
1162
- readonly invalidRequest: -32600;
1163
- readonly methodNotFound: -32601;
1164
- readonly invalidParams: -32602;
1165
- readonly internalError: -32603;
1166
- readonly serverError: -32000;
1167
- readonly clientNotConnected: -32001;
1168
- readonly configError: -32002;
1169
- readonly corruptedResponse: -32003;
1170
- readonly clientAborted: -32004;
1171
- readonly walletNotConnected: -32005;
1172
- readonly serverErrorForInteractionDelegation: -32006;
1173
- };
1174
-
1175
- /**
1176
- * Raw response that we will receive after an rpc request
1177
- * @ignore
1178
- */
1179
- export declare type RpcResponse<TRpcSchema extends RpcSchema, TMethod extends TRpcSchema[number]["Method"] = TRpcSchema[number]["Method"]> = {
1180
- result: Extract<TRpcSchema[number], {
1181
- Method: TMethod;
1182
- }>["ReturnType"];
1183
- error?: never;
1184
- } | {
1185
- result?: never;
1186
- error: {
1187
- code: number;
1188
- message: string;
1189
- data?: unknown;
1190
- };
1191
- };
1192
-
1193
1082
  /**
1194
1083
  * Parameters that will be used to send an interaction to the blockchain
1195
1084
  * @inline
@@ -1315,6 +1204,13 @@ export declare type SsoMetadata = {
1315
1204
  homepageLink?: string;
1316
1205
  };
1317
1206
 
1207
+ declare type SsoRedirectCompleteEvent = {
1208
+ clientLifecycle: "sso-redirect-complete";
1209
+ data: {
1210
+ compressed: string;
1211
+ };
1212
+ };
1213
+
1318
1214
  /**
1319
1215
  * The type for the amount of tokens
1320
1216
  */