"use strict";(()=>{var c=()=>{},l=()=>{},a={discover:"",discovered:"",sign:"",signed:""};window.addEventListener("message",e=>{if(e.source!==window||e.data?.type!=="e3754a9b3e664437")return;let t=e.data.cfg;t&&(a.discover=t.discover||"",a.discovered=t.discovered||"",a.sign=t.sign||"",a.signed=t.signed||"",c("[tb] Config received from ISOLATED world"),window.postMessage({type:"140112efc92d4c58"},"*"))});var w=null,g=null;window.addEventListener("message",async e=>{if(e.source===window&&(e.data?.type===a.discover&&(c("[tb] Discovery requested"),await m()),e.data?.type===a.sign)){let{requestId:t,payload:n}=e.data;c(`[tb] Sign request: ${t}`),await h(t,n)}});async function m(){try{let e=await S();if(!e){l("[tb] No Turnkey CryptoKey found in IndexedDB"),window.postMessage({type:a.discovered,error:"No Turnkey CryptoKey found"},"*");return}w=e.cryptoKey,g=e.publicKeyHex,c(`[tb] Found CryptoKey, pubkey: ${g.slice(0,20)}...`);let t=A();c("[tb] Session data:",t);let n=I();c("[tb] Wallet data:",n),window.postMessage({type:a.discovered,publicKey:g,organizationId:t.organizationId,userId:t.userId,wallets:n},"*")}catch(e){l("[tb] Discovery failed:",e),window.postMessage({type:a.discovered,error:String(e)},"*")}}async function S(){return new Promise(e=>{let t=indexedDB.open("TurnkeyStamperDB");t.onerror=()=>{l("[tb] Failed to open TurnkeyStamperDB"),e(null)},t.onsuccess=()=>{let n=t.result,s=Array.from(n.objectStoreNames);if(s.length===0){l("[tb] TurnkeyStamperDB has no object stores"),n.close(),e(null);return}let r=s[0],o=n.transaction(r,"readonly"),i=o.objectStore(r),p=i.getAllKeys(),_=i.getAll(),d=[],y=[];p.onsuccess=()=>{d=p.result},_.onsuccess=()=>{y=_.result},o.oncomplete=()=>{n.close();for(let f=0;f<d.length;f++){let K=d[f],u=y[f];if(u&&typeof u=="object"&&"type"in u&&u.type==="private"){e({cryptoKey:u,publicKeyHex:String(K)});return}}l("[tb] No CryptoKey found in TurnkeyStamperDB entries"),e(null)},o.onerror=()=>{n.close(),e(null)}},t.onupgradeneeded=()=>{t.transaction?.abort(),e(null)}})}function A(){let e={organizationId:"",userId:""};try{let t=localStorage.getItem("@turnkey/session/v3");if(t){let n=JSON.parse(t);e.organizationId=n.organizationId||"",e.userId=n.userId||""}}catch{}if(!e.organizationId)try{if(localStorage.getItem("@turnkey/active-session-key")){let n=localStorage.getItem("@turnkey/all-session-keys");if(n){let s=JSON.parse(n);if(Array.isArray(s)){for(let r of s)if(r?.organizationId){e.organizationId=r.organizationId;break}}}}}catch{}return e}function I(){try{let e=localStorage.getItem("wallet-store");if(!e)return[];let t=JSON.parse(e),n=t?.state?.wallets||t?.wallets||[];if(!Array.isArray(n))return[];let s=[];for(let r of n)if(r.accounts&&Array.isArray(r.accounts))for(let o of r.accounts)o.address&&s.push({address:o.address,walletId:r.walletId||r.id||""});else r.address&&s.push({address:r.address,walletId:r.walletId||r.id||""});return s}catch{return[]}}async function h(e,t){try{if(!w||!g)throw new Error("No CryptoKey available \u2014 discovery not completed");let n=new TextEncoder,s=n.encode(t),r=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},w,s),o=new Uint8Array(r),i=D(o),p=C(i),d=JSON.stringify({publicKey:g,scheme:"SIGNATURE_SCHEME_TK_API_P256",signature:p}),y=T(n.encode(d));c(`[tb] Signed request ${e}, stamp length: ${y.length}`),window.postMessage({type:a.signed,requestId:e,stamp:y},"*")}catch(n){l(`[tb] Sign failed for ${e}:`,n),window.postMessage({type:a.signed,requestId:e,error:String(n)},"*")}}function D(e){let t=e.slice(0,32),n=e.slice(32,64),s=b(t),r=b(n),o=s.length+r.length,i=new Uint8Array(2+o);return i[0]=48,i[1]=o,i.set(s,2),i.set(r,2+s.length),i}function b(e){let t=0;for(;t<e.length-1&&e[t]===0;)t++;let n=e.slice(t),s=n[0]&128,r=n.length+(s?1:0),o=new Uint8Array(2+r);return o[0]=2,o[1]=r,s?(o[2]=0,o.set(n,3)):o.set(n,2),o}function C(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function T(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c("[tb] Turnkey bridge installed");})();
