UNPKG

@tenprotocol/session-keys

Version:

Framework-agnostic session key management for TEN Protocol

2 lines 7.85 kB
var E={SESSION_KEY_CREATE:"0x0000000000000000000000000000000000000003",SESSION_KEY_RETRIEVE:"0x0000000000000000000000000000000000000007",SESSION_KEY_ACTIVATE:"0x0000000000000000000000000000000000000004",SESSION_KEY_DEACTIVATE:"0x0000000000000000000000000000000000000005",SESSION_KEY_DELETE:"0x0000000000000000000000000000000000000006",SESSION_KEY_EXECUTE:"0x0000000000000000000000000000000000000008"},u=443,P={PRIORITY_FEE_PERCENTILES:[25,50,75],FEE_HISTORY_BLOCKS:10,BASE_FEE_MULTIPLIERS:{LOW:1.1,MEDIUM:1.2,HIGH:1.5}};var c={sessionKey:null,isActive:!1,balance:null,isLoading:!1,error:null},p=new Set,f=!1;try{let e=localStorage.getItem("ten-session-key-state");if(e){let t=JSON.parse(e);c={...c,sessionKey:t.sessionKey,isActive:t.isActive}}}catch(e){console.warn("Failed to load persisted state:",e)}var _=()=>({...c}),s=async e=>{for(;f;)await new Promise(t=>setTimeout(t,50));try{if(f=!0,c={...c,...e},"sessionKey"in e||"isActive"in e)try{localStorage.setItem("ten-session-key-state",JSON.stringify({sessionKey:c.sessionKey,isActive:c.isActive}))}catch(t){console.warn("Failed to persist state:",t)}p.forEach(t=>{try{t(_())}catch(r){console.error("Error in state subscriber:",r)}})}finally{f=!1}},N=e=>(p.add(e),()=>{p.delete(e)}),T=()=>{try{localStorage.removeItem("ten-session-key-state")}catch(e){console.warn("Failed to clear persisted state:",e)}},x=()=>c.sessionKey,C=()=>c.isActive,G=()=>c.balance,D=()=>c.isLoading,B=()=>c.error;var g=e=>{let t=BigInt(e).toString(16);return t=t||"0","0x"+t},A=e=>{let t=e.replace("0x",""),r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=parseInt(t.substr(o,2),16);return r};var b=e=>{let[t,r=""]=e.split("."),o=r.padEnd(18,"0").slice(0,18);return BigInt(t+o)};var y=null,H=e=>{y&&y();let t=()=>{s({isActive:!1,error:new Error("Provider disconnected")})},r=()=>{s({isActive:!1,error:new Error("Chain changed")})};e.on?.("disconnect",t),e.on?.("chainChanged",r),y=()=>{e.removeListener?.("disconnect",t),e.removeListener?.("chainChanged",r)}},h=async e=>{let t=await e.request({method:"eth_chainId"});if(parseInt(t,16)!==u)throw new Error("Session Keys is only for TEN chain, please add or switch to TEN.")},O=async e=>{try{s({isLoading:!0,error:null}),H(e),await h(e),console.log("\u{1F511} Creating session key on TEN network..."),console.log("\u{1F511} Using address:",E.SESSION_KEY_CREATE);let t=await e.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_CREATE,"0x0","latest"]});if(console.log("\u{1F511} Create response:",t),!t||t==="0x0000000000000000000000000000000000000000000000000000000000000000"){console.log("\u{1F511} Creation failed, trying to retrieve existing session key...");let o=await e.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_RETRIEVE,"0x0","latest"]});if(console.log("\u{1F511} Existing key response:",o),o&&o!=="0x0000000000000000000000000000000000000000000000000000000000000000"){let a="0x"+o.slice(-40);return console.log("\u{1F511} Retrieved existing session key:",a),s({sessionKey:a,isLoading:!1}),a}throw new Error("Failed to create session key - both creation and retrieval returned empty response")}let r="0x"+t.slice(-40);return console.log("\u{1F511} Created new session key:",r),s({sessionKey:r,isLoading:!1}),r}catch(t){console.error("\u{1F511} Session key creation error:",t);let r=t instanceof Error?t:new Error("Unknown error");throw s({error:r,isLoading:!1}),r}},k=async(e,t,r,o)=>{try{s({isLoading:!0,error:null}),await h(r),console.log("\u{1F4B0} Funding session key:",e,"with",t,"ETH");let a=b(t),n=g(a),l=await r.request({method:"eth_sendTransaction",params:[{to:e,value:n,from:o}]});console.log("\u{1F4B0} Funding transaction sent:",l);let d=async()=>{let S=await r.request({method:"eth_getTransactionReceipt",params:[l]});return S?(console.log("\u{1F4B0} Funding confirmed!"),S):(await new Promise(I=>setTimeout(I,2e3)),d())};return await d(),s({isLoading:!1}),l}catch(a){let n=a instanceof Error?a:new Error("Unknown error");throw s({error:n,isLoading:!1}),n}},U=async e=>{try{s({isLoading:!0,error:null}),await h(e),await e.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_ACTIVATE,"0x0","latest"]}),s({isActive:!0,isLoading:!1})}catch(t){let r=t instanceof Error?t:new Error("Activation failed");throw s({error:r,isLoading:!1}),r}},R=async e=>{try{s({isLoading:!0,error:null}),await h(e),await e.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_DEACTIVATE,"0x0","latest"]}),s({isActive:!1,isLoading:!1})}catch(t){let r=t instanceof Error?t:new Error("Deactivation failed");throw s({error:r,isLoading:!1}),r}},q=async e=>{try{s({isLoading:!0,error:null}),await h(e),await e.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_DELETE,"0x0","latest"]}),T(),y&&(y(),y=null),s({sessionKey:null,isActive:!1,balance:null,isLoading:!1})}catch(t){let r=t instanceof Error?t:new Error("Deletion failed");throw s({error:r,isLoading:!1}),r}},Y=async e=>{try{s({isLoading:!0,error:null}),await h(e),await e.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_DEACTIVATE,"0x0","latest"]}),await e.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_DELETE,"0x0","latest"]}),s({sessionKey:null,isActive:!1,balance:null,isLoading:!1})}catch(t){let r=t instanceof Error?t:new Error("Cleanup failed");throw s({error:r,isLoading:!1}),r}};import{encode as M}from"rlp";var V=async e=>{let t=await e.request({method:"eth_chainId"});if(parseInt(t,16)!==u)throw new Error("Session Keys is only for TEN chain, please add or switch to TEN.")},W=async(e,t="MEDIUM")=>{let{BASE_FEE_MULTIPLIERS:r}=P;try{let o=await e.request({method:"eth_feeHistory",params:[1,"latest",[]]});if(console.log("Fee history response:",o),!o?.baseFeePerGas?.[0])throw new Error("Invalid fee history response");let a=BigInt(o.baseFeePerGas[0]);console.log("Base fee:",a.toString());let n=BigInt(1e8),l=r[t],d=BigInt(Math.floor(Number(a)*l))+n;return console.log("Priority fee:",n.toString()),console.log("Max fee:",d.toString()),{maxFeePerGas:d,maxPriorityFeePerGas:n}}catch(o){console.warn("Error getting fee history, using fallback values:",o);let a=BigInt(1e9),n=BigInt(1e8),l=r[t];return{maxFeePerGas:BigInt(Math.floor(Number(a)*l))+n,maxPriorityFeePerGas:n}}},j=async(e,t)=>{try{s({isLoading:!0,error:null}),await V(t);let r=x();if(!r)throw new Error("No active session key. Create and activate a session key first.");let o=await t.request({method:"eth_chainId"}),a=parseInt(o,16),n;if(e.nonce!==void 0)n=e.nonce;else{let i=await t.request({method:"eth_getTransactionCount",params:[r,"latest"]});n=parseInt(i,16)}let l,d;if(e.maxFeePerGas&&e.maxPriorityFeePerGas)l=BigInt(e.maxFeePerGas),d=BigInt(e.maxPriorityFeePerGas);else{let i=await W(t,"MEDIUM");l=i.maxFeePerGas,d=i.maxPriorityFeePerGas}let S;if(e.gasLimit)S=e.gasLimit;else{let i=await t.request({method:"eth_estimateGas",params:[{to:e.to,data:e.data,value:e.value||"0x0",from:r}]});S=parseInt(i,16)}let I=[g(a),n===0?"0x":g(n),g(d),g(l),g(S),e.to.toLowerCase(),e.value?.toLowerCase()||"0x0",e.data?.toLowerCase()||"0x",[],"0x","0x","0x"].map(i=>typeof i=="string"&&!i.startsWith("0x")?"0x"+i:i),m=M(I),w;if(m&&typeof m=="object"&&"length"in m)w=Array.from(m).map(F=>F.toString(16).padStart(2,"0")).join("");else throw new Error("Unexpected RLP encoding result");let K=new Uint8Array([2,...A("0x"+w)]),L=btoa(String.fromCharCode(...K)),v=await t.request({method:"eth_getStorageAt",params:[E.SESSION_KEY_EXECUTE,L,"latest"]});return s({isLoading:!1}),v}catch(r){let o=r instanceof Error?r:new Error("Transaction failed");throw s({error:o,isLoading:!1}),o}};export{U as activateSessionKey,Y as cleanupSessionKey,O as createSessionKey,R as deactivateSessionKey,q as deleteSessionKey,k as fundSessionKey,G as getBalance,B as getError,C as getIsActive,D as getIsLoading,x as getSessionKey,_ as getState,j as sendTransaction,N as subscribeToState}; //# sourceMappingURL=index.mjs.map