@stacknet/keyutils 0.4.2 → 0.4.3

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.
@@ -1,2 +1,2 @@
1
- import Ht,{createContext,useContext,useMemo,useState,useCallback,useRef,useEffect}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {Loader2,CheckCircle,Check,Copy,CreditCard,Wallet,Download,X as X$1,ArrowLeft,KeyRound,ExternalLink,AlertTriangle,ChevronDown,ChevronRight,Send,CheckCircle2,AlertCircle,Info,FileText,Minus,Plus,ChevronUp}from'lucide-react';var Qe=createContext(null);function C(){let e=useContext(Qe);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function Se({config:e,callbacks:t={},children:r}){typeof e.apiBaseUrl!="string"&&console.error("[KeyUtils] apiBaseUrl must be a string");let s=useMemo(()=>({config:e,callbacks:t}),[e,t]);return jsx(Qe.Provider,{value:s,children:r})}function z(){if(typeof document>"u")return {};let e=document.cookie.match(/(?:^|;\s*)__csrf=([^;]*)/);return e?{"x-csrf-token":e[1]}:{}}function Je(e,t){if(typeof e!="string"||e.length===0)return t;let r=e.replace(/[\u0000-\u001F\u007F]/g," ");return r.length>500?r.slice(0,500)+"\u2026":r}async function E(e,t){try{let r=await e.json();if(r&&typeof r=="object"&&"error"in r)return Je(r.error,t)}catch{}return t}function D(e,t="#"){if(!e||typeof e!="string")return t;let r=e.trim();if(r===""||r==="#")return t;if(r.startsWith("/")||r.startsWith("./")||r.startsWith("../"))return r;try{let s=new URL(r);if(s.protocol==="http:"||s.protocol==="https:")return s.toString()}catch{}return t}function l(...e){return twMerge(clsx(e))}function R(e){return e==null?"0":e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Xe(e,t){return t<=0?0:Math.min(100,Math.round(e/t*100))}function Ze(e){return e>=70?"bg-green-500":e>=30?"bg-yellow-500":"bg-red-500"}function G(e){let t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e,r=new Date(t);return isNaN(r.getTime())?String(e):r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function et(){if(typeof navigator>"u")return "mac";let e=navigator.userAgent.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/win/.test(e)?"windows":/linux/.test(e)?"linux":"mac"}function rt(){let{config:e}=C(),[t,r]=useState(null),[s,g]=useState(true),[u,a]=useState(null),i=useRef(true),o=useRef(e.apiBaseUrl);o.current=e.apiBaseUrl;let n=async()=>{try{i.current&&(g(!0),a(null));let f=await fetch(`${o.current}/api/keys/pricing`,{credentials:"include"});if(!f.ok)throw new Error(await E(f,`Pricing unavailable (${f.status})`));let m=await f.json();i.current&&r(m);}catch(f){i.current&&a(f instanceof Error?f.message:"Failed to fetch pricing");}finally{i.current&&g(false);}};return useEffect(()=>{i.current=true,n();let f=setInterval(n,6e4);return ()=>{i.current=false,clearInterval(f);}},[]),{pricing:t,loading:s,error:u,refresh:n}}function st(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[g,u]=useState(null),[a,i]=useState(null);return {mint:useCallback(async(n,f,m=1)=>{try{s(!0),i(null),t.onPaymentComplete?.(n,f);let p=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({paymentMethod:n,paymentRef:f,quantity:m,stackId:e.stackId})});if(!p.ok)throw new Error(await E(p,`Key generation failed (${p.status})`));let d=await p.json(),x=d.keys?.[0]||d,N={success:!0,key:{id:x.keyId||x.id||"",key:x.key||"",userId:x.userId||"",status:"active",tokenBalance:x.tokenBalance??x.currentTokenBalance??0,maxTokens:x.initialTokenBalance??x.tokenBalance??0,createdAt:String(x.createdAt||Date.now())},transactionId:f};return u(N),t.onMintSuccess?.(N),N}catch(p){let d=p instanceof Error?p:new Error("Key generation failed");return i(d.message),t.onMintError?.(d),{success:false,error:d.message}}finally{s(false);}},[e.apiBaseUrl,t]),minting:r,result:g,error:a}}function nt(){let{config:e}=C(),[t,r]=useState(false),[s,g]=useState(null),u=useRef(true);return {createSession:useCallback(async(i,o)=>{try{r(!0),g(null);let n=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({priceCents:i,quantity:o,stackId:e.stackId,referrerUrl:window.location.href})});if(!n.ok)throw new Error(await E(n,`Checkout failed (${n.status})`));let{url:f}=await n.json();if(!f)throw new Error("No checkout URL returned");let m;try{m=new URL(f);}catch{throw new Error("Invalid checkout URL")}if(m.protocol!=="https:"||!/(^|\.)stripe\.com$/.test(m.hostname))throw new Error("Refusing to redirect to non-Stripe URL");try{sessionStorage.setItem("keyutils_stripe_pending","1"),sessionStorage.setItem("keyutils_stripe_quantity",String(o));}catch{}window.location.href=m.toString();}catch(n){if(u.current){let f=n instanceof Error?n.message:"Checkout failed";g(f),r(false);}}},[e.apiBaseUrl,e.stackId]),loading:t,error:s}}var it=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function Ue({amountSol:e,onSuccess:t,onError:r,disabled:s,className:g,style:u}){let{config:a}=C(),[i,o]=useState(false),[n,f]=useState(null),m=!!(a.merchantWallet&&it.test(a.merchantWallet)),p=useCallback(async()=>{if(m)try{o(!0),f(null);let{Connection:d,PublicKey:x,Transaction:N,SystemProgram:I,LAMPORTS_PER_SOL:w}=await import('@solana/web3.js'),L=typeof window<"u"?window.solana:void 0;if(!L||typeof L!="object"||!L.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let A=L,P;try{P=new x(a.merchantWallet);}catch{throw new Error("Invalid merchant wallet address.")}let re=await A.connect(),M=new x(re.publicKey.toString()),F="https://api.mainnet-beta.solana.com",se=D(a.solanaRpcUrl,F),de=se==="#"?F:se,Ce=new d(de),{blockhash:O}=await Ce.getLatestBlockhash(),ee=BigInt(Math.floor(e*1e9)),ce=a.protocolTreasuryWallet,me=a.protocolFeeBps??500,ue=new N({recentBlockhash:O,feePayer:M});if(ce&&it.test(ce)&&me>0){let He=ee*BigInt(me)/10000n,Tt=ee-He,Kt=new x(ce);ue.add(I.transfer({fromPubkey:M,toPubkey:P,lamports:Number(Tt)}),I.transfer({fromPubkey:M,toPubkey:Kt,lamports:Number(He)}));}else ue.add(I.transfer({fromPubkey:M,toPubkey:P,lamports:Number(ee)}));let{signature:ye}=await A.signAndSendTransaction(ue);t(ye);}catch(d){let x=d instanceof Error?d:new Error("Payment failed");f(x.message),r?.(x);}finally{o(false);}},[e,a.merchantWallet,m,t,r]);return jsxs("div",{children:[jsx("button",{onClick:p,disabled:s||i||!m,"aria-label":`Pay ${e.toFixed(4)} SOL`,className:l("flex w-full items-center justify-center gap-2 rounded-lg bg-purple-600 px-4 py-6 font-medium text-white transition-colors hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed",g),style:u,children:i?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 animate-spin"}),"Processing..."]}):jsxs(Fragment,{children:["Pay ",e.toFixed(4)," SOL"]})}),n&&jsx("p",{className:"mt-2 text-center text-xs text-red-500",children:n})]})}function Be({result:e,className:t,style:r}){let[s,g]=useState(false),u=useRef(null);useEffect(()=>()=>{u.current&&clearTimeout(u.current);},[]);let a=useCallback(()=>{e.key?.key&&(navigator.clipboard.writeText(e.key.key),g(true),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>g(false),2e3));},[e.key?.key]);return !e.success||!e.key?null:jsxs("div",{className:l("rounded-lg border border-green-500/20 bg-green-500/10 p-6 text-center",t),style:r,children:[jsx(CheckCircle,{className:"mx-auto mb-3 h-12 w-12 text-green-500"}),jsx("h3",{className:"mb-2 text-lg font-semibold text-foreground",children:"Key Generated!"}),jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Your node key has been successfully generated."}),jsxs("div",{className:"mx-auto flex max-w-md items-center gap-2 rounded-md border bg-background p-3",children:[jsx("code",{className:"flex-1 truncate text-xs text-foreground",children:e.key.key}),jsx("button",{onClick:a,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]})]})}function X({className:e}){return jsx("div",{className:l("animate-pulse rounded-xl bg-muted",e)})}function Le(){return jsxs("div",{className:"space-y-6",children:[jsxs("div",{className:"px-6 py-10 flex flex-col items-center gap-3",children:[jsx(X,{className:"h-14 w-48"}),jsx(X,{className:"h-5 w-64"})]}),jsx(X,{className:"h-[72px] w-full rounded-2xl"}),jsx(X,{className:"h-[68px] w-full rounded-2xl"}),jsx(X,{className:"h-[60px] w-full rounded-2xl"})]})}function oe({count:e=3}){return jsx("div",{className:"space-y-3",children:Array.from({length:e}).map((t,r)=>jsxs("div",{className:"rounded-xl border p-4 space-y-3",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx(X,{className:"h-4 w-32"}),jsx(X,{className:"h-4 w-16"})]}),jsx(X,{className:"h-2 w-full rounded-full"}),jsxs("div",{className:"flex justify-between",children:[jsx(X,{className:"h-3 w-24"}),jsx(X,{className:"h-3 w-20"})]})]},r))})}function sr({quantity:e,max:t,onChange:r}){return jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-muted/20 px-6 py-6",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:"Quantity"}),jsxs("div",{className:"flex items-center gap-0 rounded-xl bg-background",children:[jsx("button",{onClick:()=>r(Math.max(1,e-1)),disabled:e<=1,"aria-label":"Decrease quantity",className:"flex h-12 w-12 items-center justify-center rounded-l-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Minus,{className:"h-5 w-5"})}),jsx("span",{className:"flex h-12 w-14 items-center justify-center border-x text-xl font-bold text-foreground","aria-live":"polite",children:e}),jsx("button",{onClick:()=>r(Math.min(t,e+1)),disabled:e>=t,"aria-label":"Increase quantity",className:"flex h-12 w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Plus,{className:"h-5 w-5"})})]})]})}function ut({pricing:e,quantity:t}){let[r,s]=useState(false),g=e.priceUsd*t;return jsxs("div",{className:"rounded-2xl border bg-background",children:[jsxs("button",{onClick:()=>s(!r),"aria-expanded":r,className:"flex w-full items-center justify-between px-6 py-6 text-left",children:[jsxs("span",{className:"text-foreground",children:[jsxs("span",{className:"text-xl font-bold",children:["$",g.toFixed(2)]})," ",jsx("span",{className:"text-sm text-muted-foreground",children:"total fees included"})]}),r?jsx(ChevronUp,{className:"h-5 w-5 text-muted-foreground"}):jsx(ChevronDown,{className:"h-5 w-5 text-muted-foreground"})]}),r&&jsxs("div",{className:"border-t px-6 pb-8 pt-4 space-y-3 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsxs("span",{className:"text-muted-foreground",children:["Node Key \xD7 ",t]}),jsxs("span",{className:"text-foreground",children:["$",(e.priceUsd*t).toFixed(2)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Keys sold"}),jsx("span",{className:"text-foreground",children:e.keysSold})]}),e.daysUntilHalving>0&&jsxs("div",{className:"flex justify-between text-muted-foreground",children:[jsx("span",{children:"Next refresh"}),jsxs("span",{children:[e.daysUntilHalving," day",e.daysUntilHalving!==1?"s":""]})]}),jsxs("div",{className:"flex justify-between border-t pt-3 font-semibold",children:[jsx("span",{className:"text-foreground",children:"Total"}),jsxs("span",{className:"text-foreground",children:["$",g.toFixed(2)]})]})]})]})}function Ee({className:e,style:t}){let{config:r}=C(),{pricing:s,loading:g,error:u,refresh:a}=rt(),{mint:i,minting:o,result:n,error:f}=st(),{createSession:m,loading:p,error:d}=nt(),[x,N]=useState(1),[I,w]=useState(r.paymentMethods?.includes("stripe")?"stripe":"solana"),[L,A]=useState(0),[P,re]=useState(false),M=Ht.useRef(x);M.current=x;let F=Math.max(1,r.maxQuantity||5),se=[...r.paymentMethods||["solana"]].sort((O,ee)=>O==="stripe"?-1:ee==="stripe"?1:0);if(useEffect(()=>{if(typeof window>"u")return;let ee=new URLSearchParams(window.location.search).get("session_id");if(!ee){try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}return}if(/^cs_(test|live)_/.test(ee)&&!P&&!n?.success){let ce=false;try{ce=sessionStorage.getItem("keyutils_stripe_pending")==="1";}catch{}if(!ce)return;try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}re(true);let me=new URL(window.location.href);me.searchParams.delete("session_id"),window.history.replaceState({},"",me.toString());let ue=M.current;try{let ye=sessionStorage.getItem("keyutils_stripe_quantity");ye&&(ue=parseInt(ye,10)||1,sessionStorage.removeItem("keyutils_stripe_quantity"));}catch{}i("stripe",ee,ue);}},[P,n,i]),n?.success)return jsx("div",{className:l("flex flex-col items-center justify-center",e),style:t,children:jsx(Be,{result:n})});if(P||o)return jsx("div",{className:l("flex flex-col",e),style:t,children:jsx(Le,{})});if(g)return jsx("div",{className:l("flex flex-col",e),style:t,children:jsx(Le,{})});if(u||!s)return jsxs("div",{className:l("flex flex-col items-center justify-center gap-4 py-24",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load pricing"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u||"Please check your connection and try again."})]}),jsx("button",{onClick:()=>a(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let de=async O=>{A(2),await i(I,O,x);},Ce=()=>{m(s.priceCents,x);};return jsx("div",{className:l("flex flex-col",e),style:t,children:jsxs("div",{className:"space-y-6",children:[L===0&&jsxs(Fragment,{children:[r.keyImage&&jsx("img",{src:D(r.keyImage),alt:"Node Key",className:r.keyImageClass||"w-1/2 mx-auto"}),jsxs("div",{className:"px-6 py-10 text-center",children:[jsxs("p",{className:"text-5xl font-bold tracking-tight text-foreground md:text-6xl",children:["$",s.priceUsd.toFixed(2)]}),jsxs("p",{className:"mt-2 text-base text-muted-foreground",children:["per key \xB7 ",s.tokenAllocationFormatted||R(s.tokenAllocation)," tokens included"]})]}),jsx(sr,{quantity:x,max:F,onChange:N}),jsx(ut,{pricing:s,quantity:x}),jsx("button",{onClick:()=>A(1),className:"w-full rounded-2xl bg-foreground py-6 text-center text-base font-semibold text-background transition-colors hover:bg-foreground/90",children:"Continue to Payment"})]}),L===1&&jsxs(Fragment,{children:[se.length>1&&jsx("div",{role:"tablist",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:se.map(O=>jsxs("button",{role:"tab","aria-selected":I===O,onClick:()=>w(O),className:l("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-4 text-sm font-medium transition-colors",I===O?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[O==="stripe"?jsx(CreditCard,{className:"h-5 w-5"}):jsx(Wallet,{className:"h-5 w-5"}),O==="stripe"?"Credit Card":"Crypto"]},O))}),jsx(ut,{pricing:s,quantity:x}),I==="stripe"?jsxs(Fragment,{children:[jsx("button",{onClick:Ce,disabled:p,className:"flex w-full items-center justify-center gap-2 rounded-2xl bg-foreground py-6 text-base font-semibold text-background transition-colors hover:bg-foreground/90 disabled:opacity-50",children:p?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-5 w-5 animate-spin"}),"Redirecting to Stripe..."]}):jsxs(Fragment,{children:[jsx(CreditCard,{className:"h-5 w-5"}),"Pay with Card"]})}),d&&jsx("p",{className:"text-center text-sm text-red-500",children:d})]}):I==="solana"?jsx(Ue,{amountSol:s.priceSol??0,onSuccess:de,className:"rounded-2xl py-5 text-base"}):null,f&&jsx("p",{className:"text-center text-sm text-red-500",children:f}),jsx("button",{onClick:()=>A(0),className:"w-full py-3 text-center text-sm text-muted-foreground hover:text-foreground transition-colors",children:"\u2190 Back"})]})]})})}var ir={ios:"iOS",android:"Android",windows:"Windows",mac:"macOS",linux:"Linux"},lr=["mac","windows","linux","ios","android"];function je({downloads:e,className:t,style:r}){let{config:s}=C(),g=useMemo(()=>et(),[]),u=e||lr.map(o=>({platform:o,label:ir[o],url:"#",compatible:o===g})),a=u.find(o=>o.compatible)||u[0],i=u.filter(o=>o.platform!==a.platform);return jsxs("div",{className:l("space-y-8",t),style:r,children:[jsxs("div",{className:"flex flex-col items-center gap-6 pt-4 mt-4",children:[s.aispImage&&jsx("img",{src:D(s.aispImage),alt:"aiSP",className:"w-full sm:w-1/2 mx-auto px-4 sm:px-0"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-lg sm:text-2xl font-medium text-foreground",children:"Download the AI Service Provider App"}),jsx("p",{className:"mt-1 text-sm sm:text-base text-muted-foreground",children:"Load your keys and run your node."})]}),jsxs("a",{href:D(a.url),target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-3 rounded-full px-10 py-4 text-lg font-semibold text-white transition-colors hover:opacity-90",style:{backgroundColor:"#0900f4"},children:[jsx(Download,{className:"h-5 w-5"}),"Get aiSP for ",a.label]})]}),jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["aiSP is also available on"," ",i.map((o,n)=>jsxs(Ht.Fragment,{children:[n>0&&(n===i.length-1?" and ":", "),jsx("a",{href:D(o.url),target:"_blank",rel:"noopener noreferrer",className:"font-medium underline transition-colors hover:text-foreground",style:{color:"#066bff"},children:o.label})]},o.platform)),"."]}),jsxs("div",{className:"flex flex-col items-center gap-2 mt-12",children:[jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["Source code is available on",jsx("a",{href:"https://github.com/stack-net",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80 color-[#0900f4]",children:"Github"})]}),jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["By downloading, you agree to the",jsx("a",{href:D(s.termsUrl,"/terms"),target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80",children:"Open Source Applications Terms"})]})]})]})}function mr(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function H(){let{config:e}=C(),[t,r]=useState([]),[s,g]=useState(true),[u,a]=useState(null),i=useRef(true),o=e.apiBaseUrl,n=useCallback(async()=>{try{g(!0),a(null);let m=await fetch(`${o}/api/keys`,{credentials:"include"});if(!m.ok)throw new Error(await E(m,`Failed to fetch keys (${m.status})`));let p=await m.json(),d=Array.isArray(p)?p:p.keys??[];i.current&&r(d.map(mr));}catch(m){i.current&&a(m instanceof Error?m.message:"Failed to fetch keys");}finally{i.current&&g(false);}},[o]);useEffect(()=>(i.current=true,n(),()=>{i.current=false;}),[n]);let f=t.reduce((m,p)=>m+p.tokenBalance,0);return {keys:t,totalBalance:f,loading:s,error:u,refresh:n}}function Q({current:e,max:t,className:r,style:s,showLabel:g=true}){let u=Xe(e,t),a=Ze(u);return jsxs("div",{className:l("w-full",r),style:s,children:[g&&jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:[R(e)," / ",R(t)]}),jsxs("span",{children:[u,"%"]})]}),jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-muted",children:jsx("div",{className:l("h-full rounded-full transition-all duration-500",a),style:{width:`${u}%`}})})]})}function Ne(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[g,u]=useState(null),[a,i]=useState(null),o=useRef(true),n=useCallback(async(m,p)=>{try{s(!0),i(null);let d=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(m)}/list`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({askPriceCents:p,stackId:e.stackId,stackName:e.stackName})});if(!d.ok)throw new Error(await E(d,`Listing failed (${d.status})`));let x=await d.json();return o.current&&(u(x),t.onListingCreated?.(x)),x}catch(d){let x=d instanceof Error?d.message:"Listing failed";return o.current&&i(x),null}finally{o.current&&s(false);}},[e.apiBaseUrl,e.stackId,e.stackName,t]),f=useCallback(async m=>{try{s(!0),i(null);let p=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(m)}/list`,{method:"DELETE",headers:{...z()},credentials:"include"});if(!p.ok)throw new Error(await E(p,`Delist failed (${p.status})`));return o.current&&u(null),!0}catch(p){let d=p instanceof Error?p.message:"Delist failed";return o.current&&i(d),false}finally{o.current&&s(false);}},[e.apiBaseUrl]);return {listKey:n,delistKey:f,listing:r,result:g,error:a}}function ve(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[g,u]=useState(null),[a,i]=useState(null),o=useRef(true);return {transferKey:useCallback(async(f,m)=>{try{s(!0),i(null);let p=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(f)}/transfer`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({recipientId:m})});if(!p.ok)throw new Error(await E(p,`Transfer failed (${p.status})`));let d=await p.json();return o.current&&(u(d),t.onTransferComplete?.(d)),d}catch(p){let d=p instanceof Error?p.message:"Transfer failed";return o.current&&i(d),null}finally{o.current&&s(false);}},[e.apiBaseUrl,t]),transferring:r,result:g,error:a}}function he(e){let{config:t}=C(),[r,s]=useState([]),[g,u]=useState(false),[a,i]=useState(null),o=useRef(true),n=t.apiBaseUrl,f=useCallback(async()=>{if(e)try{u(!0),i(null);let m=await fetch(`${n}/api/keys/${encodeURIComponent(e)}/ledger`,{credentials:"include"});if(!m.ok)throw new Error(await E(m,`Failed to fetch ledger (${m.status})`));let p=await m.json();o.current&&s(Array.isArray(p)?p:p.entries??[]);}catch(m){o.current&&i(m instanceof Error?m.message:"Failed to fetch ledger");}finally{o.current&&u(false);}},[n,e]);return useEffect(()=>(o.current=true,f(),()=>{o.current=false;}),[f]),{entries:r,loading:g,error:a,refresh:f}}function ge({open:e,onClose:t,title:r,children:s}){let g=useRef(null),[u,a]=useState(false),[i,o]=useState(false),n=useCallback(f=>{f.key==="Escape"&&t();},[t]);return useEffect(()=>{if(e)a(true),document.addEventListener("keydown",n),document.body.style.overflow="hidden",requestAnimationFrame(()=>{requestAnimationFrame(()=>o(true));});else {o(false);let f=setTimeout(()=>{a(false),document.body.style.overflow="";},300);return document.removeEventListener("keydown",n),()=>clearTimeout(f)}return ()=>{document.removeEventListener("keydown",n);}},[e,n]),u?jsxs("div",{className:"fixed inset-0 z-50 flex items-end justify-center",children:[jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm transition-opacity duration-300",style:{opacity:i?1:0},onClick:t}),jsxs("div",{ref:g,className:l("relative z-10 w-full max-w-xl rounded-t-2xl bg-background shadow-2xl","max-h-[85vh] flex flex-col","transition-transform duration-300 ease-out"),style:{transform:i?"translateY(0)":"translateY(100%)"},children:[jsx("div",{className:"flex justify-center pt-3 pb-1",children:jsx("div",{className:"h-1 w-10 rounded-full bg-muted-foreground/30"})}),r&&jsxs("div",{className:"flex items-center justify-between px-5 pb-3 pt-1",children:[jsx("h3",{className:"text-lg font-semibold text-foreground",children:r}),jsx("button",{onClick:t,className:"rounded-full p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors","aria-label":"Close",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"flex-1 overflow-y-auto px-5 pb-8",children:s})]})]}):null}function Rr({nodeKey:e,onSuccess:t}){let{transferKey:r,transferring:s,result:g,error:u}=ve(),[a,i]=useState(""),[o,n]=useState(false),f=a.trim()===e.userId,m=a.trim().length>0&&o&&!f&&!s,p=async()=>{if(!m)return;await r(e.id,a.trim())&&t();};return g?jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Transfer Complete"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Key transferred successfully"})]}):jsxs("div",{className:"space-y-5",children:[jsxs("div",{children:[jsx("label",{className:"mb-1.5 block text-sm font-semibold text-foreground",children:"Recipient User ID"}),jsx("input",{type:"text",value:a,onChange:d=>{i(d.target.value),n(false);},placeholder:"Enter recipient's user ID or global ID",className:"w-full rounded-xl border border-border bg-background px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground focus:border-foreground/30 focus:outline-none focus:ring-1 focus:ring-foreground/10"}),f&&jsx("p",{className:"mt-1.5 text-xs text-red-500",children:"Cannot transfer a key to yourself"})]}),a.trim().length>0&&!f&&jsx("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertTriangle,{className:"mt-0.5 h-5 w-5 shrink-0 text-amber-500"}),jsxs("div",{className:"space-y-3",children:[jsxs("div",{children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Confirm Transfer"}),jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Transferring key"," ",jsx("span",{className:"font-mono font-medium",children:e.keyIndex?`#${e.keyIndex}`:e.id.slice(0,12)})," ","(",R(e.tokenBalance)," tokens) to"," ",jsxs("span",{className:"font-mono font-medium",children:[a.trim().slice(0,20),a.trim().length>20?"...":""]})]})]}),jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[jsx("input",{type:"checkbox",checked:o,onChange:d=>n(d.target.checked),className:"mt-0.5 h-4 w-4 rounded border-border"}),jsx("span",{className:"text-xs text-muted-foreground",children:"I confirm this transfer is permanent and cannot be undone."})]})]})]})}),u&&jsx("p",{className:"text-sm text-red-500",children:u}),jsx("button",{onClick:p,disabled:!m,className:l("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",m?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:s?jsxs(Fragment,{children:[jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Transferring..."]}):jsxs(Fragment,{children:[jsx(Send,{className:"h-4 w-4"}),"Transfer Key"]})})]})}function Tr({nodeKey:e,onSuccess:t}){let{config:r}=C(),{listKey:s,listing:g,result:u,error:a}=Ne(),[i,o]=useState(""),[n,f]=useState(false),m=parseInt(i.replace(/[^0-9]/g,""),10)||0,d=m>0&&Number.isFinite(m)&&n&&!g,x=async()=>{if(!d)return;let N=m*100;await s(e.id,N)&&t();};return u?jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the marketplace."}),jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsx("code",{children:u.listingId})]})]}):jsxs("div",{className:"space-y-5",children:[jsxs("div",{children:[jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm font-semibold text-foreground",children:"Listing Price (USD)"}),jsxs("div",{className:"relative",children:[jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:i,onChange:N=>{let I=N.target.value.replace(/[^0-9]/g,""),w=parseInt(I,10);o(isNaN(w)?"":w.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-6 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxs("div",{className:"flex items-start gap-3",children:[jsx("button",{type:"button",role:"checkbox","aria-checked":n,onClick:()=>f(!n),className:l("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors cursor-pointer",n?"border-foreground bg-foreground":"border-muted-foreground/40"),children:n&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsx("a",{href:D(r.termsUrl,"/terms"),className:"text-foreground underline",target:"_blank",rel:"noopener noreferrer",children:"Terms"})]})]}),a&&jsx("p",{className:"text-sm text-red-500",children:a}),jsxs("button",{onClick:x,disabled:!d,className:l("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",d?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsx(ExternalLink,{className:"h-4 w-4"}),g?"Listing...":"List on Marketplace"]})]})}function Kr({nodeKey:e}){let[t,r]=useState(false);if(!e.paperWork)return jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[jsx(FileText,{className:"h-10 w-10 text-muted-foreground"}),jsx("p",{className:"text-sm text-muted-foreground",children:"This key has no paperwork to file."})]});let s=()=>{navigator.clipboard.writeText(e.paperWork||""),r(true),setTimeout(()=>r(false),2e3);};return jsxs("div",{className:"space-y-5",children:[jsxs("div",{children:[jsx("label",{className:"mb-2 block text-sm font-semibold text-foreground",children:"Paperwork"}),jsxs("div",{className:"relative rounded-xl border bg-muted/30 p-4",children:[jsx("pre",{className:"whitespace-pre-wrap break-all text-sm text-foreground font-mono",children:e.paperWork}),jsx("button",{onClick:s,className:"absolute top-3 right-3 rounded-lg p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors","aria-label":"Copy paperwork",children:t?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]})]}),jsx("p",{className:"text-xs text-muted-foreground",children:"Filing paperwork submits the key's documentation on-chain for permanent record."}),jsxs("button",{disabled:true,className:"flex w-full items-center justify-center gap-2 rounded-xl bg-muted py-4 text-sm font-semibold text-muted-foreground cursor-not-allowed",children:[jsx(FileText,{className:"h-4 w-4"}),"File Paperwork (Coming Soon)"]})]})}function We({nodeKey:e,onBack:t,onKeysChanged:r,className:s,style:g}){let{config:u}=C(),{entries:a,loading:i}=he(e.id),[o,n]=useState(null),[f,m]=useState(false),p=()=>{n(null),r?.();},d=()=>{e.key&&(navigator.clipboard.writeText(e.key),m(true),setTimeout(()=>m(false),2e3));},x=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500";return jsxs("div",{className:l("space-y-5",s),style:g,children:[jsxs("button",{onClick:t,className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[jsx(ArrowLeft,{className:"h-4 w-4"}),"Back to Keys"]}),jsx("div",{className:"space-y-1",children:jsxs("div",{className:"flex items-center justify-between",children:[jsx("h2",{className:"text-2xl font-bold text-foreground",children:e.keyIndex?`Key #${e.keyIndex}`:e.label||e.id.slice(0,16)}),jsx("span",{className:l("text-sm font-medium capitalize",x),children:e.status})]})}),e.key&&jsxs("div",{className:"flex items-center gap-2",children:[jsx("code",{className:"flex-1 truncate rounded-lg bg-muted px-3 py-2 text-xs text-muted-foreground",children:e.key}),jsx("button",{onClick:d,"aria-label":"Copy key",className:"shrink-0 rounded-lg p-2 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",children:f?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]}),jsx(Q,{current:e.tokenBalance,max:e.maxTokens,showLabel:true}),jsxs("div",{className:"rounded-xl bg-muted/30 p-5 space-y-2.5 text-sm",children:[e.keyIndex&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxs("span",{className:"text-foreground font-semibold",children:["#",e.keyIndex]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:e.id})]}),(u.stackName||e.stackName)&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Stack"}),jsx("span",{className:"text-foreground",children:e.stackName||u.stackName})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Tokens"}),jsxs("span",{className:"text-foreground",children:[R(e.tokenBalance)," / ",R(e.maxTokens)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:G(e.createdAt)})]}),e.expiresAt&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Expires"}),jsx("span",{className:"text-foreground",children:G(e.expiresAt)})]})]}),e.paperWork&&jsxs("div",{className:"rounded-xl border bg-muted/30 p-5",children:[jsx("h3",{className:"text-sm font-semibold text-foreground mb-2",children:"Paperwork"}),jsx("pre",{className:"whitespace-pre-wrap break-all text-xs text-muted-foreground font-mono",children:e.paperWork})]}),e.status==="active"&&jsxs("div",{className:"grid grid-cols-3 gap-3",children:[jsx("button",{onClick:()=>n("transfer"),className:"flex items-center justify-center rounded-xl border border-border p-4 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Transfer"}),jsx("button",{onClick:()=>n("sell"),className:"flex items-center justify-center rounded-xl border border-border p-4 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Sell"}),jsx("button",{onClick:()=>n("file"),className:l("flex items-center justify-center rounded-xl border border-border p-4 text-sm font-medium transition-colors",e.paperWork?"text-foreground hover:bg-muted/50":"text-muted-foreground cursor-not-allowed opacity-50"),disabled:!e.paperWork,children:"File"})]}),jsxs("div",{children:[jsx("h3",{className:"text-sm font-semibold text-foreground mb-3",children:"Ledger"}),i?jsx("p",{className:"text-xs text-muted-foreground",children:"Loading ledger..."}):a.length===0?jsx("p",{className:"text-xs text-muted-foreground",children:"No ledger entries."}):jsxs("div",{className:"space-y-1.5",children:[a.slice(0,20).map(N=>jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsxs("span",{className:l("font-medium",N.type==="credit"||N.type==="reward"?"text-green-500":"text-red-500"),children:[N.type==="credit"||N.type==="reward"?"+":"-",R(Math.abs(N.amount))]}),jsx("span",{className:"text-muted-foreground",children:N.description})]}),jsx("span",{className:"text-muted-foreground",children:G(N.createdAt)})]},N.id)),a.length>20&&jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Showing 20 of ",a.length," entries"]})]})]}),jsx(ge,{open:o==="transfer",onClose:()=>n(null),title:"Transfer Key",children:jsx(Rr,{nodeKey:e,onSuccess:p})}),jsx(ge,{open:o==="sell",onClose:()=>n(null),title:"Sell Key",children:jsx(Tr,{nodeKey:e,onSuccess:p})}),jsx(ge,{open:o==="file",onClose:()=>n(null),title:"File Paperwork",children:jsx(Kr,{nodeKey:e})})]})}function Ir({nodeKey:e,onClick:t}){let r=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500";return jsx("button",{onClick:t,className:"flex w-full items-start gap-3 rounded-xl border border-border p-4 text-left transition-all hover:border-foreground/20 hover:bg-muted/30",children:jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:l("text-xs font-medium capitalize",r),children:e.status})]}),jsx(Q,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"}),e.paperWork&&jsx("span",{className:"mt-1.5 inline-block text-xs text-muted-foreground",children:"Has paperwork"})]})})}function Oe({className:e,style:t}){let{keys:r,loading:g,error:u,refresh:a}=H(),[i,o]=useState(null),[n,f]=useState("active"),m=r.filter(x=>x.status===n),p=m.reduce((x,N)=>x+N.tokenBalance,0),d=r.find(x=>x.id===i);return d?jsx(We,{nodeKey:d,onBack:()=>o(null),onKeysChanged:()=>{o(null),a();},className:e,style:t}):g?jsxs("div",{className:l("space-y-4",e),style:t,children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx(oe,{count:3})]}):u?jsxs("div",{className:l("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u})]}),jsx("button",{onClick:()=>a(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]}):r.length===0?jsxs("div",{className:l("flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed py-16",e),style:t,children:[jsx(KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]})]}):jsxs("div",{className:l("space-y-4",e),style:t,children:[jsxs("div",{className:"flex items-center justify-between mt-3",children:[jsx("h3",{className:"text-2xl font-semibold text-foreground",children:"Your Keys"}),jsxs("span",{className:"text-xs text-muted-foreground",children:[m.length," key",m.length!==1?"s":""," \xB7 ",R(p)," tokens"]}),jsx("div",{className:"flex gap-1 rounded-lg bg-muted/50 p-1",children:["active","listed"].map(x=>jsx("button",{onClick:()=>f(x),className:l("rounded-md px-3 py-1 text-xs font-medium capitalize transition-all",n===x?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:x},x))})]}),m.length===0?jsxs("div",{className:"flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-12",children:[jsx(KeyRound,{className:"h-8 w-8 text-muted-foreground"}),jsxs("p",{className:"text-sm text-muted-foreground",children:["No ",n," keys."]})]}):jsx("div",{className:"space-y-2",children:m.map(x=>jsx(Ir,{nodeKey:x,onClick:()=>o(x.id)},x.id))})]})}var Br=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"keys",label:"Keys"}];function Lr({active:e,onChange:t}){return jsx("div",{role:"tablist","aria-label":"Key actions",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:Br.map(({id:r,label:s})=>jsx("button",{role:"tab","aria-selected":e===r,"aria-controls":`panel-${r}`,id:`tab-${r}`,onClick:()=>t(r),className:l("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium transition-all",e===r?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:jsx("span",{className:"inline",children:s})},r))})}function Er({defaultTab:e="buy",className:t,style:r}){let[s,g]=useState(e);return jsxs("div",{className:l("flex flex-col",t),style:r,children:[jsx("div",{className:"sticky top-0 z-10 bg-background/80 px-5 pb-3 pt-2 sm:pt-5 backdrop-blur-sm sm:px-10 md:px-16 lg:px-20",children:jsx("div",{className:"mx-auto max-w-xl",children:jsx(Lr,{active:s,onChange:g})})}),jsx("div",{className:"flex flex-1 flex-col px-5 pb-8 sm:px-10 md:px-16 md:pb-12 lg:px-20",children:jsx("div",{className:"mx-auto w-full max-w-xl flex-1",children:jsxs("div",{role:"tabpanel",id:`panel-${s}`,"aria-labelledby":`tab-${s}`,children:[s==="buy"&&jsx(Ee,{className:"flex-1"}),s==="use"&&jsx(je,{className:"flex-1"}),s==="keys"&&jsx(Oe,{className:"flex-1"})]})})})]})}function jr({apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:g,stripePublicKey:u,theme:a,maxQuantity:i,keyImage:o,keyImageClass:n,aispImage:f,termsUrl:m,onMintSuccess:p,onMintError:d,onPaymentStart:x,onPaymentComplete:N,onListingCreated:I,onTransferComplete:w,defaultTab:L,className:A,style:P}){return jsx(Se,{config:{apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:g,stripePublicKey:u,theme:a,maxQuantity:i,keyImage:o,keyImageClass:n,aispImage:f,termsUrl:m},callbacks:{onMintSuccess:p,onMintError:d,onPaymentStart:x,onPaymentComplete:N,onListingCreated:I,onTransferComplete:w},children:jsx(Er,{defaultTab:L,className:A,style:P})})}function _r({nodeKey:e,selected:t,onSelect:r}){return jsxs("button",{onClick:r,className:l("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsx("div",{className:l("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:l("text-xs font-medium capitalize",e.status==="active"?"text-green-500":"text-muted-foreground"),children:e.status})]}),jsx(Q,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function Ar({className:e,style:t}){let{config:r}=C(),{keys:s,loading:g,error:u,refresh:a}=H(),{listKey:i,listing:o,result:n,error:f}=Ne(),[m,p]=useState(null),[d,x]=useState(""),[N,I]=useState(false),w=s.find(F=>F.id===m),L=parseInt(d.replace(/[^0-9]/g,""),10)||0,A=L>0&&Number.isFinite(L),P=!!w&&A&&N&&!o,re=async()=>{if(!P||!w)return;let F=L*100;await i(w.id,F)&&a();};if(n)return jsxs("div",{className:l("flex flex-col items-center gap-4 rounded-xl bg-green-500/10 py-12",e),style:t,children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the Global Open AI Network marketplace."}),jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsx("code",{children:n.listingId})]}),jsxs("a",{href:`https://market.stacknet.org/keys/${encodeURIComponent(n.keyId)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 rounded-xl bg-foreground px-6 py-3 text-sm font-semibold text-background transition-colors hover:bg-foreground/90",children:[jsx(ExternalLink,{className:"h-4 w-4"}),"View Listing"]})]});if(g)return jsxs("div",{className:l("space-y-5 px-1",e),style:t,children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx(oe,{count:2})]});if(u)return jsxs("div",{className:l("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u})]}),jsx("button",{onClick:()=>a(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let M=s.filter(F=>F.status==="active");return M.length===0?jsxs("div",{className:l("flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16",e),style:t,children:[jsx(AlertTriangle,{className:"h-8 w-8 text-muted-foreground"}),jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys to sell."})]}):jsxs("div",{className:l("space-y-5",e),style:t,children:[jsxs("div",{children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx("div",{className:"space-y-2",children:M.map(F=>jsx(_r,{nodeKey:F,selected:m===F.id,onSelect:()=>p(F.id)},F.id))})]}),w&&jsxs("div",{className:"rounded-xl border bg-muted/30 p-5 space-y-2 text-sm",children:[w.keyIndex&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxs("span",{className:"text-foreground font-semibold",children:["#",w.keyIndex]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:w.id})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsx("span",{className:"text-foreground",children:r.stackName||"Unknown"})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Tokens (remaining / total)"}),jsxs("span",{className:"text-foreground",children:[R(w.tokenBalance)," / ",R(w.maxTokens)]})]}),w.paperWork&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Paper earned"}),jsx("span",{className:"text-foreground",children:w.paperWork})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:G(w.createdAt)})]})]}),jsxs("div",{children:[jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm sm:text-lg font-semibold text-foreground",children:"Listing Price (USD)"}),jsxs("div",{className:"relative",children:[jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:d,onChange:F=>{let se=F.target.value.replace(/[^0-9]/g,""),de=parseInt(se,10);x(isNaN(de)?"":de.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-6 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxs("div",{className:"flex items-start gap-3",children:[jsx("button",{type:"button",role:"checkbox","aria-checked":N,onClick:()=>I(!N),className:l("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors cursor-pointer",N?"border-foreground bg-foreground":"border-muted-foreground/40"),children:N&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsx("a",{href:D(r.termsUrl,"/terms"),className:"text-foreground underline",target:"_blank",rel:"noopener noreferrer",children:"Terms"})]})]}),f&&jsx("p",{className:"text-sm text-red-500",children:f}),jsxs("button",{onClick:re,disabled:!P,className:l("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",P?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsx(ExternalLink,{className:"h-4 w-4"}),o?"Listing...":"List on Marketplace"]})]})}var Ye=20;function ze({nodeKey:e,className:t,style:r}){let[s,g]=useState(false),[u,a]=useState(false),i=useRef(null),{entries:o,loading:n}=he(s?e.id:null);useEffect(()=>()=>{i.current&&clearTimeout(i.current);},[]);let f=useCallback(()=>{e.key&&(navigator.clipboard.writeText(e.key),a(true),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>a(false),2e3));},[e.key]),m=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500",p=o.slice(0,Ye);return jsxs("div",{className:l("rounded-lg border bg-background",t),style:r,children:[jsxs("div",{className:"p-4",children:[jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>g(!s),"aria-expanded":s,"aria-label":s?"Collapse ledger":"Expand ledger",className:"text-muted-foreground hover:text-foreground",children:s?jsx(ChevronDown,{className:"h-4 w-4"}):jsx(ChevronRight,{className:"h-4 w-4"})}),jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]})]}),jsx("span",{className:l("text-xs font-medium capitalize",m),children:e.status})]}),e.key&&jsxs("div",{className:"mb-3 flex items-center gap-2",children:[jsx("code",{className:"flex-1 truncate rounded bg-muted px-2 py-1 text-xs text-muted-foreground",children:e.key}),jsx("button",{onClick:f,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:u?jsx(Check,{className:"h-3.5 w-3.5 text-green-500"}):jsx(Copy,{className:"h-3.5 w-3.5"})})]}),jsx(Q,{current:e.tokenBalance,max:e.maxTokens}),jsxs("div",{className:"mt-2 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:["Created ",G(e.createdAt)]}),e.expiresAt&&jsxs("span",{children:["Expires ",G(e.expiresAt)]})]})]}),s&&jsxs("div",{className:"border-t px-4 py-3",children:[jsx("h4",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Ledger"}),n?jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}):p.length===0?jsx("p",{className:"text-xs text-muted-foreground",children:"No ledger entries."}):jsxs("div",{className:"space-y-1.5",children:[p.map(d=>jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsxs("span",{className:l("font-medium",d.type==="credit"||d.type==="reward"?"text-green-500":"text-red-500"),children:[d.type==="credit"||d.type==="reward"?"+":"-",R(Math.abs(d.amount))]}),jsx("span",{className:"text-muted-foreground",children:d.description})]}),jsx("span",{className:"text-muted-foreground",children:G(d.createdAt)})]},d.id)),o.length>Ye&&jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Showing ",Ye," of ",o.length," entries"]})]})]})]})}var qr=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"keys",label:"Keys"}];function ke({baseHref:e}){return jsx("div",{className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5 mb-6",children:qr.map(({id:t,label:r})=>jsx("a",{href:`${e}?tab=${t}`,className:"flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-all",children:r},t))})}function Hr({getKeyHref:e="/keys/get",showTabs:t=true,className:r,style:s}){let{keys:g,totalBalance:u,loading:a,error:i,refresh:o}=H();return a?jsxs("div",{className:l("space-y-4",r),style:s,children:[t&&e&&jsx(ke,{baseHref:e}),jsx(oe,{count:3})]}):i?jsxs("div",{className:l("space-y-4",r),style:s,children:[t&&e&&jsx(ke,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:i})]}),jsx("button",{onClick:()=>o(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]})]}):g.length===0?jsxs("div",{className:l("space-y-4",r),style:s,children:[t&&e&&jsx(ke,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed py-12",children:[jsx(KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]}),e&&jsx("a",{href:e,className:"rounded-lg bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]})]}):jsxs("div",{className:l("space-y-4",r),style:s,children:[t&&e&&jsx(ke,{baseHref:e}),jsxs("div",{className:"flex items-center justify-between",children:[jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," key",g.length!==1?"s":""," \xB7 Total balance: ",R(u)]}),e&&jsx("a",{href:e,className:"rounded-md bg-foreground px-3 py-1.5 text-xs font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]}),g.map(n=>jsx(ze,{nodeKey:n},n.id))]})}function es({nodeKey:e,selected:t,onSelect:r}){return jsxs("button",{onClick:r,className:l("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsx("div",{className:l("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:"text-xs font-medium capitalize text-green-500",children:e.status})]}),jsx(Q,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function ts({className:e,style:t}){let{keys:r,loading:s}=H(),{transferKey:g,transferring:u,result:a,error:i}=ve(),[o,n]=useState(null),[f,m]=useState(""),[p,d]=useState(false),x=r.filter(P=>P.status==="active"),N=x.find(P=>P.id===o),I=N&&f.trim()===N.userId,w=o&&f.trim().length>0&&p&&!I&&!u,L=async()=>{!o||!f.trim()||await g(o,f.trim());},A=()=>{n(null),m(""),d(false);};return a?jsxs("div",{className:l("flex flex-col items-center gap-4 py-8",e),style:t,children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsxs("div",{className:"text-center",children:[jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Transfer Complete"}),jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Key transferred successfully"})]}),jsxs("div",{className:"w-full max-w-sm space-y-2 rounded-xl border border-border bg-muted/30 p-4 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key"}),jsxs("span",{className:"font-mono text-foreground",children:[a.keyId.slice(0,20),"..."]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Recipient"}),jsxs("span",{className:"font-mono text-foreground",children:[a.toUserId.slice(0,20),"..."]})]})]}),jsx("button",{onClick:A,className:"mt-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Transfer Another"})]}):jsxs("div",{className:l("space-y-5",e),style:t,children:[jsxs("div",{children:[jsx("h3",{className:"mb-3 text-sm font-medium text-foreground",children:"Select Key to Transfer"}),s?jsx(oe,{count:2}):x.length===0?jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys available for transfer."}):jsx("div",{className:"space-y-2",children:x.map(P=>jsx(es,{nodeKey:P,selected:o===P.id,onSelect:()=>n(P.id)},P.id))})]}),o&&jsxs("div",{children:[jsx("label",{className:"mb-1.5 block text-sm font-medium text-foreground",children:"Recipient User ID"}),jsx("input",{type:"text",value:f,onChange:P=>{m(P.target.value),d(false);},placeholder:"Enter recipient's user ID or global ID",className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-foreground/30 focus:outline-none focus:ring-1 focus:ring-foreground/10"}),I&&jsx("p",{className:"mt-1.5 text-xs text-red-500",children:"Cannot transfer a key to yourself"})]}),N&&f.trim().length>0&&!I&&jsx("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertTriangle,{className:"mt-0.5 h-5 w-5 shrink-0 text-amber-500"}),jsxs("div",{className:"space-y-3",children:[jsxs("div",{children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Confirm Transfer"}),jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["You are about to transfer key"," ",jsx("span",{className:"font-mono font-medium",children:N.keyIndex?`#${N.keyIndex}`:N.id.slice(0,12)})," ","(",R(N.tokenBalance)," tokens) to"," ",jsxs("span",{className:"font-mono font-medium",children:[f.trim().slice(0,20),"..."]})]})]}),jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[jsx("input",{type:"checkbox",checked:p,onChange:P=>d(P.target.checked),className:"mt-0.5 h-4 w-4 rounded border-border"}),jsx("span",{className:"text-xs text-muted-foreground",children:"I confirm this transfer is permanent and cannot be undone."})]})]})]})}),i&&jsx("p",{className:"text-sm text-red-500",children:i}),jsx("button",{onClick:L,disabled:!w,className:l("flex w-full items-center justify-center gap-2 rounded-lg px-4 py-3 text-sm font-medium transition-all",w?"bg-foreground text-background hover:opacity-90":"bg-muted text-muted-foreground cursor-not-allowed"),children:u?jsxs(Fragment,{children:[jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Transferring..."]}):jsxs(Fragment,{children:[jsx(Send,{className:"h-4 w-4"}),"Transfer Key"]})})]})}function Rt(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[g,u]=useState(null),[a,i]=useState(null),o=useRef(true),n=useCallback(async m=>{try{s(!0),i(null);let p=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(m)}/file`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({stackId:e.stackId})});if(!p.ok)throw new Error(await E(p,`Filing failed (${p.status})`));let d=await p.json();return o.current&&(u(d),t.onFilingComplete?.(d)),d}catch(p){let d=p instanceof Error?p:new Error("Filing failed");return o.current&&i(d.message),t.onFilingError?.(d),null}finally{o.current&&s(false);}},[e.apiBaseUrl,e.stackId,t]),f=useCallback(()=>{u(null),i(null);},[]);return {filePaperwork:n,filing:r,result:g,error:a,reset:f}}function Pe(e,t=6,r=6){return !e||e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`}function as({nodeKey:e,stackName:t}){let r=Math.max(0,e.maxTokens-e.tokenBalance);return jsxs("div",{className:"bg-muted/30 p-5 space-y-2 text-sm",children:[e.keyIndex!=null&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxs("span",{className:"text-foreground font-semibold",children:["#",e.keyIndex]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:Pe(e.id,8,8)})]}),t&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsx("span",{className:"text-foreground",children:t})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Compute tokens used"}),jsxs("span",{className:"text-foreground",children:[R(r)," / ",R(e.maxTokens)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:G(e.createdAt)})]})]})}function we(){return jsxs("div",{className:"bg-stacknet-blue text-white p-8 lg:w-2/5 flex flex-col justify-between min-h-[260px]",children:[jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-sm font-mono opacity-80",children:"stacknet | filing"}),jsx("h2",{className:"text-2xl font-semibold leading-snug",children:"File paperwork to redeem Paper."}),jsx("p",{className:"text-sm opacity-80 leading-relaxed",children:"Filing submits your prepared paperwork on chain. Once validated, Paper is sent to your registered payment address."})]}),jsx("p",{className:"text-xs opacity-60 mt-8",children:"Powered by StackNet"})]})}function is({keyId:e,paymentAddress:t,onComplete:r,onConfigurePayment:s,onBack:g,className:u,style:a}){let{config:i}=C(),{keys:o,loading:n,error:f,refresh:m}=H(),{filePaperwork:p,filing:d,result:x,error:N,reset:I}=Rt(),w=o.find(M=>M.id===e),L=!!w?.paperWork&&w.paperWork.length>0,A=!!t&&t.length>0,P=L&&A&&!d&&!x,re=async()=>{if(!P||!w)return;let M=await p(w.id);M&&(m(),r?.(M));};return x?jsxs("div",{className:l("flex flex-col lg:flex-row",u),style:a,children:[jsx(we,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-6",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx(CheckCircle2,{className:"h-7 w-7 text-green-500","aria-hidden":true}),jsx("h3",{className:"text-2xl font-semibold text-foreground",children:"Paperwork filed"})]}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your filing has been submitted. Paper will be released to your payment address once the watcher network validates the proof."}),jsxs("div",{className:"bg-muted/30 p-5 space-y-3 text-sm",children:[jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Status"}),jsx("span",{className:"text-foreground capitalize",children:x.status})]}),jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Paper amount"}),jsxs("span",{className:"text-foreground tabular-nums",children:[(x.paperAmount/1e6).toLocaleString(void 0,{maximumFractionDigits:6})," Paper"]})]}),jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"File hash"}),jsx("code",{className:"text-xs text-foreground break-all",children:Pe(x.fileHash,10,10)})]}),x.txSignature&&jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Tx"}),jsx("a",{href:`https://solscan.io/tx/${encodeURIComponent(x.txSignature)}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-foreground underline underline-offset-4",children:Pe(x.txSignature,8,8)})]}),jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Beneficiary"}),jsx("code",{className:"text-xs text-foreground",children:Pe(x.beneficiary,6,6)})]})]}),g&&jsx("button",{type:"button",onClick:()=>{I(),g();},className:"w-full bg-foreground text-background py-4 text-sm font-semibold hover:bg-foreground/90 transition-colors",children:"Back to dashboard"})]})]}):n?jsxs("div",{className:l("flex flex-col lg:flex-row",u),style:a,children:[jsx(we,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-4",children:[jsx("div",{className:"h-7 w-48 bg-muted animate-pulse"}),jsx("div",{className:"h-32 w-full bg-muted animate-pulse"}),jsx("div",{className:"h-12 w-full bg-muted animate-pulse"})]})]}):f||!w?jsxs("div",{className:l("flex flex-col lg:flex-row",u),style:a,children:[jsx(we,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx(AlertCircle,{className:"h-6 w-6 text-red-500","aria-hidden":true}),jsx("h3",{className:"text-xl font-semibold text-foreground",children:f?"Unable to load keys":"Key not found"})]}),jsx("p",{className:"text-sm text-muted-foreground",children:f||`No key with id ${e} on this account.`}),jsx("button",{type:"button",onClick:()=>m(),className:"bg-foreground text-background px-4 py-3 text-sm font-semibold hover:bg-foreground/90 transition-colors",children:"Try again"})]})]}):jsxs("div",{className:l("flex flex-col lg:flex-row",u),style:a,children:[jsx(we,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-6",children:[jsxs("div",{children:[jsx("h2",{className:"text-2xl font-semibold text-foreground",children:"File paperwork"}),jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Review the key and beneficiary, then submit your filing."})]}),jsx(as,{nodeKey:w,stackName:i.stackName}),!L&&jsx("div",{className:"bg-muted/30 p-4 text-sm text-muted-foreground",children:"This key has no pending paperwork. Run your node to earn Paper, then return to file."}),jsxs("div",{className:"space-y-2",children:[jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Beneficiary (payment address)"}),A?jsx("div",{className:"bg-muted/30 p-4",children:jsx("code",{className:"text-xs text-foreground break-all",children:t})}):jsxs("div",{className:"bg-muted/30 p-4 space-y-3",children:[jsx("p",{className:"text-sm text-foreground",children:"You haven't set a payment address yet."}),s&&jsx("button",{type:"button",onClick:s,className:"bg-foreground text-background px-4 py-3 text-sm font-semibold hover:bg-foreground/90 transition-colors",children:"Set payment address"})]})]}),jsxs("div",{className:"bg-muted/30 p-4 flex gap-3",children:[jsx(Info,{className:"h-5 w-5 shrink-0 text-foreground mt-0.5","aria-hidden":true}),jsxs("p",{className:"text-sm text-foreground leading-relaxed",children:[jsx("span",{className:"font-semibold",children:"Important."})," ","Filing is one-time per key. Paper will be sent to the address above and cannot be reversed. Double-check the address before submitting."]})]}),N&&jsx("p",{className:"text-sm text-red-500",children:N}),jsx("button",{type:"button",onClick:re,disabled:!P,className:l("w-full py-4 text-sm font-semibold transition-colors",P?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:d?"Filing\u2026":"File Paperwork"})]})]})}function cs(e){return typeof e.paperWork=="string"&&e.paperWork.length>0}function us({count:e=3}){return jsx("div",{className:"space-y-2",children:Array.from({length:e}).map((t,r)=>jsxs("div",{className:"bg-muted/30 p-4 space-y-3",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("div",{className:"h-4 w-40 bg-muted animate-pulse"}),jsx("div",{className:"h-4 w-16 bg-muted animate-pulse"})]}),jsx("div",{className:"h-3 w-32 bg-muted animate-pulse"})]},r))})}function ms({nodeKey:e,onSelect:t}){let r=Math.max(0,e.maxTokens-e.tokenBalance);return jsxs("button",{type:"button",onClick:t,className:"group flex w-full items-center gap-4 bg-muted/30 p-4 text-left transition-colors hover:bg-muted/50",children:[jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsxs("span",{className:"text-sm font-semibold text-foreground",children:[e.keyIndex!=null?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:"text-xs text-muted-foreground",children:e.stackName||""})]}),jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[jsxs("span",{className:"tabular-nums",children:[R(r)," / ",R(e.maxTokens)," compute used"]}),jsx("span",{className:"text-foreground",children:"Eligible"})]})]}),jsx(ChevronRight,{className:"h-5 w-5 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5","aria-hidden":true})]})}function fs({onSelect:e,className:t,style:r}){let{keys:s,loading:g,error:u,refresh:a}=H();if(g)return jsx("div",{className:l("space-y-3",t),style:r,children:jsx(us,{count:3})});if(u)return jsx("div",{className:l("space-y-3",t),style:r,children:jsxs("div",{className:"bg-muted/30 p-5 text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u}),jsx("button",{type:"button",onClick:()=>a(),className:"mt-3 bg-foreground text-background px-4 py-2 text-xs font-semibold hover:bg-foreground/90 transition-colors",children:"Try again"})]})});let i=s.filter(cs);return i.length===0?jsxs("div",{className:l("flex flex-col items-center justify-center gap-3 bg-muted/20 py-16",t),style:r,children:[jsx(FileText,{className:"h-10 w-10 text-muted-foreground","aria-hidden":true}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys with pending paperwork"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Run a node to earn Paper, then return here to file."})]})]}):jsx("div",{className:l("space-y-2",t),style:r,children:i.map(o=>jsx(ms,{nodeKey:o,onSelect:()=>e(o.id)},o.id))})}
2
- export{ge as BottomSheet,jr as BuyKeyWidget,Ee as BuyPanel,fs as FilePaperworkList,is as FilePaperworkView,Q as KeyBalanceBar,ze as KeyCard,We as KeyDetailView,Hr as KeyList,Se as KeyUtilsProvider,Oe as KeysPanel,Be as MintSuccess,Ar as SellPanel,Ue as SolanaPayButton,ts as TransferPanel,je as UsePanel,C as useKeyUtilsContext};
1
+ import rr,{createContext,useContext,useMemo,useState,useCallback,useRef,useEffect}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {Loader2,CheckCircle,Check,Copy,CreditCard,Wallet,Download,X as X$1,ArrowLeft,KeyRound,ExternalLink,AlertTriangle,ChevronDown,ChevronRight,Send,CheckCircle2,AlertCircle,Info,FileText,Minus,Plus,ChevronUp}from'lucide-react';var et=createContext(null);function C(){let e=useContext(et);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function Ie({config:e,callbacks:t={},children:r}){typeof e.apiBaseUrl!="string"&&console.error("[KeyUtils] apiBaseUrl must be a string");let s=useMemo(()=>({config:e,callbacks:t}),[e,t]);return jsx(et.Provider,{value:s,children:r})}function z(){if(typeof document>"u")return {};let e=document.cookie.match(/(?:^|;\s*)__csrf=([^;]*)/);return e?{"x-csrf-token":e[1]}:{}}function tt(e,t){if(typeof e!="string"||e.length===0)return t;let r=e.replace(/[\u0000-\u001F\u007F]/g," ");return r.length>500?r.slice(0,500)+"\u2026":r}async function B(e,t){try{let r=await e.json();if(r&&typeof r=="object"&&"error"in r)return tt(r.error,t)}catch{}return t}function F(e,t="#"){if(!e||typeof e!="string")return t;let r=e.trim();if(r===""||r==="#")return t;if(r.startsWith("/")||r.startsWith("./")||r.startsWith("../"))return r;try{let s=new URL(r);if(s.protocol==="http:"||s.protocol==="https:")return s.toString()}catch{}return t}function i(...e){return twMerge(clsx(e))}function K(e){return e==null?"0":e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function rt(e,t){return t<=0?0:Math.min(100,Math.round(e/t*100))}function st(e){return e>=70?"bg-green-500":e>=30?"bg-yellow-500":"bg-red-500"}function G(e){if(e==null||e==="")return "";let t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e,r=new Date(t);return isNaN(r.getTime())?"":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function nt(){if(typeof navigator>"u")return "mac";let e=navigator.userAgent.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/win/.test(e)?"windows":/linux/.test(e)?"linux":"mac"}function at(){let{config:e}=C(),[t,r]=useState(null),[s,x]=useState(true),[l,d]=useState(null),c=useRef(true),n=useRef(e.apiBaseUrl);n.current=e.apiBaseUrl;let a=async()=>{try{c.current&&(x(!0),d(null));let u=await fetch(`${n.current}/api/keys/pricing`,{credentials:"include"});if(!u.ok)throw new Error(await B(u,`Pricing unavailable (${u.status})`));let m=await u.json();c.current&&r(m);}catch(u){c.current&&d(u instanceof Error?u.message:"Failed to fetch pricing");}finally{c.current&&x(false);}};return useEffect(()=>{c.current=true,a();let u=setInterval(a,6e4);return ()=>{c.current=false,clearInterval(u);}},[]),{pricing:t,loading:s,error:l,refresh:a}}function it(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[x,l]=useState(null),[d,c]=useState(null);return {mint:useCallback(async(a,u,m=1)=>{try{s(!0),c(null),t.onPaymentComplete?.(a,u);let f=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({paymentMethod:a,paymentRef:u,quantity:m,stackId:e.stackId})});if(!f.ok)throw new Error(await B(f,`Key generation failed (${f.status})`));let o=await f.json(),g=o.keys?.[0]||o,v={success:!0,key:{id:g.keyId||g.id||"",key:g.key||"",userId:g.userId||"",status:"active",tokenBalance:g.tokenBalance??g.currentTokenBalance??0,maxTokens:g.initialTokenBalance??g.tokenBalance??0,createdAt:String(g.createdAt||Date.now())},transactionId:u};return l(v),t.onMintSuccess?.(v),v}catch(f){let o=f instanceof Error?f:new Error("Key generation failed");return c(o.message),t.onMintError?.(o),{success:false,error:o.message}}finally{s(false);}},[e.apiBaseUrl,t]),minting:r,result:x,error:d}}function ct(){let{config:e}=C(),[t,r]=useState(false),[s,x]=useState(null),l=useRef(true);return {createSession:useCallback(async(c,n)=>{try{r(!0),x(null);let a=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({priceCents:c,quantity:n,stackId:e.stackId,referrerUrl:window.location.href})});if(!a.ok)throw new Error(await B(a,`Checkout failed (${a.status})`));let{url:u}=await a.json();if(!u)throw new Error("No checkout URL returned");let m;try{m=new URL(u);}catch{throw new Error("Invalid checkout URL")}if(m.protocol!=="https:"||!/(^|\.)stripe\.com$/.test(m.hostname))throw new Error("Refusing to redirect to non-Stripe URL");try{sessionStorage.setItem("keyutils_stripe_pending","1"),sessionStorage.setItem("keyutils_stripe_quantity",String(n));}catch{}window.location.href=m.toString();}catch(a){if(l.current){let u=a instanceof Error?a.message:"Checkout failed";x(u),r(false);}}},[e.apiBaseUrl,e.stackId]),loading:t,error:s}}var ut=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function Le({amountSol:e,onSuccess:t,onError:r,disabled:s,className:x,style:l}){let{config:d}=C(),[c,n]=useState(false),[a,u]=useState(null),m=!!(d.merchantWallet&&ut.test(d.merchantWallet)),f=useCallback(async()=>{if(m)try{n(!0),u(null);let{Connection:o,PublicKey:g,Transaction:v,SystemProgram:T,LAMPORTS_PER_SOL:w}=await import('@solana/web3.js'),E=typeof window<"u"?window.solana:void 0;if(!E||typeof E!="object"||!E.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let $=E,P;try{P=new g(d.merchantWallet);}catch{throw new Error("Invalid merchant wallet address.")}let re=await $.connect(),M=new g(re.publicKey.toString()),A="https://api.mainnet-beta.solana.com",se=F(d.solanaRpcUrl,A),ce=se==="#"?A:se,Re=new o(ce),{blockhash:W}=await Re.getLatestBlockhash(),ee=BigInt(Math.floor(e*1e9)),de=d.protocolTreasuryWallet,me=d.protocolFeeBps??500,ue=new v({recentBlockhash:W,feePayer:M});if(de&&ut.test(de)&&me>0){let Ze=ee*BigInt(me)/10000n,_t=ee-Ze,At=new g(de);ue.add(T.transfer({fromPubkey:M,toPubkey:P,lamports:Number(_t)}),T.transfer({fromPubkey:M,toPubkey:At,lamports:Number(Ze)}));}else ue.add(T.transfer({fromPubkey:M,toPubkey:P,lamports:Number(ee)}));let{signature:ye}=await $.signAndSendTransaction(ue);t(ye);}catch(o){let g=o instanceof Error?o:new Error("Payment failed");u(g.message),r?.(g);}finally{n(false);}},[e,d.merchantWallet,m,t,r]);return jsxs("div",{children:[jsx("button",{onClick:f,disabled:s||c||!m,"aria-label":`Pay ${e.toFixed(4)} SOL`,className:i("flex w-full items-center justify-center gap-2 rounded-lg bg-purple-600 px-4 py-6 font-medium text-white transition-colors hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed",x),style:l,children:c?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 animate-spin"}),"Processing..."]}):jsxs(Fragment,{children:["Pay ",e.toFixed(4)," SOL"]})}),a&&jsx("p",{className:"mt-2 text-center text-xs text-red-500",children:a})]})}function Ee({result:e,className:t,style:r}){let[s,x]=useState(false),l=useRef(null);useEffect(()=>()=>{l.current&&clearTimeout(l.current);},[]);let d=useCallback(()=>{e.key?.key&&(navigator.clipboard.writeText(e.key.key),x(true),l.current&&clearTimeout(l.current),l.current=setTimeout(()=>x(false),2e3));},[e.key?.key]);return !e.success||!e.key?null:jsxs("div",{className:i("rounded-lg border border-green-500/20 bg-green-500/10 p-6 text-center",t),style:r,children:[jsx(CheckCircle,{className:"mx-auto mb-3 h-12 w-12 text-green-500"}),jsx("h3",{className:"mb-2 text-lg font-semibold text-foreground",children:"Key Generated!"}),jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Your node key has been successfully generated."}),jsxs("div",{className:"mx-auto flex max-w-md items-center gap-2 rounded-md border bg-background p-3",children:[jsx("code",{className:"flex-1 truncate text-xs text-foreground",children:e.key.key}),jsx("button",{onClick:d,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]})]})}function X({className:e}){return jsx("div",{className:i("animate-pulse rounded-xl bg-muted",e)})}function _e(){return jsxs("div",{className:"space-y-6",children:[jsxs("div",{className:"px-6 py-10 flex flex-col items-center gap-3",children:[jsx(X,{className:"h-14 w-48"}),jsx(X,{className:"h-5 w-64"})]}),jsx(X,{className:"h-[72px] w-full rounded-2xl"}),jsx(X,{className:"h-[68px] w-full rounded-2xl"}),jsx(X,{className:"h-[60px] w-full rounded-2xl"})]})}function ne({count:e=3}){return jsx("div",{className:"space-y-3",children:Array.from({length:e}).map((t,r)=>jsxs("div",{className:"rounded-xl border p-4 space-y-3",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx(X,{className:"h-4 w-32"}),jsx(X,{className:"h-4 w-16"})]}),jsx(X,{className:"h-2 w-full rounded-full"}),jsxs("div",{className:"flex justify-between",children:[jsx(X,{className:"h-3 w-24"}),jsx(X,{className:"h-3 w-20"})]})]},r))})}function dr({quantity:e,max:t,onChange:r}){return jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-muted/20 px-6 py-6",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:"Quantity"}),jsxs("div",{className:"flex items-center gap-0 rounded-xl bg-background",children:[jsx("button",{onClick:()=>r(Math.max(1,e-1)),disabled:e<=1,"aria-label":"Decrease quantity",className:"flex h-12 w-12 items-center justify-center rounded-l-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Minus,{className:"h-5 w-5"})}),jsx("span",{className:"flex h-12 w-14 items-center justify-center border-x text-xl font-bold text-foreground","aria-live":"polite",children:e}),jsx("button",{onClick:()=>r(Math.min(t,e+1)),disabled:e>=t,"aria-label":"Increase quantity",className:"flex h-12 w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Plus,{className:"h-5 w-5"})})]})]})}function gt({pricing:e,quantity:t}){let[r,s]=useState(false),x=e.priceUsd*t;return jsxs("div",{className:"rounded-2xl border bg-background",children:[jsxs("button",{onClick:()=>s(!r),"aria-expanded":r,className:"flex w-full items-center justify-between px-6 py-6 text-left",children:[jsxs("span",{className:"text-foreground",children:[jsxs("span",{className:"text-xl font-bold",children:["$",x.toFixed(2)]})," ",jsx("span",{className:"text-sm text-muted-foreground",children:"total fees included"})]}),r?jsx(ChevronUp,{className:"h-5 w-5 text-muted-foreground"}):jsx(ChevronDown,{className:"h-5 w-5 text-muted-foreground"})]}),r&&jsxs("div",{className:"border-t px-6 pb-8 pt-4 space-y-3 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsxs("span",{className:"text-muted-foreground",children:["Node Key \xD7 ",t]}),jsxs("span",{className:"text-foreground",children:["$",(e.priceUsd*t).toFixed(2)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Keys sold"}),jsx("span",{className:"text-foreground",children:e.keysSold})]}),e.daysUntilHalving>0&&jsxs("div",{className:"flex justify-between text-muted-foreground",children:[jsx("span",{children:"Next refresh"}),jsxs("span",{children:[e.daysUntilHalving," day",e.daysUntilHalving!==1?"s":""]})]}),jsxs("div",{className:"flex justify-between border-t pt-3 font-semibold",children:[jsx("span",{className:"text-foreground",children:"Total"}),jsxs("span",{className:"text-foreground",children:["$",x.toFixed(2)]})]})]})]})}function Ae({className:e,style:t}){let{config:r}=C(),{pricing:s,loading:x,error:l,refresh:d}=at(),{mint:c,minting:n,result:a,error:u}=it(),{createSession:m,loading:f,error:o}=ct(),[g,v]=useState(1),[T,w]=useState(r.paymentMethods?.includes("stripe")?"stripe":"solana"),[E,$]=useState(0),[P,re]=useState(false),M=rr.useRef(g);M.current=g;let A=Math.max(1,r.maxQuantity||5),se=[...r.paymentMethods||["solana"]].sort((W,ee)=>W==="stripe"?-1:ee==="stripe"?1:0);if(useEffect(()=>{if(typeof window>"u")return;let ee=new URLSearchParams(window.location.search).get("session_id");if(!ee){try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}return}if(/^cs_(test|live)_/.test(ee)&&!P&&!a?.success){let de=false;try{de=sessionStorage.getItem("keyutils_stripe_pending")==="1";}catch{}if(!de)return;try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}re(true);let me=new URL(window.location.href);me.searchParams.delete("session_id"),window.history.replaceState({},"",me.toString());let ue=M.current;try{let ye=sessionStorage.getItem("keyutils_stripe_quantity");ye&&(ue=parseInt(ye,10)||1,sessionStorage.removeItem("keyutils_stripe_quantity"));}catch{}c("stripe",ee,ue);}},[P,a,c]),a?.success)return jsx("div",{className:i("flex flex-col items-center justify-center",e),style:t,children:jsx(Ee,{result:a})});if(P||n)return jsx("div",{className:i("flex flex-col",e),style:t,children:jsx(_e,{})});if(x)return jsx("div",{className:i("flex flex-col",e),style:t,children:jsx(_e,{})});if(l||!s)return jsxs("div",{className:i("flex flex-col items-center justify-center gap-4 py-24",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load pricing"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l||"Please check your connection and try again."})]}),jsx("button",{onClick:()=>d(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let ce=async W=>{$(2),await c(T,W,g);},Re=()=>{m(s.priceCents,g);};return jsx("div",{className:i("flex flex-col",e),style:t,children:jsxs("div",{className:"space-y-6",children:[E===0&&jsxs(Fragment,{children:[r.keyImage&&jsx("img",{src:F(r.keyImage),alt:"Node Key",className:r.keyImageClass||"w-1/2 mx-auto"}),jsxs("div",{className:"px-6 py-10 text-center",children:[jsxs("p",{className:"text-5xl font-bold tracking-tight text-foreground md:text-6xl",children:["$",s.priceUsd.toFixed(2)]}),jsxs("p",{className:"mt-2 text-base text-muted-foreground",children:["per key \xB7 ",s.tokenAllocationFormatted||K(s.tokenAllocation)," tokens included"]})]}),jsx(dr,{quantity:g,max:A,onChange:v}),jsx(gt,{pricing:s,quantity:g}),jsx("button",{onClick:()=>$(1),className:"w-full rounded-2xl bg-foreground py-6 text-center text-base font-semibold text-background transition-colors hover:bg-foreground/90",children:"Continue to Payment"})]}),E===1&&jsxs(Fragment,{children:[se.length>1&&jsx("div",{role:"tablist",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:se.map(W=>jsxs("button",{role:"tab","aria-selected":T===W,onClick:()=>w(W),className:i("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-4 text-sm font-medium transition-colors",T===W?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[W==="stripe"?jsx(CreditCard,{className:"h-5 w-5"}):jsx(Wallet,{className:"h-5 w-5"}),W==="stripe"?"Credit Card":"Crypto"]},W))}),jsx(gt,{pricing:s,quantity:g}),T==="stripe"?jsxs(Fragment,{children:[jsx("button",{onClick:Re,disabled:f,className:"flex w-full items-center justify-center gap-2 rounded-2xl bg-foreground py-6 text-base font-semibold text-background transition-colors hover:bg-foreground/90 disabled:opacity-50",children:f?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-5 w-5 animate-spin"}),"Redirecting to Stripe..."]}):jsxs(Fragment,{children:[jsx(CreditCard,{className:"h-5 w-5"}),"Pay with Card"]})}),o&&jsx("p",{className:"text-center text-sm text-red-500",children:o})]}):T==="solana"?jsx(Le,{amountSol:s.priceSol??0,onSuccess:ce,className:"rounded-2xl py-5 text-base"}):null,u&&jsx("p",{className:"text-center text-sm text-red-500",children:u}),jsx("button",{onClick:()=>$(0),className:"w-full py-3 text-center text-sm text-muted-foreground hover:text-foreground transition-colors",children:"\u2190 Back"})]})]})})}var pr={ios:"iOS",android:"Android",windows:"Windows",mac:"macOS",linux:"Linux"},gr=["mac","windows","linux","ios","android"],xr="https://www.stacknet.org/download";function Me({downloads:e,className:t,style:r}){let{config:s}=C(),x=useMemo(()=>nt(),[]),l=e||gr.map(n=>({platform:n,label:pr[n],url:xr,compatible:n===x})),d=l.find(n=>n.compatible)||l[0],c=l.filter(n=>n.platform!==d.platform);return jsxs("div",{className:i("space-y-8",t),style:r,children:[jsxs("div",{className:"flex flex-col items-center gap-6 pt-4 mt-4",children:[s.aispImage&&jsx("img",{src:F(s.aispImage),alt:"aiSP",className:"w-full sm:w-1/2 mx-auto px-4 sm:px-0"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-lg sm:text-2xl font-medium text-foreground",children:"Download the AI Service Provider App"}),jsx("p",{className:"mt-1 text-sm sm:text-base text-muted-foreground",children:"Load your keys and run your node."})]}),jsxs("a",{href:F(d.url),target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-3 rounded-full px-10 py-4 text-lg font-semibold text-white transition-colors hover:opacity-90",style:{backgroundColor:"#0900f4"},children:[jsx(Download,{className:"h-5 w-5"}),"Get aiSP for ",d.label]})]}),jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["aiSP is also available on"," ",c.map((n,a)=>jsxs(rr.Fragment,{children:[a>0&&(a===c.length-1?" and ":", "),jsx("a",{href:F(n.url),target:"_blank",rel:"noopener noreferrer",className:"font-medium underline transition-colors hover:text-foreground",style:{color:"#066bff"},children:n.label})]},n.platform)),"."]}),jsxs("div",{className:"flex flex-col items-center gap-2 mt-12",children:[jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["Source code is available on",jsx("a",{href:"https://github.com/stack-net",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80 color-[#0900f4]",children:"Github"})]}),jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["By downloading, you agree to the",jsx("a",{href:F(s.termsUrl,"/terms"),target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80",children:"Open Source Applications Terms"})]})]})]})}function Nr(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function q(){let{config:e}=C(),[t,r]=useState([]),[s,x]=useState(true),[l,d]=useState(null),c=useRef(true),n=e.apiBaseUrl,a=useCallback(async()=>{try{x(!0),d(null);let m=await fetch(`${n}/api/keys`,{credentials:"include"});if(!m.ok)throw new Error(await B(m,`Failed to fetch keys (${m.status})`));let f=await m.json(),o=Array.isArray(f)?f:f.keys??[];c.current&&r(o.map(Nr));}catch(m){c.current&&d(m instanceof Error?m.message:"Failed to fetch keys");}finally{c.current&&x(false);}},[n]);useEffect(()=>(c.current=true,a(),()=>{c.current=false;}),[a]);let u=t.reduce((m,f)=>m+f.tokenBalance,0);return {keys:t,totalBalance:u,loading:s,error:l,refresh:a}}function J({current:e,max:t,className:r,style:s,showLabel:x=true}){let l=rt(e,t),d=st(l);return jsxs("div",{className:i("w-full",r),style:s,children:[x&&jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:[K(e)," / ",K(t)]}),jsxs("span",{children:[l,"%"]})]}),jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-muted",children:jsx("div",{className:i("h-full rounded-full transition-all duration-500",d),style:{width:`${l}%`}})})]})}function ke(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[x,l]=useState(null),[d,c]=useState(null),n=useRef(true),a=useCallback(async(m,f)=>{try{s(!0),c(null);let o=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(m)}/list`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({askPriceCents:f,stackId:e.stackId,stackName:e.stackName})});if(!o.ok)throw new Error(await B(o,`Listing failed (${o.status})`));let g=await o.json();return n.current&&(l(g),t.onListingCreated?.(g)),g}catch(o){let g=o instanceof Error?o.message:"Listing failed";return n.current&&c(g),null}finally{n.current&&s(false);}},[e.apiBaseUrl,e.stackId,e.stackName,t]),u=useCallback(async m=>{try{s(!0),c(null);let f=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(m)}/list`,{method:"DELETE",headers:{...z()},credentials:"include"});if(!f.ok)throw new Error(await B(f,`Delist failed (${f.status})`));return n.current&&l(null),!0}catch(f){let o=f instanceof Error?f.message:"Delist failed";return n.current&&c(o),false}finally{n.current&&s(false);}},[e.apiBaseUrl]);return {listKey:a,delistKey:u,listing:r,result:x,error:d}}function Ne(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[x,l]=useState(null),[d,c]=useState(null),n=useRef(true);return {transferKey:useCallback(async(u,m)=>{try{s(!0),c(null);let f=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(u)}/transfer`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({recipientId:m})});if(!f.ok)throw new Error(await B(f,`Transfer failed (${f.status})`));let o=await f.json();return n.current&&(l(o),t.onTransferComplete?.(o)),o}catch(f){let o=f instanceof Error?f.message:"Transfer failed";return n.current&&c(o),null}finally{n.current&&s(false);}},[e.apiBaseUrl,t]),transferring:r,result:x,error:d}}function bt(e){let t=e.type||e.entry_type||"debit",r=e.amount??e.tokens??e.token_amount??0,s=e.description||e.memo||e.reason||Pr(t);return {id:e.id||"",keyId:e.keyId||e.key_id||"",type:t,amount:r,description:s,createdAt:String(e.createdAt??e.created_at??e.timestamp??""),metadata:e.metadata||void 0}}function Pr(e){switch(e){case "credit":return "Credit";case "debit":return "Usage";case "mint":return "Mint";case "reward":return "Reward";default:return ""}}function ve(e){let{config:t}=C(),[r,s]=useState([]),[x,l]=useState(false),[d,c]=useState(null),n=useRef(true),a=t.apiBaseUrl,u=useCallback(async()=>{if(e)try{l(!0),c(null);let m=await fetch(`${a}/api/keys/${encodeURIComponent(e)}/ledger`,{credentials:"include"});if(!m.ok)throw new Error(await B(m,`Failed to fetch ledger (${m.status})`));let f=await m.json(),o=Array.isArray(f)?f:f.entries??[];n.current&&s(o.map(bt));}catch(m){n.current&&c(m instanceof Error?m.message:"Failed to fetch ledger");}finally{n.current&&l(false);}},[a,e]);return useEffect(()=>(n.current=true,u(),()=>{n.current=false;}),[u]),{entries:r,loading:x,error:d,refresh:u}}function xe({open:e,onClose:t,title:r,children:s}){let x=useRef(null),[l,d]=useState(false),[c,n]=useState(false),a=useCallback(u=>{u.key==="Escape"&&t();},[t]);return useEffect(()=>{if(e)d(true),document.addEventListener("keydown",a),document.body.style.overflow="hidden",requestAnimationFrame(()=>{requestAnimationFrame(()=>n(true));});else {n(false);let u=setTimeout(()=>{d(false),document.body.style.overflow="";},300);return document.removeEventListener("keydown",a),()=>clearTimeout(u)}return ()=>{document.removeEventListener("keydown",a);}},[e,a]),l?jsxs("div",{className:"fixed inset-0 z-50 flex items-end justify-center",children:[jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm transition-opacity duration-300",style:{opacity:c?1:0},onClick:t}),jsxs("div",{ref:x,className:i("relative z-10 w-full max-w-xl rounded-t-2xl bg-background shadow-2xl","max-h-[85vh] flex flex-col","transition-transform duration-300 ease-out"),style:{transform:c?"translateY(0)":"translateY(100%)"},children:[jsx("div",{className:"flex justify-center pt-3 pb-1",children:jsx("div",{className:"h-1 w-10 rounded-full bg-muted-foreground/30"})}),r&&jsxs("div",{className:"flex items-center justify-between px-5 pb-3 pt-1",children:[jsx("h3",{className:"text-lg font-semibold text-foreground",children:r}),jsx("button",{onClick:t,className:"rounded-full p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors","aria-label":"Close",children:jsx(X$1,{className:"h-5 w-5"})})]}),jsx("div",{className:"flex-1 overflow-y-auto px-5 pb-8",children:s})]})]}):null}var we=[" .-----."," / (_) \\"," / \\","( )"," \\ /"," \\_______/"," || |"," || |"," || /"," || /"," || \\"," || /"," || /"," \\// "],We=16,Br=We*.6,Nt=We*1;function He({className:e,style:t,color:r="currentColor",ariaLabel:s="Node key",keyImage:x,keyImageClass:l}){if(x)return jsx("img",{src:F(x),alt:s,className:i(l||"h-20 w-auto mx-auto",e),style:t});let d=we.reduce((f,o)=>Math.max(f,o.length),0),c=we.length,n=d*Br,u=c*Nt;return jsx("svg",{viewBox:`0 0 ${u} ${n}`,xmlns:"http://www.w3.org/2000/svg",className:i("block",e),style:t,role:"img","aria-label":s,preserveAspectRatio:"xMidYMid meet",children:jsx("g",{transform:`translate(0 ${n}) rotate(-90)`,children:we.map((f,o)=>jsx("text",{x:0,y:(o+.8)*Nt,fill:r,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:We,xmlSpace:"preserve",children:f},o))})})}function Ar({nodeKey:e,onSuccess:t}){let{transferKey:r,transferring:s,result:x,error:l}=Ne(),[d,c]=useState(""),[n,a]=useState(false),u=d.trim()===e.userId,m=d.trim().length>0&&n&&!u&&!s,f=async()=>{if(!m)return;await r(e.id,d.trim())&&t();};return x?jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Transfer Complete"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Key transferred successfully"})]}):jsxs("div",{className:"space-y-5",children:[jsxs("div",{children:[jsx("label",{className:"mb-1.5 block text-sm font-semibold text-foreground",children:"Recipient User ID"}),jsx("input",{type:"text",value:d,onChange:o=>{c(o.target.value),a(false);},placeholder:"Enter recipient's user ID or global ID",className:"w-full rounded-xl border border-border bg-background px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground focus:border-foreground/30 focus:outline-none focus:ring-1 focus:ring-foreground/10"}),u&&jsx("p",{className:"mt-1.5 text-xs text-red-500",children:"Cannot transfer a key to yourself"})]}),d.trim().length>0&&!u&&jsx("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertTriangle,{className:"mt-0.5 h-5 w-5 shrink-0 text-amber-500"}),jsxs("div",{className:"space-y-3",children:[jsxs("div",{children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Confirm Transfer"}),jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Transferring key"," ",jsx("span",{className:"font-mono font-medium",children:e.keyIndex?`#${e.keyIndex}`:e.id.slice(0,12)})," ","(",K(e.tokenBalance)," tokens) to"," ",jsxs("span",{className:"font-mono font-medium",children:[d.trim().slice(0,20),d.trim().length>20?"...":""]})]})]}),jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[jsx("input",{type:"checkbox",checked:n,onChange:o=>a(o.target.checked),className:"mt-0.5 h-4 w-4 rounded border-border"}),jsx("span",{className:"text-xs text-muted-foreground",children:"I confirm this transfer is permanent and cannot be undone."})]})]})]})}),l&&jsx("p",{className:"text-sm text-red-500",children:l}),jsx("button",{onClick:f,disabled:!m,className:i("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",m?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:s?jsxs(Fragment,{children:[jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Transferring..."]}):jsxs(Fragment,{children:[jsx(Send,{className:"h-4 w-4"}),"Transfer Key"]})})]})}function Mr({nodeKey:e,onSuccess:t}){let{config:r}=C(),{listKey:s,listing:x,result:l,error:d}=ke(),[c,n]=useState(""),[a,u]=useState(false),m=parseInt(c.replace(/[^0-9]/g,""),10)||0,o=m>0&&Number.isFinite(m)&&a&&!x,g=async()=>{if(!o)return;let v=m*100;await s(e.id,v)&&t();};return l?jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the marketplace."}),jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsx("code",{children:l.listingId})]}),jsxs("a",{href:`https://market.stacknet.org/keys/${encodeURIComponent(l.keyId)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 rounded-xl bg-foreground px-6 py-3 text-sm font-semibold text-background transition-colors hover:bg-foreground/90",children:[jsx(ExternalLink,{className:"h-4 w-4"}),"View Listing"]})]}):jsxs("div",{className:"space-y-5",children:[jsxs("div",{children:[jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm font-semibold text-foreground",children:"Listing Price (USD)"}),jsxs("div",{className:"relative",children:[jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:c,onChange:v=>{let T=v.target.value.replace(/[^0-9]/g,""),w=parseInt(T,10);n(isNaN(w)?"":w.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-6 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxs("div",{className:"flex items-start gap-3",children:[jsx("button",{type:"button",role:"checkbox","aria-checked":a,onClick:()=>u(!a),className:i("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors cursor-pointer",a?"border-foreground bg-foreground":"border-muted-foreground/40"),children:a&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsx("a",{href:F(r.termsUrl,"/terms"),className:"text-foreground underline",target:"_blank",rel:"noopener noreferrer",children:"Terms"})]})]}),d&&jsx("p",{className:"text-sm text-red-500",children:d}),jsxs("button",{onClick:g,disabled:!o,className:i("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",o?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsx(ExternalLink,{className:"h-4 w-4"}),x?"Listing...":"List on Marketplace"]})]})}function Fr({nodeKey:e}){let[t,r]=useState(false);if(!e.paperWork)return jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[jsx(FileText,{className:"h-10 w-10 text-muted-foreground"}),jsx("p",{className:"text-sm text-muted-foreground",children:"This key has no paperwork to file."})]});let s=()=>{navigator.clipboard.writeText(e.paperWork||""),r(true),setTimeout(()=>r(false),2e3);};return jsxs("div",{className:"space-y-5",children:[jsxs("div",{children:[jsx("label",{className:"mb-2 block text-sm font-semibold text-foreground",children:"Paperwork"}),jsxs("div",{className:"relative rounded-xl border bg-muted/30 p-4",children:[jsx("pre",{className:"whitespace-pre-wrap break-all text-sm text-foreground font-mono",children:e.paperWork}),jsx("button",{onClick:s,className:"absolute top-3 right-3 rounded-lg p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors","aria-label":"Copy paperwork",children:t?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]})]}),jsx("p",{className:"text-xs text-muted-foreground",children:"Filing paperwork submits the key's documentation on-chain for permanent record."}),jsxs("button",{disabled:true,className:"flex w-full items-center justify-center gap-2 rounded-xl bg-muted py-4 text-sm font-semibold text-muted-foreground cursor-not-allowed",children:[jsx(FileText,{className:"h-4 w-4"}),"File Paperwork (Coming Soon)"]})]})}function ze({nodeKey:e,onBack:t,onKeysChanged:r,className:s,style:x}){let {config:l}=C();ve(e.id);let [n,a]=useState(null),[u,m]=useState(false),f=()=>{a(null),r?.();},o=()=>{e.key&&(navigator.clipboard.writeText(e.key),m(true),setTimeout(()=>m(false),2e3));},g=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500";return jsxs("div",{className:i("space-y-5",s),style:x,children:[jsxs("button",{onClick:t,className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[jsx(ArrowLeft,{className:"h-4 w-4"}),"Back to Keys"]}),jsx(He,{className:i("mx-auto text-foreground",l.keyImage?"w-2/3 h-auto":"h-20 w-auto"),keyImage:l.keyImage,keyImageClass:l.keyImageClass}),jsx("div",{className:"space-y-1",children:jsxs("div",{className:"flex items-center justify-between",children:[jsx("h2",{className:"text-2xl font-bold text-foreground",children:e.keyIndex?`Key #${e.keyIndex}`:e.label||e.id.slice(0,16)}),jsx("span",{className:i("text-sm font-medium capitalize",g),children:e.status})]})}),e.key&&jsxs("div",{className:"flex items-center gap-2",children:[jsx("code",{className:"flex-1 truncate rounded-lg bg-muted px-3 py-2 text-xs text-muted-foreground",children:e.key}),jsx("button",{onClick:o,"aria-label":"Copy key",className:"shrink-0 rounded-lg p-2 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",children:u?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]}),jsx(J,{current:e.tokenBalance,max:e.maxTokens,showLabel:true}),jsxs("div",{className:"rounded-xl bg-muted/30 p-5 space-y-2.5 text-sm",children:[e.keyIndex&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxs("span",{className:"text-foreground font-semibold",children:["#",e.keyIndex]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:e.id})]}),(l.stackName||e.stackName)&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Stack"}),jsx("span",{className:"text-foreground",children:e.stackName||l.stackName})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Tokens"}),jsxs("span",{className:"text-foreground",children:[K(e.tokenBalance)," / ",K(e.maxTokens)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:G(e.createdAt)})]}),e.expiresAt&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Expires"}),jsx("span",{className:"text-foreground",children:G(e.expiresAt)})]})]}),e.paperWork&&jsxs("div",{className:"rounded-xl border bg-muted/30 p-5",children:[jsx("h3",{className:"text-sm font-semibold text-foreground mb-2",children:"Paperwork"}),jsx("pre",{className:"whitespace-pre-wrap break-all text-xs text-muted-foreground font-mono",children:e.paperWork})]}),e.status==="active"&&jsxs("div",{className:"grid grid-cols-3 gap-3",children:[jsx("button",{onClick:()=>a("transfer"),className:"flex items-center justify-center rounded-xl border border-border p-4 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Transfer"}),jsx("button",{onClick:()=>a("sell"),className:"flex items-center justify-center rounded-xl border border-border p-4 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Sell"}),jsx("button",{onClick:()=>a("file"),className:i("flex items-center justify-center rounded-xl border border-border p-4 text-sm font-medium transition-colors",e.paperWork?"text-foreground hover:bg-muted/50":"text-muted-foreground cursor-not-allowed opacity-50"),disabled:!e.paperWork,children:"File"})]}),jsx(xe,{open:n==="transfer",onClose:()=>a(null),title:"Transfer Key",children:jsx(Ar,{nodeKey:e,onSuccess:f})}),jsx(xe,{open:n==="sell",onClose:()=>a(null),title:"Sell Key",children:jsx(Mr,{nodeKey:e,onSuccess:f})}),jsx(xe,{open:n==="file",onClose:()=>a(null),title:"File Paperwork",children:jsx(Fr,{nodeKey:e})})]})}function jr({nodeKey:e,onClick:t}){let r=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500";return jsx("button",{onClick:t,className:"flex w-full items-start gap-3 rounded-xl border border-border p-4 text-left transition-all hover:border-foreground/20 hover:bg-muted/30",children:jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:i("text-xs font-medium capitalize",r),children:e.status})]}),jsx(J,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"}),e.paperWork&&jsx("span",{className:"mt-1.5 inline-block text-xs text-muted-foreground",children:"Has paperwork"})]})})}function Ye({className:e,style:t}){let{keys:r,loading:x,error:l,refresh:d}=q(),[c,n]=useState(null),[a,u]=useState("active"),m=r.filter(g=>g.status===a),f=m.reduce((g,v)=>g+v.tokenBalance,0),o=r.find(g=>g.id===c);return o?jsx(ze,{nodeKey:o,onBack:()=>n(null),onKeysChanged:()=>{n(null),d();},className:e,style:t}):x?jsxs("div",{className:i("space-y-4",e),style:t,children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx(ne,{count:3})]}):l?jsxs("div",{className:i("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l})]}),jsx("button",{onClick:()=>d(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]}):r.length===0?jsxs("div",{className:i("flex flex-col items-center justify-center gap-4 rounded-xl border border-dashed py-16",e),style:t,children:[jsx(KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]})]}):jsxs("div",{className:i("space-y-4",e),style:t,children:[jsxs("div",{className:"flex items-center justify-between mt-3",children:[jsx("h3",{className:"text-2xl font-semibold text-foreground",children:"Your Keys"}),jsxs("span",{className:"text-xs text-muted-foreground",children:[m.length," key",m.length!==1?"s":""," \xB7 ",K(f)," tokens"]}),jsx("div",{className:"flex gap-1 rounded-lg bg-muted/50 p-1",children:["active","listed"].map(g=>jsx("button",{onClick:()=>u(g),className:i("rounded-md px-3 py-1 text-xs font-medium capitalize transition-all",a===g?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:g},g))})]}),m.length===0?jsxs("div",{className:"flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-12",children:[jsx(KeyRound,{className:"h-8 w-8 text-muted-foreground"}),jsxs("p",{className:"text-sm text-muted-foreground",children:["No ",a," keys."]})]}):jsx("div",{className:"space-y-2",children:m.map(g=>jsx(jr,{nodeKey:g,onClick:()=>n(g.id)},g.id))})]})}var Dr=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"keys",label:"Keys"}];function Or({active:e,onChange:t}){return jsx("div",{role:"tablist","aria-label":"Key actions",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:Dr.map(({id:r,label:s})=>jsx("button",{role:"tab","aria-selected":e===r,"aria-controls":`panel-${r}`,id:`tab-${r}`,onClick:()=>t(r),className:i("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium transition-all",e===r?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:jsx("span",{className:"inline",children:s})},r))})}function Wr({defaultTab:e="buy",className:t,style:r}){let[s,x]=useState(e);return jsxs("div",{className:i("flex flex-col",t),style:r,children:[jsx("div",{className:"sticky top-0 z-10 bg-background/80 px-5 pb-3 pt-2 sm:pt-5 backdrop-blur-sm sm:px-10 md:px-16 lg:px-20",children:jsx("div",{className:"mx-auto max-w-xl",children:jsx(Or,{active:s,onChange:x})})}),jsx("div",{className:"flex flex-1 flex-col px-5 pb-8 sm:px-10 md:px-16 md:pb-12 lg:px-20",children:jsx("div",{className:"mx-auto w-full max-w-xl flex-1",children:jsxs("div",{role:"tabpanel",id:`panel-${s}`,"aria-labelledby":`tab-${s}`,children:[s==="buy"&&jsx(Ae,{className:"flex-1"}),s==="use"&&jsx(Me,{className:"flex-1"}),s==="keys"&&jsx(Ye,{className:"flex-1"})]})})})]})}function Hr({apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:x,stripePublicKey:l,theme:d,maxQuantity:c,keyImage:n,keyImageClass:a,aispImage:u,termsUrl:m,onMintSuccess:f,onMintError:o,onPaymentStart:g,onPaymentComplete:v,onListingCreated:T,onTransferComplete:w,defaultTab:E,className:$,style:P}){return jsx(Ie,{config:{apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:x,stripePublicKey:l,theme:d,maxQuantity:c,keyImage:n,keyImageClass:a,aispImage:u,termsUrl:m},callbacks:{onMintSuccess:f,onMintError:o,onPaymentStart:g,onPaymentComplete:v,onListingCreated:T,onTransferComplete:w},children:jsx(Wr,{defaultTab:E,className:$,style:P})})}function Yr({nodeKey:e,selected:t,onSelect:r}){return jsxs("button",{onClick:r,className:i("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsx("div",{className:i("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:i("text-xs font-medium capitalize",e.status==="active"?"text-green-500":"text-muted-foreground"),children:e.status})]}),jsx(J,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function qr({className:e,style:t}){let{config:r}=C(),{keys:s,loading:x,error:l,refresh:d}=q(),{listKey:c,listing:n,result:a,error:u}=ke(),[m,f]=useState(null),[o,g]=useState(""),[v,T]=useState(false),w=s.find(A=>A.id===m),E=parseInt(o.replace(/[^0-9]/g,""),10)||0,$=E>0&&Number.isFinite(E),P=!!w&&$&&v&&!n,re=async()=>{if(!P||!w)return;let A=E*100;await c(w.id,A)&&d();};if(a)return jsxs("div",{className:i("flex flex-col items-center gap-4 rounded-xl bg-green-500/10 py-12",e),style:t,children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the Global Open AI Network marketplace."}),jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsx("code",{children:a.listingId})]}),jsxs("a",{href:`https://market.stacknet.org/keys/${encodeURIComponent(a.keyId)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 rounded-xl bg-foreground px-6 py-3 text-sm font-semibold text-background transition-colors hover:bg-foreground/90",children:[jsx(ExternalLink,{className:"h-4 w-4"}),"View Listing"]})]});if(x)return jsxs("div",{className:i("space-y-5 px-1",e),style:t,children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx(ne,{count:2})]});if(l)return jsxs("div",{className:i("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l})]}),jsx("button",{onClick:()=>d(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let M=s.filter(A=>A.status==="active");return M.length===0?jsxs("div",{className:i("flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16",e),style:t,children:[jsx(AlertTriangle,{className:"h-8 w-8 text-muted-foreground"}),jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys to sell."})]}):jsxs("div",{className:i("space-y-5",e),style:t,children:[jsxs("div",{children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx("div",{className:"space-y-2",children:M.map(A=>jsx(Yr,{nodeKey:A,selected:m===A.id,onSelect:()=>f(A.id)},A.id))})]}),w&&jsxs("div",{className:"rounded-xl border bg-muted/30 p-5 space-y-2 text-sm",children:[w.keyIndex&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxs("span",{className:"text-foreground font-semibold",children:["#",w.keyIndex]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:w.id})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsx("span",{className:"text-foreground",children:r.stackName||"Unknown"})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Tokens (remaining / total)"}),jsxs("span",{className:"text-foreground",children:[K(w.tokenBalance)," / ",K(w.maxTokens)]})]}),w.paperWork&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Paper earned"}),jsx("span",{className:"text-foreground",children:w.paperWork})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:G(w.createdAt)})]})]}),jsxs("div",{children:[jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm sm:text-lg font-semibold text-foreground",children:"Listing Price (USD)"}),jsxs("div",{className:"relative",children:[jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:o,onChange:A=>{let se=A.target.value.replace(/[^0-9]/g,""),ce=parseInt(se,10);g(isNaN(ce)?"":ce.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-6 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxs("div",{className:"flex items-start gap-3",children:[jsx("button",{type:"button",role:"checkbox","aria-checked":v,onClick:()=>T(!v),className:i("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors cursor-pointer",v?"border-foreground bg-foreground":"border-muted-foreground/40"),children:v&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsx("a",{href:F(r.termsUrl,"/terms"),className:"text-foreground underline",target:"_blank",rel:"noopener noreferrer",children:"Terms"})]})]}),u&&jsx("p",{className:"text-sm text-red-500",children:u}),jsxs("button",{onClick:re,disabled:!P,className:i("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",P?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsx(ExternalLink,{className:"h-4 w-4"}),n?"Listing...":"List on Marketplace"]})]})}var Ge=20;function Je({nodeKey:e,className:t,style:r}){let[s,x]=useState(false),[l,d]=useState(false),c=useRef(null),{entries:n,loading:a}=ve(s?e.id:null);useEffect(()=>()=>{c.current&&clearTimeout(c.current);},[]);let u=useCallback(()=>{e.key&&(navigator.clipboard.writeText(e.key),d(true),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>d(false),2e3));},[e.key]),m=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500",f=n.slice(0,Ge);return jsxs("div",{className:i("rounded-lg border bg-background",t),style:r,children:[jsxs("div",{className:"p-4",children:[jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>x(!s),"aria-expanded":s,"aria-label":s?"Collapse ledger":"Expand ledger",className:"text-muted-foreground hover:text-foreground",children:s?jsx(ChevronDown,{className:"h-4 w-4"}):jsx(ChevronRight,{className:"h-4 w-4"})}),jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]})]}),jsx("span",{className:i("text-xs font-medium capitalize",m),children:e.status})]}),e.key&&jsxs("div",{className:"mb-3 flex items-center gap-2",children:[jsx("code",{className:"flex-1 truncate rounded bg-muted px-2 py-1 text-xs text-muted-foreground",children:e.key}),jsx("button",{onClick:u,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:l?jsx(Check,{className:"h-3.5 w-3.5 text-green-500"}):jsx(Copy,{className:"h-3.5 w-3.5"})})]}),jsx(J,{current:e.tokenBalance,max:e.maxTokens}),jsxs("div",{className:"mt-2 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:["Created ",G(e.createdAt)]}),e.expiresAt&&jsxs("span",{children:["Expires ",G(e.expiresAt)]})]})]}),s&&jsxs("div",{className:"border-t px-4 py-3",children:[jsx("h4",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Ledger"}),a?jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}):f.length===0?jsx("p",{className:"text-xs text-muted-foreground",children:"No ledger entries."}):jsxs("div",{className:"space-y-1.5",children:[f.map(o=>jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsxs("span",{className:i("font-medium",o.type==="credit"||o.type==="reward"?"text-green-500":"text-red-500"),children:[o.type==="credit"||o.type==="reward"?"+":"-",K(Math.abs(o.amount))]}),jsx("span",{className:"text-muted-foreground",children:o.description})]}),jsx("span",{className:"text-muted-foreground",children:G(o.createdAt)})]},o.id)),n.length>Ge&&jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Showing ",Ge," of ",n.length," entries"]})]})]})]})}var ss=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"keys",label:"Keys"}];function Pe({baseHref:e}){return jsx("div",{className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5 mb-6",children:ss.map(({id:t,label:r})=>jsx("a",{href:`${e}?tab=${t}`,className:"flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-all",children:r},t))})}function ns({getKeyHref:e="/keys/get",showTabs:t=true,className:r,style:s}){let{keys:x,totalBalance:l,loading:d,error:c,refresh:n}=q();return d?jsxs("div",{className:i("space-y-4",r),style:s,children:[t&&e&&jsx(Pe,{baseHref:e}),jsx(ne,{count:3})]}):c?jsxs("div",{className:i("space-y-4",r),style:s,children:[t&&e&&jsx(Pe,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:c})]}),jsx("button",{onClick:()=>n(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]})]}):x.length===0?jsxs("div",{className:i("space-y-4",r),style:s,children:[t&&e&&jsx(Pe,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed py-12",children:[jsx(KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]}),e&&jsx("a",{href:e,className:"rounded-lg bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]})]}):jsxs("div",{className:i("space-y-4",r),style:s,children:[t&&e&&jsx(Pe,{baseHref:e}),jsxs("div",{className:"flex items-center justify-between",children:[jsxs("p",{className:"text-sm text-muted-foreground",children:[x.length," key",x.length!==1?"s":""," \xB7 Total balance: ",K(l)]}),e&&jsx("a",{href:e,className:"rounded-md bg-foreground px-3 py-1.5 text-xs font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]}),x.map(a=>jsx(Je,{nodeKey:a},a.id))]})}function cs({nodeKey:e,selected:t,onSelect:r}){return jsxs("button",{onClick:r,className:i("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsx("div",{className:i("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:"text-xs font-medium capitalize text-green-500",children:e.status})]}),jsx(J,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function ds({className:e,style:t}){let{keys:r,loading:s}=q(),{transferKey:x,transferring:l,result:d,error:c}=Ne(),[n,a]=useState(null),[u,m]=useState(""),[f,o]=useState(false),g=r.filter(P=>P.status==="active"),v=g.find(P=>P.id===n),T=v&&u.trim()===v.userId,w=n&&u.trim().length>0&&f&&!T&&!l,E=async()=>{!n||!u.trim()||await x(n,u.trim());},$=()=>{a(null),m(""),o(false);};return d?jsxs("div",{className:i("flex flex-col items-center gap-4 py-8",e),style:t,children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsxs("div",{className:"text-center",children:[jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Transfer Complete"}),jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Key transferred successfully"})]}),jsxs("div",{className:"w-full max-w-sm space-y-2 rounded-xl border border-border bg-muted/30 p-4 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key"}),jsxs("span",{className:"font-mono text-foreground",children:[d.keyId.slice(0,20),"..."]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Recipient"}),jsxs("span",{className:"font-mono text-foreground",children:[d.toUserId.slice(0,20),"..."]})]})]}),jsx("button",{onClick:$,className:"mt-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Transfer Another"})]}):jsxs("div",{className:i("space-y-5",e),style:t,children:[jsxs("div",{children:[jsx("h3",{className:"mb-3 text-sm font-medium text-foreground",children:"Select Key to Transfer"}),s?jsx(ne,{count:2}):g.length===0?jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys available for transfer."}):jsx("div",{className:"space-y-2",children:g.map(P=>jsx(cs,{nodeKey:P,selected:n===P.id,onSelect:()=>a(P.id)},P.id))})]}),n&&jsxs("div",{children:[jsx("label",{className:"mb-1.5 block text-sm font-medium text-foreground",children:"Recipient User ID"}),jsx("input",{type:"text",value:u,onChange:P=>{m(P.target.value),o(false);},placeholder:"Enter recipient's user ID or global ID",className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-foreground/30 focus:outline-none focus:ring-1 focus:ring-foreground/10"}),T&&jsx("p",{className:"mt-1.5 text-xs text-red-500",children:"Cannot transfer a key to yourself"})]}),v&&u.trim().length>0&&!T&&jsx("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertTriangle,{className:"mt-0.5 h-5 w-5 shrink-0 text-amber-500"}),jsxs("div",{className:"space-y-3",children:[jsxs("div",{children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Confirm Transfer"}),jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["You are about to transfer key"," ",jsx("span",{className:"font-mono font-medium",children:v.keyIndex?`#${v.keyIndex}`:v.id.slice(0,12)})," ","(",K(v.tokenBalance)," tokens) to"," ",jsxs("span",{className:"font-mono font-medium",children:[u.trim().slice(0,20),"..."]})]})]}),jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[jsx("input",{type:"checkbox",checked:f,onChange:P=>o(P.target.checked),className:"mt-0.5 h-4 w-4 rounded border-border"}),jsx("span",{className:"text-xs text-muted-foreground",children:"I confirm this transfer is permanent and cannot be undone."})]})]})]})}),c&&jsx("p",{className:"text-sm text-red-500",children:c}),jsx("button",{onClick:E,disabled:!w,className:i("flex w-full items-center justify-center gap-2 rounded-lg px-4 py-3 text-sm font-medium transition-all",w?"bg-foreground text-background hover:opacity-90":"bg-muted text-muted-foreground cursor-not-allowed"),children:l?jsxs(Fragment,{children:[jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Transferring..."]}):jsxs(Fragment,{children:[jsx(Send,{className:"h-4 w-4"}),"Transfer Key"]})})]})}function Et(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[x,l]=useState(null),[d,c]=useState(null),n=useRef(true),a=useCallback(async m=>{try{s(!0),c(null);let f=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(m)}/file`,{method:"POST",headers:{"Content-Type":"application/json",...z()},credentials:"include",body:JSON.stringify({stackId:e.stackId})});if(!f.ok)throw new Error(await B(f,`Filing failed (${f.status})`));let o=await f.json();return n.current&&(l(o),t.onFilingComplete?.(o)),o}catch(f){let o=f instanceof Error?f:new Error("Filing failed");return n.current&&c(o.message),t.onFilingError?.(o),null}finally{n.current&&s(false);}},[e.apiBaseUrl,e.stackId,t]),u=useCallback(()=>{l(null),c(null);},[]);return {filePaperwork:a,filing:r,result:x,error:d,reset:u}}function Se(e,t=6,r=6){return !e||e.length<=t+r+1?e:`${e.slice(0,t)}\u2026${e.slice(-r)}`}function gs({nodeKey:e,stackName:t}){let r=Math.max(0,e.maxTokens-e.tokenBalance);return jsxs("div",{className:"bg-muted/30 p-5 space-y-2 text-sm",children:[e.keyIndex!=null&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxs("span",{className:"text-foreground font-semibold",children:["#",e.keyIndex]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:Se(e.id,8,8)})]}),t&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsx("span",{className:"text-foreground",children:t})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Compute tokens used"}),jsxs("span",{className:"text-foreground",children:[K(r)," / ",K(e.maxTokens)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:G(e.createdAt)})]})]})}function Ce(){return jsxs("div",{className:"bg-stacknet-blue text-white p-8 lg:w-2/5 flex flex-col justify-between min-h-[260px]",children:[jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-sm font-mono opacity-80",children:"stacknet | filing"}),jsx("h2",{className:"text-2xl font-semibold leading-snug",children:"File paperwork to redeem Paper."}),jsx("p",{className:"text-sm opacity-80 leading-relaxed",children:"Filing submits your prepared paperwork on chain. Once validated, Paper is sent to your registered payment address."})]}),jsx("p",{className:"text-xs opacity-60 mt-8",children:"Powered by StackNet"})]})}function xs({keyId:e,paymentAddress:t,onComplete:r,onConfigurePayment:s,onBack:x,className:l,style:d}){let{config:c}=C(),{keys:n,loading:a,error:u,refresh:m}=q(),{filePaperwork:f,filing:o,result:g,error:v,reset:T}=Et(),w=n.find(M=>M.id===e),E=!!w?.paperWork&&w.paperWork.length>0,$=!!t&&t.length>0,P=E&&$&&!o&&!g,re=async()=>{if(!P||!w)return;let M=await f(w.id);M&&(m(),r?.(M));};return g?jsxs("div",{className:i("flex flex-col lg:flex-row",l),style:d,children:[jsx(Ce,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-6",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx(CheckCircle2,{className:"h-7 w-7 text-green-500","aria-hidden":true}),jsx("h3",{className:"text-2xl font-semibold text-foreground",children:"Paperwork filed"})]}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your filing has been submitted. Paper will be released to your payment address once the watcher network validates the proof."}),jsxs("div",{className:"bg-muted/30 p-5 space-y-3 text-sm",children:[jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Status"}),jsx("span",{className:"text-foreground capitalize",children:g.status})]}),jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Paper amount"}),jsxs("span",{className:"text-foreground tabular-nums",children:[(g.paperAmount/1e6).toLocaleString(void 0,{maximumFractionDigits:6})," Paper"]})]}),jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"File hash"}),jsx("code",{className:"text-xs text-foreground break-all",children:Se(g.fileHash,10,10)})]}),g.txSignature&&jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Tx"}),jsx("a",{href:`https://solscan.io/tx/${encodeURIComponent(g.txSignature)}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-foreground underline underline-offset-4",children:Se(g.txSignature,8,8)})]}),jsxs("div",{className:"flex justify-between gap-4",children:[jsx("span",{className:"text-muted-foreground",children:"Beneficiary"}),jsx("code",{className:"text-xs text-foreground",children:Se(g.beneficiary,6,6)})]})]}),x&&jsx("button",{type:"button",onClick:()=>{T(),x();},className:"w-full bg-foreground text-background py-4 text-sm font-semibold hover:bg-foreground/90 transition-colors",children:"Back to dashboard"})]})]}):a?jsxs("div",{className:i("flex flex-col lg:flex-row",l),style:d,children:[jsx(Ce,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-4",children:[jsx("div",{className:"h-7 w-48 bg-muted animate-pulse"}),jsx("div",{className:"h-32 w-full bg-muted animate-pulse"}),jsx("div",{className:"h-12 w-full bg-muted animate-pulse"})]})]}):u||!w?jsxs("div",{className:i("flex flex-col lg:flex-row",l),style:d,children:[jsx(Ce,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx(AlertCircle,{className:"h-6 w-6 text-red-500","aria-hidden":true}),jsx("h3",{className:"text-xl font-semibold text-foreground",children:u?"Unable to load keys":"Key not found"})]}),jsx("p",{className:"text-sm text-muted-foreground",children:u||`No key with id ${e} on this account.`}),jsx("button",{type:"button",onClick:()=>m(),className:"bg-foreground text-background px-4 py-3 text-sm font-semibold hover:bg-foreground/90 transition-colors",children:"Try again"})]})]}):jsxs("div",{className:i("flex flex-col lg:flex-row",l),style:d,children:[jsx(Ce,{}),jsxs("div",{className:"flex-1 bg-background p-8 space-y-6",children:[jsxs("div",{children:[jsx("h2",{className:"text-2xl font-semibold text-foreground",children:"File paperwork"}),jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Review the key and beneficiary, then submit your filing."})]}),jsx(gs,{nodeKey:w,stackName:c.stackName}),!E&&jsx("div",{className:"bg-muted/30 p-4 text-sm text-muted-foreground",children:"This key has no pending paperwork. Run your node to earn Paper, then return to file."}),jsxs("div",{className:"space-y-2",children:[jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Beneficiary (payment address)"}),$?jsx("div",{className:"bg-muted/30 p-4",children:jsx("code",{className:"text-xs text-foreground break-all",children:t})}):jsxs("div",{className:"bg-muted/30 p-4 space-y-3",children:[jsx("p",{className:"text-sm text-foreground",children:"You haven't set a payment address yet."}),s&&jsx("button",{type:"button",onClick:s,className:"bg-foreground text-background px-4 py-3 text-sm font-semibold hover:bg-foreground/90 transition-colors",children:"Set payment address"})]})]}),jsxs("div",{className:"bg-muted/30 p-4 flex gap-3",children:[jsx(Info,{className:"h-5 w-5 shrink-0 text-foreground mt-0.5","aria-hidden":true}),jsxs("p",{className:"text-sm text-foreground leading-relaxed",children:[jsx("span",{className:"font-semibold",children:"Important."})," ","Filing is one-time per key. Paper will be sent to the address above and cannot be reversed. Double-check the address before submitting."]})]}),v&&jsx("p",{className:"text-sm text-red-500",children:v}),jsx("button",{type:"button",onClick:re,disabled:!P,className:i("w-full py-4 text-sm font-semibold transition-colors",P?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:o?"Filing\u2026":"File Paperwork"})]})]})}function ks(e){return typeof e.paperWork=="string"&&e.paperWork.length>0}function Ns({count:e=3}){return jsx("div",{className:"space-y-2",children:Array.from({length:e}).map((t,r)=>jsxs("div",{className:"bg-muted/30 p-4 space-y-3",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("div",{className:"h-4 w-40 bg-muted animate-pulse"}),jsx("div",{className:"h-4 w-16 bg-muted animate-pulse"})]}),jsx("div",{className:"h-3 w-32 bg-muted animate-pulse"})]},r))})}function vs({nodeKey:e,onSelect:t}){let r=Math.max(0,e.maxTokens-e.tokenBalance);return jsxs("button",{type:"button",onClick:t,className:"group flex w-full items-center gap-4 bg-muted/30 p-4 text-left transition-colors hover:bg-muted/50",children:[jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsxs("span",{className:"text-sm font-semibold text-foreground",children:[e.keyIndex!=null?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:"text-xs text-muted-foreground",children:e.stackName||""})]}),jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[jsxs("span",{className:"tabular-nums",children:[K(r)," / ",K(e.maxTokens)," compute used"]}),jsx("span",{className:"text-foreground",children:"Eligible"})]})]}),jsx(ChevronRight,{className:"h-5 w-5 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5","aria-hidden":true})]})}function hs({onSelect:e,className:t,style:r}){let{keys:s,loading:x,error:l,refresh:d}=q();if(x)return jsx("div",{className:i("space-y-3",t),style:r,children:jsx(Ns,{count:3})});if(l)return jsx("div",{className:i("space-y-3",t),style:r,children:jsxs("div",{className:"bg-muted/30 p-5 text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:l}),jsx("button",{type:"button",onClick:()=>d(),className:"mt-3 bg-foreground text-background px-4 py-2 text-xs font-semibold hover:bg-foreground/90 transition-colors",children:"Try again"})]})});let c=s.filter(ks);return c.length===0?jsxs("div",{className:i("flex flex-col items-center justify-center gap-3 bg-muted/20 py-16",t),style:r,children:[jsx(FileText,{className:"h-10 w-10 text-muted-foreground","aria-hidden":true}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys with pending paperwork"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Run a node to earn Paper, then return here to file."})]})]}):jsx("div",{className:i("space-y-2",t),style:r,children:c.map(n=>jsx(vs,{nodeKey:n,onSelect:()=>e(n.id)},n.id))})}
2
+ export{we as ASCII_KEY_ART,xe as BottomSheet,Hr as BuyKeyWidget,Ae as BuyPanel,He as DefaultKeyArt,hs as FilePaperworkList,xs as FilePaperworkView,J as KeyBalanceBar,Je as KeyCard,ze as KeyDetailView,ns as KeyList,Ie as KeyUtilsProvider,Ye as KeysPanel,Ee as MintSuccess,qr as SellPanel,Le as SolanaPayButton,ds as TransferPanel,Me as UsePanel,C as useKeyUtilsContext};
@@ -1 +1 @@
1
- 'use strict';function m(e,i){if(typeof e!="string"||e.length===0)return i;let r=e.replace(/[\u0000-\u001F\u007F]/g," ");return r.length>500?r.slice(0,500)+"\u2026":r}async function u(e,i){try{let r=await e.json();if(r&&typeof r=="object"&&"error"in r)return m(r.error,i)}catch{}return i}function l(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}async function f(e){if(!e)return {};let i=e();return i instanceof Promise?await i:i}async function d(e,i={}){let{getHeaders:r,...g}=i,a=await f(r),n=await fetch(e,{...g,headers:{"Content-Type":"application/json",...a,...g.headers},credentials:"include"});if(!n.ok)throw new Error(await u(n,`Request failed (${n.status})`));return n.json()}function p(e){let{apiBaseUrl:i,stackId:r,stackName:g,getHeaders:a}=e,n=`${i}/api/keys`;return {async getKeys(){let t=await d(n,{getHeaders:a});return (Array.isArray(t)?t:t.keys??[]).map(l)},async getLedger(t){let s=await d(`${n}/${encodeURIComponent(t)}/ledger`,{getHeaders:a});return Array.isArray(s)?s:s.entries??[]},async getPricing(){return d(`${n}/pricing`,{getHeaders:a})},async mint(t,s,y=1){try{let c=await d(n+"/mint",{method:"POST",body:JSON.stringify({paymentMethod:t,paymentRef:s,quantity:y,stackId:r}),getHeaders:a}),o=c.keys?.[0]||c;return {success:!0,key:{id:o.keyId||o.id||"",key:o.key||"",userId:o.userId||"",status:"active",tokenBalance:o.tokenBalance??o.currentTokenBalance??0,maxTokens:o.initialTokenBalance??o.tokenBalance??0,createdAt:String(o.createdAt||Date.now())},transactionId:s}}catch(c){return {success:false,error:c instanceof Error?c.message:"Key generation failed"}}},async listKey(t,s){return d(`${n}/${encodeURIComponent(t)}/list`,{method:"POST",body:JSON.stringify({askPriceCents:s,stackId:r,stackName:g}),getHeaders:a})},async delistKey(t){await d(`${n}/${encodeURIComponent(t)}/list`,{method:"DELETE",getHeaders:a});},async transferKey(t,s){return d(`${n}/${encodeURIComponent(t)}/transfer`,{method:"POST",body:JSON.stringify({recipientId:s}),getHeaders:a})},async createStripeSession(t,s,y){return d(`${n}/stripe-session`,{method:"POST",body:JSON.stringify({priceCents:t,quantity:s,stackId:r,referrerUrl:y}),getHeaders:a})}}}exports.createKeyClient=p;
1
+ 'use strict';function m(e,n){if(typeof e!="string"||e.length===0)return n;let t=e.replace(/[\u0000-\u001F\u007F]/g," ");return t.length>500?t.slice(0,500)+"\u2026":t}async function y(e,n){try{let t=await e.json();if(t&&typeof t=="object"&&"error"in t)return m(t.error,n)}catch{}return n}function l(e){let n=e.type||e.entry_type||"debit",t=e.amount??e.tokens??e.token_amount??0,c=e.description||e.memo||e.reason||p(n);return {id:e.id||"",keyId:e.keyId||e.key_id||"",type:n,amount:t,description:c,createdAt:String(e.createdAt??e.created_at??e.timestamp??""),metadata:e.metadata||void 0}}function p(e){switch(e){case "credit":return "Credit";case "debit":return "Usage";case "mint":return "Mint";case "reward":return "Reward";default:return ""}}function f(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}async function k(e){if(!e)return {};let n=e();return n instanceof Promise?await n:n}async function d(e,n={}){let{getHeaders:t,...c}=n,a=await k(t),s=await fetch(e,{...c,headers:{"Content-Type":"application/json",...a,...c.headers},credentials:"include"});if(!s.ok)throw new Error(await y(s,`Request failed (${s.status})`));return s.json()}function P(e){let{apiBaseUrl:n,stackId:t,stackName:c,getHeaders:a}=e,s=`${n}/api/keys`;return {async getKeys(){let r=await d(s,{getHeaders:a});return (Array.isArray(r)?r:r.keys??[]).map(f)},async getLedger(r){let i=await d(`${s}/${encodeURIComponent(r)}/ledger`,{getHeaders:a});return (Array.isArray(i)?i:i.entries??[]).map(l)},async getPricing(){return d(`${s}/pricing`,{getHeaders:a})},async mint(r,i,u=1){try{let g=await d(s+"/mint",{method:"POST",body:JSON.stringify({paymentMethod:r,paymentRef:i,quantity:u,stackId:t}),getHeaders:a}),o=g.keys?.[0]||g;return {success:!0,key:{id:o.keyId||o.id||"",key:o.key||"",userId:o.userId||"",status:"active",tokenBalance:o.tokenBalance??o.currentTokenBalance??0,maxTokens:o.initialTokenBalance??o.tokenBalance??0,createdAt:String(o.createdAt||Date.now())},transactionId:i}}catch(g){return {success:false,error:g instanceof Error?g.message:"Key generation failed"}}},async listKey(r,i){return d(`${s}/${encodeURIComponent(r)}/list`,{method:"POST",body:JSON.stringify({askPriceCents:i,stackId:t,stackName:c}),getHeaders:a})},async delistKey(r){await d(`${s}/${encodeURIComponent(r)}/list`,{method:"DELETE",getHeaders:a});},async transferKey(r,i){return d(`${s}/${encodeURIComponent(r)}/transfer`,{method:"POST",body:JSON.stringify({recipientId:i}),getHeaders:a})},async createStripeSession(r,i,u){return d(`${s}/stripe-session`,{method:"POST",body:JSON.stringify({priceCents:r,quantity:i,stackId:t,referrerUrl:u}),getHeaders:a})}}}exports.createKeyClient=P;
@@ -1 +1 @@
1
- function m(e,i){if(typeof e!="string"||e.length===0)return i;let r=e.replace(/[\u0000-\u001F\u007F]/g," ");return r.length>500?r.slice(0,500)+"\u2026":r}async function u(e,i){try{let r=await e.json();if(r&&typeof r=="object"&&"error"in r)return m(r.error,i)}catch{}return i}function l(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}async function f(e){if(!e)return {};let i=e();return i instanceof Promise?await i:i}async function d(e,i={}){let{getHeaders:r,...g}=i,a=await f(r),n=await fetch(e,{...g,headers:{"Content-Type":"application/json",...a,...g.headers},credentials:"include"});if(!n.ok)throw new Error(await u(n,`Request failed (${n.status})`));return n.json()}function p(e){let{apiBaseUrl:i,stackId:r,stackName:g,getHeaders:a}=e,n=`${i}/api/keys`;return {async getKeys(){let t=await d(n,{getHeaders:a});return (Array.isArray(t)?t:t.keys??[]).map(l)},async getLedger(t){let s=await d(`${n}/${encodeURIComponent(t)}/ledger`,{getHeaders:a});return Array.isArray(s)?s:s.entries??[]},async getPricing(){return d(`${n}/pricing`,{getHeaders:a})},async mint(t,s,y=1){try{let c=await d(n+"/mint",{method:"POST",body:JSON.stringify({paymentMethod:t,paymentRef:s,quantity:y,stackId:r}),getHeaders:a}),o=c.keys?.[0]||c;return {success:!0,key:{id:o.keyId||o.id||"",key:o.key||"",userId:o.userId||"",status:"active",tokenBalance:o.tokenBalance??o.currentTokenBalance??0,maxTokens:o.initialTokenBalance??o.tokenBalance??0,createdAt:String(o.createdAt||Date.now())},transactionId:s}}catch(c){return {success:false,error:c instanceof Error?c.message:"Key generation failed"}}},async listKey(t,s){return d(`${n}/${encodeURIComponent(t)}/list`,{method:"POST",body:JSON.stringify({askPriceCents:s,stackId:r,stackName:g}),getHeaders:a})},async delistKey(t){await d(`${n}/${encodeURIComponent(t)}/list`,{method:"DELETE",getHeaders:a});},async transferKey(t,s){return d(`${n}/${encodeURIComponent(t)}/transfer`,{method:"POST",body:JSON.stringify({recipientId:s}),getHeaders:a})},async createStripeSession(t,s,y){return d(`${n}/stripe-session`,{method:"POST",body:JSON.stringify({priceCents:t,quantity:s,stackId:r,referrerUrl:y}),getHeaders:a})}}}export{p as createKeyClient};
1
+ function m(e,n){if(typeof e!="string"||e.length===0)return n;let t=e.replace(/[\u0000-\u001F\u007F]/g," ");return t.length>500?t.slice(0,500)+"\u2026":t}async function y(e,n){try{let t=await e.json();if(t&&typeof t=="object"&&"error"in t)return m(t.error,n)}catch{}return n}function l(e){let n=e.type||e.entry_type||"debit",t=e.amount??e.tokens??e.token_amount??0,c=e.description||e.memo||e.reason||p(n);return {id:e.id||"",keyId:e.keyId||e.key_id||"",type:n,amount:t,description:c,createdAt:String(e.createdAt??e.created_at??e.timestamp??""),metadata:e.metadata||void 0}}function p(e){switch(e){case "credit":return "Credit";case "debit":return "Usage";case "mint":return "Mint";case "reward":return "Reward";default:return ""}}function f(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}async function k(e){if(!e)return {};let n=e();return n instanceof Promise?await n:n}async function d(e,n={}){let{getHeaders:t,...c}=n,a=await k(t),s=await fetch(e,{...c,headers:{"Content-Type":"application/json",...a,...c.headers},credentials:"include"});if(!s.ok)throw new Error(await y(s,`Request failed (${s.status})`));return s.json()}function P(e){let{apiBaseUrl:n,stackId:t,stackName:c,getHeaders:a}=e,s=`${n}/api/keys`;return {async getKeys(){let r=await d(s,{getHeaders:a});return (Array.isArray(r)?r:r.keys??[]).map(f)},async getLedger(r){let i=await d(`${s}/${encodeURIComponent(r)}/ledger`,{getHeaders:a});return (Array.isArray(i)?i:i.entries??[]).map(l)},async getPricing(){return d(`${s}/pricing`,{getHeaders:a})},async mint(r,i,u=1){try{let g=await d(s+"/mint",{method:"POST",body:JSON.stringify({paymentMethod:r,paymentRef:i,quantity:u,stackId:t}),getHeaders:a}),o=g.keys?.[0]||g;return {success:!0,key:{id:o.keyId||o.id||"",key:o.key||"",userId:o.userId||"",status:"active",tokenBalance:o.tokenBalance??o.currentTokenBalance??0,maxTokens:o.initialTokenBalance??o.tokenBalance??0,createdAt:String(o.createdAt||Date.now())},transactionId:i}}catch(g){return {success:false,error:g instanceof Error?g.message:"Key generation failed"}}},async listKey(r,i){return d(`${s}/${encodeURIComponent(r)}/list`,{method:"POST",body:JSON.stringify({askPriceCents:i,stackId:t,stackName:c}),getHeaders:a})},async delistKey(r){await d(`${s}/${encodeURIComponent(r)}/list`,{method:"DELETE",getHeaders:a});},async transferKey(r,i){return d(`${s}/${encodeURIComponent(r)}/transfer`,{method:"POST",body:JSON.stringify({recipientId:i}),getHeaders:a})},async createStripeSession(r,i,u){return d(`${s}/stripe-session`,{method:"POST",body:JSON.stringify({priceCents:r,quantity:i,stackId:t,referrerUrl:u}),getHeaders:a})}}}export{P as createKeyClient};
@@ -1,2 +1,2 @@
1
- 'use strict';var react=require('react');require('react/jsx-runtime');var z=react.createContext(null);function d(){let e=react.useContext(z);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function Y(e,a){if(typeof e!="string"||e.length===0)return a;let i=e.replace(/[\u0000-\u001F\u007F]/g," ");return i.length>500?i.slice(0,500)+"\u2026":i}async function y(e,a){try{let i=await e.json();if(i&&typeof i=="object"&&"error"in i)return Y(i.error,a)}catch{}return a}function G(){let{config:e}=d(),[a,i]=react.useState(null),[u,f]=react.useState(true),[m,p]=react.useState(null),r=react.useRef(true),o=react.useRef(e.apiBaseUrl);o.current=e.apiBaseUrl;let c=async()=>{try{r.current&&(f(!0),p(null));let s=await fetch(`${o.current}/api/keys/pricing`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Pricing unavailable (${s.status})`));let n=await s.json();r.current&&i(n);}catch(s){r.current&&p(s instanceof Error?s.message:"Failed to fetch pricing");}finally{r.current&&f(false);}};return react.useEffect(()=>{r.current=true,c();let s=setInterval(c,6e4);return ()=>{r.current=false,clearInterval(s);}},[]),{pricing:a,loading:u,error:m,refresh:c}}function re(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function ne(){let{config:e}=d(),[a,i]=react.useState([]),[u,f]=react.useState(true),[m,p]=react.useState(null),r=react.useRef(true),o=e.apiBaseUrl,c=react.useCallback(async()=>{try{f(!0),p(null);let n=await fetch(`${o}/api/keys`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch keys (${n.status})`));let t=await n.json(),l=Array.isArray(t)?t:t.keys??[];r.current&&i(l.map(re));}catch(n){r.current&&p(n instanceof Error?n.message:"Failed to fetch keys");}finally{r.current&&f(false);}},[o]);react.useEffect(()=>(r.current=true,c(),()=>{r.current=false;}),[c]);let s=a.reduce((n,t)=>n+t.tokenBalance,0);return {keys:a,totalBalance:s,loading:u,error:m,refresh:c}}function ae(e){let{config:a}=d(),[i,u]=react.useState([]),[f,m]=react.useState(false),[p,r]=react.useState(null),o=react.useRef(true),c=a.apiBaseUrl,s=react.useCallback(async()=>{if(e)try{m(!0),r(null);let n=await fetch(`${c}/api/keys/${encodeURIComponent(e)}/ledger`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch ledger (${n.status})`));let t=await n.json();o.current&&u(Array.isArray(t)?t:t.entries??[]);}catch(n){o.current&&r(n instanceof Error?n.message:"Failed to fetch ledger");}finally{o.current&&m(false);}},[c,e]);return react.useEffect(()=>(o.current=true,s(),()=>{o.current=false;}),[s]),{entries:i,loading:f,error:p,refresh:s}}function k(){if(typeof document>"u")return {};let e=document.cookie.match(/(?:^|;\s*)__csrf=([^;]*)/);return e?{"x-csrf-token":e[1]}:{}}function ce(){let{config:e,callbacks:a}=d(),[i,u]=react.useState(false),[f,m]=react.useState(null),[p,r]=react.useState(null);return {mint:react.useCallback(async(c,s,n=1)=>{try{u(!0),r(null),a.onPaymentComplete?.(c,s);let t=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({paymentMethod:c,paymentRef:s,quantity:n,stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Key generation failed (${t.status})`));let l=await t.json(),g=l.keys?.[0]||l,h={success:!0,key:{id:g.keyId||g.id||"",key:g.key||"",userId:g.userId||"",status:"active",tokenBalance:g.tokenBalance??g.currentTokenBalance??0,maxTokens:g.initialTokenBalance??g.tokenBalance??0,createdAt:String(g.createdAt||Date.now())},transactionId:s};return m(h),a.onMintSuccess?.(h),h}catch(t){let l=t instanceof Error?t:new Error("Key generation failed");return r(l.message),a.onMintError?.(l),{success:false,error:l.message}}finally{u(false);}},[e.apiBaseUrl,a]),minting:i,result:f,error:p}}function fe(){let{config:e,callbacks:a}=d(),[i,u]=react.useState(false),[f,m]=react.useState(null),[p,r]=react.useState(null),o=react.useRef(true),c=react.useCallback(async(n,t)=>{try{u(!0),r(null);let l=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({askPriceCents:t,stackId:e.stackId,stackName:e.stackName})});if(!l.ok)throw new Error(await y(l,`Listing failed (${l.status})`));let g=await l.json();return o.current&&(m(g),a.onListingCreated?.(g)),g}catch(l){let g=l instanceof Error?l.message:"Listing failed";return o.current&&r(g),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,e.stackName,a]),s=react.useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"DELETE",headers:{...k()},credentials:"include"});if(!t.ok)throw new Error(await y(t,`Delist failed (${t.status})`));return o.current&&m(null),!0}catch(t){let l=t instanceof Error?t.message:"Delist failed";return o.current&&r(l),false}finally{o.current&&u(false);}},[e.apiBaseUrl]);return {listKey:c,delistKey:s,listing:i,result:f,error:p}}function de(){let{config:e}=d(),[a,i]=react.useState(false),[u,f]=react.useState(null),m=react.useRef(true);return {createSession:react.useCallback(async(r,o)=>{try{i(!0),f(null);let c=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({priceCents:r,quantity:o,stackId:e.stackId,referrerUrl:window.location.href})});if(!c.ok)throw new Error(await y(c,`Checkout failed (${c.status})`));let{url:s}=await c.json();if(!s)throw new Error("No checkout URL returned");let n;try{n=new URL(s);}catch{throw new Error("Invalid checkout URL")}if(n.protocol!=="https:"||!/(^|\.)stripe\.com$/.test(n.hostname))throw new Error("Refusing to redirect to non-Stripe URL");try{sessionStorage.setItem("keyutils_stripe_pending","1"),sessionStorage.setItem("keyutils_stripe_quantity",String(o));}catch{}window.location.href=n.toString();}catch(c){if(m.current){let s=c instanceof Error?c.message:"Checkout failed";f(s),i(false);}}},[e.apiBaseUrl,e.stackId]),loading:a,error:u}}function _(e,a="#"){if(!e||typeof e!="string")return a;let i=e.trim();if(i===""||i==="#")return a;if(i.startsWith("/")||i.startsWith("./")||i.startsWith("../"))return i;try{let u=new URL(i);if(u.protocol==="http:"||u.protocol==="https:")return u.toString()}catch{}return a}var A=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function ge(){let{config:e}=d(),[a,i]=react.useState(false),[u,f]=react.useState(null);return {pay:react.useCallback(async p=>{if(!e.merchantWallet||!A.test(e.merchantWallet))throw new Error("Merchant wallet not configured");try{i(!0),f(null);let{Connection:r,PublicKey:o,Transaction:c,SystemProgram:s}=await import('@solana/web3.js'),n=typeof window<"u"?window.solana:void 0;if(!n||typeof n!="object"||!n.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let t=n,l=new o(e.merchantWallet),g=await t.connect(),h=new o(g.publicKey.toString()),B="https://api.mainnet-beta.solana.com",I=_(e.solanaRpcUrl,B),H=I==="#"?B:I,O=new r(H),{blockhash:W}=await O.getLatestBlockhash(),R=BigInt(Math.floor(p*1e9)),U=e.protocolTreasuryWallet,T=e.protocolFeeBps??500,w=new c({recentBlockhash:W,feePayer:h});if(U&&A.test(U)&&T>0){let F=R*BigInt(T)/10000n,J=R-F,V=new o(U);w.add(s.transfer({fromPubkey:h,toPubkey:l,lamports:Number(J)}),s.transfer({fromPubkey:h,toPubkey:V,lamports:Number(F)}));}else w.add(s.transfer({fromPubkey:h,toPubkey:l,lamports:Number(R)}));let{signature:D}=await t.signAndSendTransaction(w);return D}catch(r){let o=r instanceof Error?r:new Error("SOL payment failed");throw f(o.message),o}finally{i(false);}},[e.merchantWallet,e.protocolTreasuryWallet,e.protocolFeeBps,e.solanaRpcUrl]),processing:a,error:u}}function Re(){let{config:e,callbacks:a}=d(),[i,u]=react.useState(false),[f,m]=react.useState(null),[p,r]=react.useState(null),o=react.useRef(true);return {transferKey:react.useCallback(async(s,n)=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(s)}/transfer`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({recipientId:n})});if(!t.ok)throw new Error(await y(t,`Transfer failed (${t.status})`));let l=await t.json();return o.current&&(m(l),a.onTransferComplete?.(l)),l}catch(t){let l=t instanceof Error?t.message:"Transfer failed";return o.current&&r(l),null}finally{o.current&&u(false);}},[e.apiBaseUrl,a]),transferring:i,result:f,error:p}}function we(){let{config:e,callbacks:a}=d(),[i,u]=react.useState(false),[f,m]=react.useState(null),[p,r]=react.useState(null),o=react.useRef(true),c=react.useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/file`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Filing failed (${t.status})`));let l=await t.json();return o.current&&(m(l),a.onFilingComplete?.(l)),l}catch(t){let l=t instanceof Error?t:new Error("Filing failed");return o.current&&r(l.message),a.onFilingError?.(l),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,a]),s=react.useCallback(()=>{m(null),r(null);},[]);return {filePaperwork:c,filing:i,result:f,error:p,reset:s}}function Ke(){let{config:e}=d(),[a,i]=react.useState([]),[u,f]=react.useState(true),[m,p]=react.useState(null),r=react.useRef(true),o=e.apiBaseUrl,c=react.useCallback(async()=>{try{f(!0),p(null);let s=await fetch(`${o}/api/keys/filings`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Failed to fetch filings (${s.status})`));let n=await s.json(),t=Array.isArray(n)?n:n.filings??[];r.current&&i(t);}catch(s){r.current&&p(s instanceof Error?s.message:"Failed to fetch filings");}finally{r.current&&f(false);}},[o]);return react.useEffect(()=>(r.current=true,c(),()=>{r.current=false;}),[c]),{entries:a,loading:u,error:m,refresh:c}}
2
- exports.useFilePaperwork=we;exports.useFilingHistory=Ke;exports.useKeyLedger=ae;exports.useKeys=ne;exports.useListKey=fe;exports.useMintKey=ce;exports.usePricing=G;exports.useSolanaPayment=ge;exports.useStripeCheckout=de;exports.useTransferKey=Re;
1
+ 'use strict';var react=require('react');require('react/jsx-runtime');var Y=react.createContext(null);function m(){let e=react.useContext(Y);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function Z(e,a){if(typeof e!="string"||e.length===0)return a;let i=e.replace(/[\u0000-\u001F\u007F]/g," ");return i.length>500?i.slice(0,500)+"\u2026":i}async function y(e,a){try{let i=await e.json();if(i&&typeof i=="object"&&"error"in i)return Z(i.error,a)}catch{}return a}function Q(){let{config:e}=m(),[a,i]=react.useState(null),[u,f]=react.useState(true),[d,g]=react.useState(null),r=react.useRef(true),o=react.useRef(e.apiBaseUrl);o.current=e.apiBaseUrl;let l=async()=>{try{r.current&&(f(!0),g(null));let s=await fetch(`${o.current}/api/keys/pricing`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Pricing unavailable (${s.status})`));let n=await s.json();r.current&&i(n);}catch(s){r.current&&g(s instanceof Error?s.message:"Failed to fetch pricing");}finally{r.current&&f(false);}};return react.useEffect(()=>{r.current=true,l();let s=setInterval(l,6e4);return ()=>{r.current=false,clearInterval(s);}},[]),{pricing:a,loading:u,error:d,refresh:l}}function ne(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function se(){let{config:e}=m(),[a,i]=react.useState([]),[u,f]=react.useState(true),[d,g]=react.useState(null),r=react.useRef(true),o=e.apiBaseUrl,l=react.useCallback(async()=>{try{f(!0),g(null);let n=await fetch(`${o}/api/keys`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch keys (${n.status})`));let t=await n.json(),c=Array.isArray(t)?t:t.keys??[];r.current&&i(c.map(ne));}catch(n){r.current&&g(n instanceof Error?n.message:"Failed to fetch keys");}finally{r.current&&f(false);}},[o]);react.useEffect(()=>(r.current=true,l(),()=>{r.current=false;}),[l]);let s=a.reduce((n,t)=>n+t.tokenBalance,0);return {keys:a,totalBalance:s,loading:u,error:d,refresh:l}}function N(e){let a=e.type||e.entry_type||"debit",i=e.amount??e.tokens??e.token_amount??0,u=e.description||e.memo||e.reason||ie(a);return {id:e.id||"",keyId:e.keyId||e.key_id||"",type:a,amount:i,description:u,createdAt:String(e.createdAt??e.created_at??e.timestamp??""),metadata:e.metadata||void 0}}function ie(e){switch(e){case "credit":return "Credit";case "debit":return "Usage";case "mint":return "Mint";case "reward":return "Reward";default:return ""}}function le(e){let{config:a}=m(),[i,u]=react.useState([]),[f,d]=react.useState(false),[g,r]=react.useState(null),o=react.useRef(true),l=a.apiBaseUrl,s=react.useCallback(async()=>{if(e)try{d(!0),r(null);let n=await fetch(`${l}/api/keys/${encodeURIComponent(e)}/ledger`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch ledger (${n.status})`));let t=await n.json(),c=Array.isArray(t)?t:t.entries??[];o.current&&u(c.map(N));}catch(n){o.current&&r(n instanceof Error?n.message:"Failed to fetch ledger");}finally{o.current&&d(false);}},[l,e]);return react.useEffect(()=>(o.current=true,s(),()=>{o.current=false;}),[s]),{entries:i,loading:f,error:g,refresh:s}}function k(){if(typeof document>"u")return {};let e=document.cookie.match(/(?:^|;\s*)__csrf=([^;]*)/);return e?{"x-csrf-token":e[1]}:{}}function fe(){let{config:e,callbacks:a}=m(),[i,u]=react.useState(false),[f,d]=react.useState(null),[g,r]=react.useState(null);return {mint:react.useCallback(async(l,s,n=1)=>{try{u(!0),r(null),a.onPaymentComplete?.(l,s);let t=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({paymentMethod:l,paymentRef:s,quantity:n,stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Key generation failed (${t.status})`));let c=await t.json(),p=c.keys?.[0]||c,h={success:!0,key:{id:p.keyId||p.id||"",key:p.key||"",userId:p.userId||"",status:"active",tokenBalance:p.tokenBalance??p.currentTokenBalance??0,maxTokens:p.initialTokenBalance??p.tokenBalance??0,createdAt:String(p.createdAt||Date.now())},transactionId:s};return d(h),a.onMintSuccess?.(h),h}catch(t){let c=t instanceof Error?t:new Error("Key generation failed");return r(c.message),a.onMintError?.(c),{success:false,error:c.message}}finally{u(false);}},[e.apiBaseUrl,a]),minting:i,result:f,error:g}}function ge(){let{config:e,callbacks:a}=m(),[i,u]=react.useState(false),[f,d]=react.useState(null),[g,r]=react.useState(null),o=react.useRef(true),l=react.useCallback(async(n,t)=>{try{u(!0),r(null);let c=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({askPriceCents:t,stackId:e.stackId,stackName:e.stackName})});if(!c.ok)throw new Error(await y(c,`Listing failed (${c.status})`));let p=await c.json();return o.current&&(d(p),a.onListingCreated?.(p)),p}catch(c){let p=c instanceof Error?c.message:"Listing failed";return o.current&&r(p),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,e.stackName,a]),s=react.useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"DELETE",headers:{...k()},credentials:"include"});if(!t.ok)throw new Error(await y(t,`Delist failed (${t.status})`));return o.current&&d(null),!0}catch(t){let c=t instanceof Error?t.message:"Delist failed";return o.current&&r(c),false}finally{o.current&&u(false);}},[e.apiBaseUrl]);return {listKey:l,delistKey:s,listing:i,result:f,error:g}}function pe(){let{config:e}=m(),[a,i]=react.useState(false),[u,f]=react.useState(null),d=react.useRef(true);return {createSession:react.useCallback(async(r,o)=>{try{i(!0),f(null);let l=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({priceCents:r,quantity:o,stackId:e.stackId,referrerUrl:window.location.href})});if(!l.ok)throw new Error(await y(l,`Checkout failed (${l.status})`));let{url:s}=await l.json();if(!s)throw new Error("No checkout URL returned");let n;try{n=new URL(s);}catch{throw new Error("Invalid checkout URL")}if(n.protocol!=="https:"||!/(^|\.)stripe\.com$/.test(n.hostname))throw new Error("Refusing to redirect to non-Stripe URL");try{sessionStorage.setItem("keyutils_stripe_pending","1"),sessionStorage.setItem("keyutils_stripe_quantity",String(o));}catch{}window.location.href=n.toString();}catch(l){if(d.current){let s=l instanceof Error?l.message:"Checkout failed";f(s),i(false);}}},[e.apiBaseUrl,e.stackId]),loading:a,error:u}}function H(e,a="#"){if(!e||typeof e!="string")return a;let i=e.trim();if(i===""||i==="#")return a;if(i.startsWith("/")||i.startsWith("./")||i.startsWith("../"))return i;try{let u=new URL(i);if(u.protocol==="http:"||u.protocol==="https:")return u.toString()}catch{}return a}var v=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function he(){let{config:e}=m(),[a,i]=react.useState(false),[u,f]=react.useState(null);return {pay:react.useCallback(async g=>{if(!e.merchantWallet||!v.test(e.merchantWallet))throw new Error("Merchant wallet not configured");try{i(!0),f(null);let{Connection:r,PublicKey:o,Transaction:l,SystemProgram:s}=await import('@solana/web3.js'),n=typeof window<"u"?window.solana:void 0;if(!n||typeof n!="object"||!n.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let t=n,c=new o(e.merchantWallet),p=await t.connect(),h=new o(p.publicKey.toString()),L="https://api.mainnet-beta.solana.com",T=H(e.solanaRpcUrl,L),j=T==="#"?L:T,D=new r(j),{blockhash:W}=await D.getLatestBlockhash(),R=BigInt(Math.floor(g*1e9)),P=e.protocolTreasuryWallet,B=e.protocolFeeBps??500,b=new l({recentBlockhash:W,feePayer:h});if(P&&v.test(P)&&B>0){let M=R*BigInt(B)/10000n,q=R-M,z=new o(P);b.add(s.transfer({fromPubkey:h,toPubkey:c,lamports:Number(q)}),s.transfer({fromPubkey:h,toPubkey:z,lamports:Number(M)}));}else b.add(s.transfer({fromPubkey:h,toPubkey:c,lamports:Number(R)}));let{signature:J}=await t.signAndSendTransaction(b);return J}catch(r){let o=r instanceof Error?r:new Error("SOL payment failed");throw f(o.message),o}finally{i(false);}},[e.merchantWallet,e.protocolTreasuryWallet,e.protocolFeeBps,e.solanaRpcUrl]),processing:a,error:u}}function be(){let{config:e,callbacks:a}=m(),[i,u]=react.useState(false),[f,d]=react.useState(null),[g,r]=react.useState(null),o=react.useRef(true);return {transferKey:react.useCallback(async(s,n)=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(s)}/transfer`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({recipientId:n})});if(!t.ok)throw new Error(await y(t,`Transfer failed (${t.status})`));let c=await t.json();return o.current&&(d(c),a.onTransferComplete?.(c)),c}catch(t){let c=t instanceof Error?t.message:"Transfer failed";return o.current&&r(c),null}finally{o.current&&u(false);}},[e.apiBaseUrl,a]),transferring:i,result:f,error:g}}function Ee(){let{config:e,callbacks:a}=m(),[i,u]=react.useState(false),[f,d]=react.useState(null),[g,r]=react.useState(null),o=react.useRef(true),l=react.useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/file`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Filing failed (${t.status})`));let c=await t.json();return o.current&&(d(c),a.onFilingComplete?.(c)),c}catch(t){let c=t instanceof Error?t:new Error("Filing failed");return o.current&&r(c.message),a.onFilingError?.(c),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,a]),s=react.useCallback(()=>{d(null),r(null);},[]);return {filePaperwork:l,filing:i,result:f,error:g,reset:s}}function Ie(){let{config:e}=m(),[a,i]=react.useState([]),[u,f]=react.useState(true),[d,g]=react.useState(null),r=react.useRef(true),o=e.apiBaseUrl,l=react.useCallback(async()=>{try{f(!0),g(null);let s=await fetch(`${o}/api/keys/filings`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Failed to fetch filings (${s.status})`));let n=await s.json(),t=Array.isArray(n)?n:n.filings??[];r.current&&i(t);}catch(s){r.current&&g(s instanceof Error?s.message:"Failed to fetch filings");}finally{r.current&&f(false);}},[o]);return react.useEffect(()=>(r.current=true,l(),()=>{r.current=false;}),[l]),{entries:a,loading:u,error:d,refresh:l}}
2
+ exports.useFilePaperwork=Ee;exports.useFilingHistory=Ie;exports.useKeyLedger=le;exports.useKeys=se;exports.useListKey=ge;exports.useMintKey=fe;exports.usePricing=Q;exports.useSolanaPayment=he;exports.useStripeCheckout=pe;exports.useTransferKey=be;
@@ -1,2 +1,2 @@
1
- import {createContext,useState,useRef,useEffect,useCallback,useContext}from'react';import'react/jsx-runtime';var z=createContext(null);function d(){let e=useContext(z);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function Y(e,a){if(typeof e!="string"||e.length===0)return a;let i=e.replace(/[\u0000-\u001F\u007F]/g," ");return i.length>500?i.slice(0,500)+"\u2026":i}async function y(e,a){try{let i=await e.json();if(i&&typeof i=="object"&&"error"in i)return Y(i.error,a)}catch{}return a}function G(){let{config:e}=d(),[a,i]=useState(null),[u,f]=useState(true),[m,p]=useState(null),r=useRef(true),o=useRef(e.apiBaseUrl);o.current=e.apiBaseUrl;let c=async()=>{try{r.current&&(f(!0),p(null));let s=await fetch(`${o.current}/api/keys/pricing`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Pricing unavailable (${s.status})`));let n=await s.json();r.current&&i(n);}catch(s){r.current&&p(s instanceof Error?s.message:"Failed to fetch pricing");}finally{r.current&&f(false);}};return useEffect(()=>{r.current=true,c();let s=setInterval(c,6e4);return ()=>{r.current=false,clearInterval(s);}},[]),{pricing:a,loading:u,error:m,refresh:c}}function re(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function ne(){let{config:e}=d(),[a,i]=useState([]),[u,f]=useState(true),[m,p]=useState(null),r=useRef(true),o=e.apiBaseUrl,c=useCallback(async()=>{try{f(!0),p(null);let n=await fetch(`${o}/api/keys`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch keys (${n.status})`));let t=await n.json(),l=Array.isArray(t)?t:t.keys??[];r.current&&i(l.map(re));}catch(n){r.current&&p(n instanceof Error?n.message:"Failed to fetch keys");}finally{r.current&&f(false);}},[o]);useEffect(()=>(r.current=true,c(),()=>{r.current=false;}),[c]);let s=a.reduce((n,t)=>n+t.tokenBalance,0);return {keys:a,totalBalance:s,loading:u,error:m,refresh:c}}function ae(e){let{config:a}=d(),[i,u]=useState([]),[f,m]=useState(false),[p,r]=useState(null),o=useRef(true),c=a.apiBaseUrl,s=useCallback(async()=>{if(e)try{m(!0),r(null);let n=await fetch(`${c}/api/keys/${encodeURIComponent(e)}/ledger`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch ledger (${n.status})`));let t=await n.json();o.current&&u(Array.isArray(t)?t:t.entries??[]);}catch(n){o.current&&r(n instanceof Error?n.message:"Failed to fetch ledger");}finally{o.current&&m(false);}},[c,e]);return useEffect(()=>(o.current=true,s(),()=>{o.current=false;}),[s]),{entries:i,loading:f,error:p,refresh:s}}function k(){if(typeof document>"u")return {};let e=document.cookie.match(/(?:^|;\s*)__csrf=([^;]*)/);return e?{"x-csrf-token":e[1]}:{}}function ce(){let{config:e,callbacks:a}=d(),[i,u]=useState(false),[f,m]=useState(null),[p,r]=useState(null);return {mint:useCallback(async(c,s,n=1)=>{try{u(!0),r(null),a.onPaymentComplete?.(c,s);let t=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({paymentMethod:c,paymentRef:s,quantity:n,stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Key generation failed (${t.status})`));let l=await t.json(),g=l.keys?.[0]||l,h={success:!0,key:{id:g.keyId||g.id||"",key:g.key||"",userId:g.userId||"",status:"active",tokenBalance:g.tokenBalance??g.currentTokenBalance??0,maxTokens:g.initialTokenBalance??g.tokenBalance??0,createdAt:String(g.createdAt||Date.now())},transactionId:s};return m(h),a.onMintSuccess?.(h),h}catch(t){let l=t instanceof Error?t:new Error("Key generation failed");return r(l.message),a.onMintError?.(l),{success:false,error:l.message}}finally{u(false);}},[e.apiBaseUrl,a]),minting:i,result:f,error:p}}function fe(){let{config:e,callbacks:a}=d(),[i,u]=useState(false),[f,m]=useState(null),[p,r]=useState(null),o=useRef(true),c=useCallback(async(n,t)=>{try{u(!0),r(null);let l=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({askPriceCents:t,stackId:e.stackId,stackName:e.stackName})});if(!l.ok)throw new Error(await y(l,`Listing failed (${l.status})`));let g=await l.json();return o.current&&(m(g),a.onListingCreated?.(g)),g}catch(l){let g=l instanceof Error?l.message:"Listing failed";return o.current&&r(g),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,e.stackName,a]),s=useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"DELETE",headers:{...k()},credentials:"include"});if(!t.ok)throw new Error(await y(t,`Delist failed (${t.status})`));return o.current&&m(null),!0}catch(t){let l=t instanceof Error?t.message:"Delist failed";return o.current&&r(l),false}finally{o.current&&u(false);}},[e.apiBaseUrl]);return {listKey:c,delistKey:s,listing:i,result:f,error:p}}function de(){let{config:e}=d(),[a,i]=useState(false),[u,f]=useState(null),m=useRef(true);return {createSession:useCallback(async(r,o)=>{try{i(!0),f(null);let c=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({priceCents:r,quantity:o,stackId:e.stackId,referrerUrl:window.location.href})});if(!c.ok)throw new Error(await y(c,`Checkout failed (${c.status})`));let{url:s}=await c.json();if(!s)throw new Error("No checkout URL returned");let n;try{n=new URL(s);}catch{throw new Error("Invalid checkout URL")}if(n.protocol!=="https:"||!/(^|\.)stripe\.com$/.test(n.hostname))throw new Error("Refusing to redirect to non-Stripe URL");try{sessionStorage.setItem("keyutils_stripe_pending","1"),sessionStorage.setItem("keyutils_stripe_quantity",String(o));}catch{}window.location.href=n.toString();}catch(c){if(m.current){let s=c instanceof Error?c.message:"Checkout failed";f(s),i(false);}}},[e.apiBaseUrl,e.stackId]),loading:a,error:u}}function _(e,a="#"){if(!e||typeof e!="string")return a;let i=e.trim();if(i===""||i==="#")return a;if(i.startsWith("/")||i.startsWith("./")||i.startsWith("../"))return i;try{let u=new URL(i);if(u.protocol==="http:"||u.protocol==="https:")return u.toString()}catch{}return a}var A=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function ge(){let{config:e}=d(),[a,i]=useState(false),[u,f]=useState(null);return {pay:useCallback(async p=>{if(!e.merchantWallet||!A.test(e.merchantWallet))throw new Error("Merchant wallet not configured");try{i(!0),f(null);let{Connection:r,PublicKey:o,Transaction:c,SystemProgram:s}=await import('@solana/web3.js'),n=typeof window<"u"?window.solana:void 0;if(!n||typeof n!="object"||!n.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let t=n,l=new o(e.merchantWallet),g=await t.connect(),h=new o(g.publicKey.toString()),B="https://api.mainnet-beta.solana.com",I=_(e.solanaRpcUrl,B),H=I==="#"?B:I,O=new r(H),{blockhash:W}=await O.getLatestBlockhash(),R=BigInt(Math.floor(p*1e9)),U=e.protocolTreasuryWallet,T=e.protocolFeeBps??500,w=new c({recentBlockhash:W,feePayer:h});if(U&&A.test(U)&&T>0){let F=R*BigInt(T)/10000n,J=R-F,V=new o(U);w.add(s.transfer({fromPubkey:h,toPubkey:l,lamports:Number(J)}),s.transfer({fromPubkey:h,toPubkey:V,lamports:Number(F)}));}else w.add(s.transfer({fromPubkey:h,toPubkey:l,lamports:Number(R)}));let{signature:D}=await t.signAndSendTransaction(w);return D}catch(r){let o=r instanceof Error?r:new Error("SOL payment failed");throw f(o.message),o}finally{i(false);}},[e.merchantWallet,e.protocolTreasuryWallet,e.protocolFeeBps,e.solanaRpcUrl]),processing:a,error:u}}function Re(){let{config:e,callbacks:a}=d(),[i,u]=useState(false),[f,m]=useState(null),[p,r]=useState(null),o=useRef(true);return {transferKey:useCallback(async(s,n)=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(s)}/transfer`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({recipientId:n})});if(!t.ok)throw new Error(await y(t,`Transfer failed (${t.status})`));let l=await t.json();return o.current&&(m(l),a.onTransferComplete?.(l)),l}catch(t){let l=t instanceof Error?t.message:"Transfer failed";return o.current&&r(l),null}finally{o.current&&u(false);}},[e.apiBaseUrl,a]),transferring:i,result:f,error:p}}function we(){let{config:e,callbacks:a}=d(),[i,u]=useState(false),[f,m]=useState(null),[p,r]=useState(null),o=useRef(true),c=useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/file`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Filing failed (${t.status})`));let l=await t.json();return o.current&&(m(l),a.onFilingComplete?.(l)),l}catch(t){let l=t instanceof Error?t:new Error("Filing failed");return o.current&&r(l.message),a.onFilingError?.(l),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,a]),s=useCallback(()=>{m(null),r(null);},[]);return {filePaperwork:c,filing:i,result:f,error:p,reset:s}}function Ke(){let{config:e}=d(),[a,i]=useState([]),[u,f]=useState(true),[m,p]=useState(null),r=useRef(true),o=e.apiBaseUrl,c=useCallback(async()=>{try{f(!0),p(null);let s=await fetch(`${o}/api/keys/filings`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Failed to fetch filings (${s.status})`));let n=await s.json(),t=Array.isArray(n)?n:n.filings??[];r.current&&i(t);}catch(s){r.current&&p(s instanceof Error?s.message:"Failed to fetch filings");}finally{r.current&&f(false);}},[o]);return useEffect(()=>(r.current=true,c(),()=>{r.current=false;}),[c]),{entries:a,loading:u,error:m,refresh:c}}
2
- export{we as useFilePaperwork,Ke as useFilingHistory,ae as useKeyLedger,ne as useKeys,fe as useListKey,ce as useMintKey,G as usePricing,ge as useSolanaPayment,de as useStripeCheckout,Re as useTransferKey};
1
+ import {createContext,useState,useRef,useEffect,useCallback,useContext}from'react';import'react/jsx-runtime';var Y=createContext(null);function m(){let e=useContext(Y);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function Z(e,a){if(typeof e!="string"||e.length===0)return a;let i=e.replace(/[\u0000-\u001F\u007F]/g," ");return i.length>500?i.slice(0,500)+"\u2026":i}async function y(e,a){try{let i=await e.json();if(i&&typeof i=="object"&&"error"in i)return Z(i.error,a)}catch{}return a}function Q(){let{config:e}=m(),[a,i]=useState(null),[u,f]=useState(true),[d,g]=useState(null),r=useRef(true),o=useRef(e.apiBaseUrl);o.current=e.apiBaseUrl;let l=async()=>{try{r.current&&(f(!0),g(null));let s=await fetch(`${o.current}/api/keys/pricing`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Pricing unavailable (${s.status})`));let n=await s.json();r.current&&i(n);}catch(s){r.current&&g(s instanceof Error?s.message:"Failed to fetch pricing");}finally{r.current&&f(false);}};return useEffect(()=>{r.current=true,l();let s=setInterval(l,6e4);return ()=>{r.current=false,clearInterval(s);}},[]),{pricing:a,loading:u,error:d,refresh:l}}function ne(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function se(){let{config:e}=m(),[a,i]=useState([]),[u,f]=useState(true),[d,g]=useState(null),r=useRef(true),o=e.apiBaseUrl,l=useCallback(async()=>{try{f(!0),g(null);let n=await fetch(`${o}/api/keys`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch keys (${n.status})`));let t=await n.json(),c=Array.isArray(t)?t:t.keys??[];r.current&&i(c.map(ne));}catch(n){r.current&&g(n instanceof Error?n.message:"Failed to fetch keys");}finally{r.current&&f(false);}},[o]);useEffect(()=>(r.current=true,l(),()=>{r.current=false;}),[l]);let s=a.reduce((n,t)=>n+t.tokenBalance,0);return {keys:a,totalBalance:s,loading:u,error:d,refresh:l}}function N(e){let a=e.type||e.entry_type||"debit",i=e.amount??e.tokens??e.token_amount??0,u=e.description||e.memo||e.reason||ie(a);return {id:e.id||"",keyId:e.keyId||e.key_id||"",type:a,amount:i,description:u,createdAt:String(e.createdAt??e.created_at??e.timestamp??""),metadata:e.metadata||void 0}}function ie(e){switch(e){case "credit":return "Credit";case "debit":return "Usage";case "mint":return "Mint";case "reward":return "Reward";default:return ""}}function le(e){let{config:a}=m(),[i,u]=useState([]),[f,d]=useState(false),[g,r]=useState(null),o=useRef(true),l=a.apiBaseUrl,s=useCallback(async()=>{if(e)try{d(!0),r(null);let n=await fetch(`${l}/api/keys/${encodeURIComponent(e)}/ledger`,{credentials:"include"});if(!n.ok)throw new Error(await y(n,`Failed to fetch ledger (${n.status})`));let t=await n.json(),c=Array.isArray(t)?t:t.entries??[];o.current&&u(c.map(N));}catch(n){o.current&&r(n instanceof Error?n.message:"Failed to fetch ledger");}finally{o.current&&d(false);}},[l,e]);return useEffect(()=>(o.current=true,s(),()=>{o.current=false;}),[s]),{entries:i,loading:f,error:g,refresh:s}}function k(){if(typeof document>"u")return {};let e=document.cookie.match(/(?:^|;\s*)__csrf=([^;]*)/);return e?{"x-csrf-token":e[1]}:{}}function fe(){let{config:e,callbacks:a}=m(),[i,u]=useState(false),[f,d]=useState(null),[g,r]=useState(null);return {mint:useCallback(async(l,s,n=1)=>{try{u(!0),r(null),a.onPaymentComplete?.(l,s);let t=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({paymentMethod:l,paymentRef:s,quantity:n,stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Key generation failed (${t.status})`));let c=await t.json(),p=c.keys?.[0]||c,h={success:!0,key:{id:p.keyId||p.id||"",key:p.key||"",userId:p.userId||"",status:"active",tokenBalance:p.tokenBalance??p.currentTokenBalance??0,maxTokens:p.initialTokenBalance??p.tokenBalance??0,createdAt:String(p.createdAt||Date.now())},transactionId:s};return d(h),a.onMintSuccess?.(h),h}catch(t){let c=t instanceof Error?t:new Error("Key generation failed");return r(c.message),a.onMintError?.(c),{success:false,error:c.message}}finally{u(false);}},[e.apiBaseUrl,a]),minting:i,result:f,error:g}}function ge(){let{config:e,callbacks:a}=m(),[i,u]=useState(false),[f,d]=useState(null),[g,r]=useState(null),o=useRef(true),l=useCallback(async(n,t)=>{try{u(!0),r(null);let c=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({askPriceCents:t,stackId:e.stackId,stackName:e.stackName})});if(!c.ok)throw new Error(await y(c,`Listing failed (${c.status})`));let p=await c.json();return o.current&&(d(p),a.onListingCreated?.(p)),p}catch(c){let p=c instanceof Error?c.message:"Listing failed";return o.current&&r(p),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,e.stackName,a]),s=useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/list`,{method:"DELETE",headers:{...k()},credentials:"include"});if(!t.ok)throw new Error(await y(t,`Delist failed (${t.status})`));return o.current&&d(null),!0}catch(t){let c=t instanceof Error?t.message:"Delist failed";return o.current&&r(c),false}finally{o.current&&u(false);}},[e.apiBaseUrl]);return {listKey:l,delistKey:s,listing:i,result:f,error:g}}function pe(){let{config:e}=m(),[a,i]=useState(false),[u,f]=useState(null),d=useRef(true);return {createSession:useCallback(async(r,o)=>{try{i(!0),f(null);let l=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({priceCents:r,quantity:o,stackId:e.stackId,referrerUrl:window.location.href})});if(!l.ok)throw new Error(await y(l,`Checkout failed (${l.status})`));let{url:s}=await l.json();if(!s)throw new Error("No checkout URL returned");let n;try{n=new URL(s);}catch{throw new Error("Invalid checkout URL")}if(n.protocol!=="https:"||!/(^|\.)stripe\.com$/.test(n.hostname))throw new Error("Refusing to redirect to non-Stripe URL");try{sessionStorage.setItem("keyutils_stripe_pending","1"),sessionStorage.setItem("keyutils_stripe_quantity",String(o));}catch{}window.location.href=n.toString();}catch(l){if(d.current){let s=l instanceof Error?l.message:"Checkout failed";f(s),i(false);}}},[e.apiBaseUrl,e.stackId]),loading:a,error:u}}function H(e,a="#"){if(!e||typeof e!="string")return a;let i=e.trim();if(i===""||i==="#")return a;if(i.startsWith("/")||i.startsWith("./")||i.startsWith("../"))return i;try{let u=new URL(i);if(u.protocol==="http:"||u.protocol==="https:")return u.toString()}catch{}return a}var v=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function he(){let{config:e}=m(),[a,i]=useState(false),[u,f]=useState(null);return {pay:useCallback(async g=>{if(!e.merchantWallet||!v.test(e.merchantWallet))throw new Error("Merchant wallet not configured");try{i(!0),f(null);let{Connection:r,PublicKey:o,Transaction:l,SystemProgram:s}=await import('@solana/web3.js'),n=typeof window<"u"?window.solana:void 0;if(!n||typeof n!="object"||!n.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let t=n,c=new o(e.merchantWallet),p=await t.connect(),h=new o(p.publicKey.toString()),L="https://api.mainnet-beta.solana.com",T=H(e.solanaRpcUrl,L),j=T==="#"?L:T,D=new r(j),{blockhash:W}=await D.getLatestBlockhash(),R=BigInt(Math.floor(g*1e9)),P=e.protocolTreasuryWallet,B=e.protocolFeeBps??500,b=new l({recentBlockhash:W,feePayer:h});if(P&&v.test(P)&&B>0){let M=R*BigInt(B)/10000n,q=R-M,z=new o(P);b.add(s.transfer({fromPubkey:h,toPubkey:c,lamports:Number(q)}),s.transfer({fromPubkey:h,toPubkey:z,lamports:Number(M)}));}else b.add(s.transfer({fromPubkey:h,toPubkey:c,lamports:Number(R)}));let{signature:J}=await t.signAndSendTransaction(b);return J}catch(r){let o=r instanceof Error?r:new Error("SOL payment failed");throw f(o.message),o}finally{i(false);}},[e.merchantWallet,e.protocolTreasuryWallet,e.protocolFeeBps,e.solanaRpcUrl]),processing:a,error:u}}function be(){let{config:e,callbacks:a}=m(),[i,u]=useState(false),[f,d]=useState(null),[g,r]=useState(null),o=useRef(true);return {transferKey:useCallback(async(s,n)=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(s)}/transfer`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({recipientId:n})});if(!t.ok)throw new Error(await y(t,`Transfer failed (${t.status})`));let c=await t.json();return o.current&&(d(c),a.onTransferComplete?.(c)),c}catch(t){let c=t instanceof Error?t.message:"Transfer failed";return o.current&&r(c),null}finally{o.current&&u(false);}},[e.apiBaseUrl,a]),transferring:i,result:f,error:g}}function Ee(){let{config:e,callbacks:a}=m(),[i,u]=useState(false),[f,d]=useState(null),[g,r]=useState(null),o=useRef(true),l=useCallback(async n=>{try{u(!0),r(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${encodeURIComponent(n)}/file`,{method:"POST",headers:{"Content-Type":"application/json",...k()},credentials:"include",body:JSON.stringify({stackId:e.stackId})});if(!t.ok)throw new Error(await y(t,`Filing failed (${t.status})`));let c=await t.json();return o.current&&(d(c),a.onFilingComplete?.(c)),c}catch(t){let c=t instanceof Error?t:new Error("Filing failed");return o.current&&r(c.message),a.onFilingError?.(c),null}finally{o.current&&u(false);}},[e.apiBaseUrl,e.stackId,a]),s=useCallback(()=>{d(null),r(null);},[]);return {filePaperwork:l,filing:i,result:f,error:g,reset:s}}function Ie(){let{config:e}=m(),[a,i]=useState([]),[u,f]=useState(true),[d,g]=useState(null),r=useRef(true),o=e.apiBaseUrl,l=useCallback(async()=>{try{f(!0),g(null);let s=await fetch(`${o}/api/keys/filings`,{credentials:"include"});if(!s.ok)throw new Error(await y(s,`Failed to fetch filings (${s.status})`));let n=await s.json(),t=Array.isArray(n)?n:n.filings??[];r.current&&i(t);}catch(s){r.current&&g(s instanceof Error?s.message:"Failed to fetch filings");}finally{r.current&&f(false);}},[o]);return useEffect(()=>(r.current=true,l(),()=>{r.current=false;}),[l]),{entries:a,loading:u,error:d,refresh:l}}
2
+ export{Ee as useFilePaperwork,Ie as useFilingHistory,le as useKeyLedger,se as useKeys,ge as useListKey,fe as useMintKey,Q as usePricing,he as useSolanaPayment,pe as useStripeCheckout,be as useTransferKey};