1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./DmmBUNbX.js","./DmE-NGqm.js","./DYuROC2c.js"])))=>i.map(i=>d[i]); 2var Sr=Object.defineProperty;var Es=i=>{throw TypeError(i)};var Ir=(i,t,e)=>t in i?Sr(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var G=(i,t,e)=>Ir(i,typeof t!="symbol"?t+"":t,e),Xe=(i,t,e)=>t.has(i)||Es("Cannot "+e);var w=(i,t,e)=>(Xe(i,t,"read from private field"),e?e.call(i):t.get(i)),L=(i,t,e)=>t.has(i)?Es("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),D=(i,t,e,s)=>(Xe(i,t,"write to private field"),s?s.call(i,e):t.set(i,e),e),y=(i,t,e)=>(Xe(i,t,"access private method"),e);import{b as ht,g as dt,d as gt}from"./CN4tyA6q.js";import{_ as Ke}from"./C1FmrZbK.js";import{b as Ar}from"./8mUhvwNQ.js";const ae=100000000n,Ve=8;function H(i){const t=i.trim();if(!/^-?\d+(\.\d+)?$/.test(t))throw new Error(`not a valid amount: ${JSON.stringify(i)}`);const e=t.startsWith("-"),s=e?t.slice(1):t,[r="0",n=""]=s.split("."),a=(n+"0".repeat(Ve)).slice(0,Ve),o=BigInt(r)*ae+BigInt(a);return e?-o:o}function z(i){const t=i<0n,e=t?-i:i,s=e/ae,r=e%ae;return`${t?"-":""}${s}.${r.toString().padStart(Ve,"0")}`}function ai(i,t){const e=H(i),s=H(t);return e<s?-1:e>s?1:0}function oi(i){return H(i)===0n}function ci(i){return H(i)>0n}function xe(i,t={}){const{decimals:e=3,group:s=!0,locale:r="en-US"}=t,n=H(i),a=n<0n,o=a?-n:n,c=(o/ae).toString(),u=(o%ae).toString().padStart(Ve,"0").slice(0,e),l=s?Number(c).toLocaleString(r,{maximumFractionDigits:0}):c;return`${a?"-":""}${l}${e>0?"."+u:""}`}function Y(i){const t=H(i);if(t<0n)throw new Error("amount cannot be negative");return t.toString()}const ui={Viral:0,Deep:1},xr={swap_lc_hbd:"swap_lassecash_hbd",swap_hbd_lc:"swap_hbd_lassecash"};function Cr(i){return xr[i]??i}const li={Split:0,PowerUp:1,Burn:2},O={Transfer:"transfer",Burn:"burn",Fund:"fund",Settle:"settle",Mint:"mint",ClaimMint:"claim_mint",GoodAccounting:"good_accounting",SetDuration:"set_duration",SettlePending:"settle_pending",Promote:"promote",SetParam:"set_param",Post:"post",PromotePost:"promote_post",Vote:"vote",Payout:"payout",ClaimCuration:"claim_curation",AddLiquidity:"add_liquidity",RemoveLiquidity:"remove_liquidity",ClaimPool:"claim_pool",SwapLassecashHbd:"swap_lassecash_hbd",SwapHbdLassecash:"swap_hbd_lassecash",ClaimMigration:"claim_migration",RecordBurn:"record_burn"},hi={VolumeStart:"mint.volume_start",VolumeEnd:"mint.volume_end"},us=2,te=5;function di(i){return i<=0?0:Math.ceil(i/te)}class x extends Error{constructor(t,e,s){super(t),this.status=e,this.body=s,this.name="BackendError"}}const Nt={HBD:1000n,HIVE:1000n,BTC:100000000n},Vs=[{contractId:"vsc1BVb95YKRHAEy24XgRSaW4L6d9vB88AdwjM",router:"vsc1Brvi4YZHLkocYNAFd7Gf1JpsPjzNnv4i45",asset0:"BTC",asset1:"HBD",feeBps:8},{contractId:"vsc1BoaniA5HW56GuQy6pVdoZfMcVaaDfnC8kp",router:"vsc1Brvi4YZHLkocYNAFd7Gf1JpsPjzNnv4i45",asset0:"HBD",asset1:"HIVE",feeBps:8}],$s={BTC:"vsc1BdrQ6EtbQ64rq2PkPd21x4MaLnVRcJj85d"};function Tr(i,t){return Vs.find(e=>e.asset0===i&&e.asset1===t||e.asset0===t&&e.asset1===i)??null}function gi(i){const t=[];for(const e of Vs)e.asset0===i?t.push(e.asset1):e.asset1===i&&t.push(e.asset0);return t}function Pr(i,t,e,s,r){if(i<=0n||t<=0n||e<=0n)return null;const n=e*BigInt(1e4-s)/10000n;if(n<=0n)return null;const a=n*t/(i+n);if(a<=0n)return null;const o=n*t/i,c=o>0n?Number(o-a)/Number(o):0;return{amountInUnits:e,amountOutUnits:a,amountOut:ws(a,r),priceImpact:c,feeBps:s}}function ws(i,t){const e=i<0n,s=e?-i:i,r=s/t,n=(s%t).toString().padStart(String(t).length-1,"0");return`${e?"-":""}${r}.${n}`}function Ze(i,t){const e=String(t).length-1,[s="0",r=""]=i.trim().split("."),n=(r+"0".repeat(e)).slice(0,e);return BigInt(s||"0")*t+BigInt(n||"0")}function Ls(i){return i.toString()}function Er(i,t){const e=Nt[i]??1000n;return{type:"transfer.allow",args:{token:i.toLowerCase(),limit:ws(t,e)}}}function $r(i){return JSON.stringify({type:"swap",version:"1.0.0",asset_in:i.assetIn,asset_out:i.assetOut,amount_in:Ls(i.amountInUnits),min_amount_out:Ls(i.minOutUnits),recipient:i.recipient})}function ts(i){const t=i.trim();return t&&(t.includes(":")?t:`hive:${t}`)}const Lr="vsc1BdrQ6EtbQ64rq2PkPd21x4MaLnVRcJj85d",Rr="a-",Rs=546n,ut=["https://api.vsc.eco/api/v1/graphql","https://api.okinoko.io/api/v1/graphql","https://vsc.techcoderx.com/api/v1/graphql"],Mr=6e3,Gs=/rate limit exceeded/i,Ws="lc_magi_n
2ode";let ie=(()=>{var i;try{const t=ut.indexOf(((i=globalThis.localStorage)==null?void 0:i.getItem(Ws))??"");return t<0?0:t}catch{return 0}})();function ls(i){var t;ie=i;try{(t=globalThis.localStorage)==null||t.setItem(Ws,ut[i])}catch{}}function Or(i){return i&&!ut.includes(i)?i:ut[ie]}async function Hr(i={}){const t=i.fetch??globalThis.fetch.bind(globalThis);if(i.url!==void 0&&!ut.includes(i.url))return i.url;const e=JSON.stringify({query:"{localNodeInfo{last_processed_block}}"}),s=async a=>{const o=new AbortController,c=setTimeout(()=>o.abort(),qr);try{const u=await t(a,{method:"POST",headers:{"Content-Type":"application/json"},body:e,signal:o.signal});if(!u.ok)throw new Error(`HTTP ${u.status}`);if(Gs.test(await u.text()))throw new Error("rate limited")}finally{clearTimeout(c)}},n=(await Promise.all(ut.map(async(a,o)=>{try{await s(a);const c=Date.now();return await s(a),{i:o,ms:Date.now()-c}}catch{return null}}))).filter(a=>a!==null).sort((a,o)=>a.ms-o.ms)[0];return n&&ls(n.i),Or()}const qr=3e3;class Nr extends Error{constructor(t,e){super(t,{cause:e}),this.name="MagiUnreachableError"}}async function Me(i,t={}){const e=t.fetch??globalThis.fetch.bind(globalThis),s=t.timeoutMs??15e3,r=t.url!==void 0&&!ut.includes(t.url),n=r?[t.url]:ut.map((c,u)=>(ie+u)%ut.length),a=[];let o;for(let c=0;c<n.length;c++){const u=r?n[c]:ut[n[c]],l=c===n.length-1,h=new AbortController,d=l?s:Math.min(s,Mr),g=setTimeout(()=>h.abort(),d);try{const f=await e(u,{method:"POST",headers:{"Content-Type":"application/json"},body:i,signal:h.signal});if(f.status>=500&&!l){o=new Error(`HTTP ${f.status}`),a.push(`${u} (HTTP ${f.status})`);continue}const m=await f.text();if(Gs.test(m)&&!l){o=new Error("rate limited"),a.push(`${u} (rate limited)`);continue}return!r&&n[c]!==ie&&ls(n[c]),new Response(m,{status:f.status,headers:f.headers})}catch(f){o=f;const m=f,p=(m==null?void 0:m.name)==="AbortError"?`no answer within ${d/1e3}s`:m!=null&&m.message?`${m.name??"error"}: ${m.message}`:"no response";a.push(`${u} (${p})`)}finally{clearTimeout(g)}}throw r||ls((ie+1)%ut.length),new Nr(`MAGI node unreachable â tried ${a.join("; ")}`,o)}let oe,Zt;async function Ur(i,t){if(!oe){if(Zt)return Zt;Zt=(async()=>{const e=globalThis;if(!e.Go)throw new Error("TinyGo's wasm_exec shim is not loaded. Import api/src/wasm/wasm_exec.cjs before calling loadEngine().");const s=new e.Go,r=i;let n;n=await WebAssembly.instantiateStreaming(fetch(r),s.importObject).catch(async()=>{const o=await fetch(r).then(c=>c.arrayBuffer());return WebAssembly.instantiate(o,s.importObject)}),s.run(n.instance);const a=globalThis.__lassecashEngine;if(!a)throw new Error("engine wasm loaded but exposed no bridge");oe=a})();try{await Zt}finally{Zt=void 0}}}function Br(){return oe!==void 0}function B(){if(!oe)throw new Error("engine not loaded â await loadEngine() first");return oe}function mt(){return B().constants}const S=i=>z(BigInt(i));function Dr(i,t,e,s,r){const n=B().mintQuote(i,t,e,s,r);return{ok:n.ok,shares:S(n.shares),durationMultiplier:S(n.durationMultiplier),volumeMultiplier:S(n.volumeMultiplier),combinedMultiplier:S(n.combinedMultiplier)}}function Fr(i,t,e){return S(B().entitlement(i,t,e))}function Js(i,t){return B().canPost(i,t)}function Kr(i,t){const e=B().effectiveValue(i,t);return{ok:e.ok,value:S(e.value),min:S(e.min),max:S(e.max),defaultValue:S(e.defaultValue)}}function Vr(i){return B().consensusGroup(i).map(t=>({account:t.account,shares:S(t.shares)}))}function Gr(i,t){return S(B().shareRate(String(i),String(t)))}function Wr(i,t,e,s){const r=B().shareRateHbd(String(i),String(t),e,s);return r===""?null:S(r)}function mi(i){const t=B().supplyLimits(i);return{hardcap:S(t.hardcap),emissionCap:S(t.emissionCap),maxEver:S(t.maxEver),lost:S(t.lost)}}function fi(i,t,e,s){const r=B().poolApy(Y(i),Y(t),Y(e),Y(s));return r.ok?S(r.apy):null}function pi(i,t){const e=B().dailyRewards(String(i),String(t));return{total:S(e.total),proofOfBrain:S(e.proofOfBrain),lshare:S(e.lshare),liquidity:S(e.liquidity),viral:S(e.viral),deep:S(e.deep)}}function yi(i){return S(B().voteCost(i))}function wi(i,t){return S(B().voteWeight(i,t))}
2function Jr(i,t,e,s){return S(B().votePower(i,String(t),String(e),s))}function js(i){const t=B().trancheView(i.shares,String(i.startHeight),i.weight,i.accStart,String(i.height),i.totalShares,i.lcReserve,i.hbdReserve,i.poolLiq,i.accSeen,i.accHeld,i.acc,i.totalWeight);return{age_days:t.age_days,loyalty:S(t.loyalty),value_lc:S(t.value_lc),value_hbd:S(t.value_hbd),pending_reward:S(t.pending_reward)}}function _i(i,t){const e=B().trancheHealth(String(i),String(t));return{phase:e.phase,daysUntilEvict:e.daysUntilEvict,dormantDays:e.dormantDays}}function vi(i){const t=B().blockSplit(i);return{proofOfBrain:S(t.proofOfBrain),lshare:S(t.lshare),liquidity:S(t.liquidity),viral:S(t.viral),deep:S(t.deep)}}function zs(i,t,e){const s=B().swapOut(i,t,e);return{ok:s.ok,amountOut:S(s.amountOut),rate:s.rate?S(s.rate):"0.00000000",priceImpactPct:s.priceImpactPct?S(s.priceImpactPct):"0.00000000"}}function Ms(i,t,e){return S(B().rewardShare(i,t,e))}function jr(i,t,e){const s=B().lcToHbd(i,t,e);return s===""?null:S(s)}function Qs(i,t,e,s){const r=B().liquidityQuote(i,t,e,s);return{ok:r.ok,isFirstDeposit:r.isFirstDeposit,hbdNeeded:S(r.hbdNeeded),shares:S(r.shares)}}function zr(i,t,e,s){const r=B().withdrawQuote(i,t,e,s);return{ok:r.ok,lc:S(r.lc),hbd:S(r.hbd)}}function Qr(i,t,e){const s=B().mintPreview(H(i.principal).toString(),H(i.shares).toString(),String(i.start_height),i.days,i.good_accounting,String(t),e);return{toOwner:S(s.toOwner),toRewardPool:S(s.toRewardPool),early:s.early,mature:s.mature,canArmGoodAccounting:s.canArm,recoveryFraction:S(s.recoveryFraction),bleedRemaining:S(s.bleedRemaining),maturityHeight:Number(s.maturityHeight),liquidationHeight:Number(s.liquidationHeight)}}var ue,nt,Tt,le,C,Oe,He,qe,he,jt,Ys,Xs,de,Zs,Ut,hs,tr,ds,ge,er,Ne;class Yr{constructor(t){L(this,C);G(this,"name","magi");L(this,ue);L(this,nt);L(this,Tt);L(this,le);L(this,he,0);L(this,jt);L(this,de,new Map);L(this,ge,new Map);D(this,ue,t.url),D(this,nt,t.contractId),D(this,Tt,t.fetch??globalThis.fetch.bind(globalThis)),D(this,le,t.timeoutMs??15e3)}async query(t,e={}){var n;let s;try{s=await Me(JSON.stringify({query:t,variables:e}),{url:w(this,ue),fetch:w(this,Tt),timeoutMs:w(this,le)})}catch(a){throw new x(a.message,void 0,a)}const r=await s.json();if((n=r.errors)!=null&&n.length)throw new x(`MAGI GraphQL: ${r.errors.map(a=>a.message).join("; ")}`,s.status,r.errors);if(!r.data)throw new x("MAGI returned no data",s.status,r);return r.data}async state(t){if(t.length===0)return{};const e=100,s=[];for(let n=0;n<t.length;n+=e)s.push(t.slice(n,n+e));const r=await Promise.all(s.map(n=>this.query("query($id: String!, $keys: [String!]!) { getStateByKeys(contractId: $id, keys: $keys) }",{id:w(this,nt),keys:n})));return Object.assign({},...r.map(n=>n.getStateByKeys??{}))}async tokenBalance(t,e){var a;const s=e.includes(":")?e:"hive:"+e,n=(a=(await this.query(`query($i: SimulateContractCallsInput!) { 3 simulateContractCalls(input: $i) { success err_msg ret } 4 }`,{i:{tx_id:"balanceOf",required_auths:s,calls:[{contract_id:t,action:"balanceOf",payload:JSON.stringify({account:s}),rc_limit:1e4,intents:[]}]}})).simulateContractCalls)==null?void 0:a[0];if(!(n!=null&&n.success)||!n.ret)return"0";try{return JSON.parse(n.ret).balance??"0"}catch{return"0"}}async txStatus(t){var n,a,o,c;const s=(n=(await this.query("query($id: String!) { findTransaction(filterOptions: {byId: $id}) { status output { id } } }",{id:t})).findTransaction)==null?void 0:n[0];if(!s)return{status:"UNKNOWN"};if(s.status==="CONFIRMED")return{status:"CONFIRMED"};if(s.status!=="FAILED")return{status:"PENDING"};const r=(o=(a=s.output)==null?void 0:a[0])==null?void 0:o.id;if(!r)return{status:"FAILED"};try{const u=await this.query("query($c: String!) { getDagByCID(cidString: $c) }",{c:r}),h=(c=JSON.parse(u.getDagByCID).results)==null?void 0:c[0];return{status:"FAILED",error:(h==null?void 0:h.errMsg)||(h==null?void 0:h.err)||void 0}}catch{return{status:"FAILED"}}}async height(){return(await this.query("{ localNodeInfo { last_processed_block } }")).localNodeInfo.last_processed_block}async resourceCredits(t){const s=(await this.query("query($a: String!) { getAccountRC(account: $a) { amount max_rcs } }",{a:ot(t)})).getAccountRC;return!s||!s.max_rcs?null:{amount:s.amount,max:s.max_rcs}}async governance(t){const s=((await this.state(["gov_board"])).gov_board??"").split("|").filter(
4Boolean),r=s.flatMap(a=>["shr_"+a,...t.map(o=>`gov_${o}_${a}`)]),n=r.length?await this.state(r):{};return s.map(a=>{const o={};for(const c of t)o[c]=n[`gov_${c}_${a}`]||null;return{account:a,shares:n["shr_"+a]||"0",preferences:o}})}async chain(){const[t,e]=await Promise.all([this.state(["cfg_genesis","cfg_settled","sup_migrated","sup_emitted","cfg_migtotal","cfg_migburn","bal_hive:null","shares_total","pool_lshare","pool_viral","pool_deep","rsh_viral","rsh_deep","pool_liq","amm_lc","amm_hbd","amm_shares","amm_weight","gov_board","cfg_token"]),this.height()]),s=t.cfg_token?(BigInt(await this.tokenBalance(t.cfg_token,"hive:null"))+BigInt(t["bal_hive:null"]||"0")).toString():t["bal_hive:null"],r=(t.gov_board??"").split("|").filter(Boolean),n=r.length?await this.state(r.map(o=>"shr_"+o)):{},a=Vr(r.map(o=>({account:o,shares:n["shr_"+o]??"0"}))).map(o=>o.account);return{height:e,timestamp:new Date().toISOString(),epoch:0,genesis_height:W(t.cfg_genesis),token_contract:t.cfg_token??"",settled_height:W(t.cfg_settled),migrated_supply:M(t.sup_migrated),snapshot_total:M(String(BigInt(t.cfg_migtotal||"0")+BigInt(t.cfg_migburn||"0"))),snapshot_burned:M(t.cfg_migburn||"0"),total_emitted:M(t.sup_emitted),total_burned:M(s),total_shares:M(t.shares_total),pool_lshare:M(t.pool_lshare),pool_viral:M(t.pool_viral),pool_deep:M(t.pool_deep),rsh_viral:M(t.rsh_viral),rsh_deep:M(t.rsh_deep),pool_liquidity:M(t.pool_liq),amm_lc:M(t.amm_lc),amm_hbd:M(t.amm_hbd),amm_shares:M(t.amm_shares),amm_weight:M(t.amm_weight),consensus_group:a}}async account(t){var Is,As;const e=t.includes(":")?t:"hive:"+t,s=await this.state(["bal_"+e,"shr_"+e,"pend_"+e,"mseq_"+e,"cfg_token","set_"+e+"_days","acc_per","acc_day","cfg_genesis","gov_board","vp_"+e+"_0","vp_"+e+"_1","lpseq_"+e,"amm_lc","amm_hbd","amm_shares","pool_liq","amm_accseen","amm_accheld","amm_acc","amm_weight"]),r=await this.height(),n=s.cfg_token,a=n?(BigInt(await this.tokenBalance(n,e))+BigInt(s["bal_"+e]||"0")).toString():s["bal_"+e],o=W(s["mseq_"+e]),c=[];for(let q=1;q<=o;q++)c.push(`mint_${e}_${q}`);const u=W(s["lpseq_"+e]);for(let q=1;q<=u;q++)c.push(`lp_${e}_${q}`);const l=c.length?await this.state(c):{},h=W(s.cfg_genesis),d=Number(mt().heightsPerDay),g=s.acc_per||"0",f=W(s.acc_day),m=[],p=new Set,k=[];for(let q=1;q<=o;q++){const at=l[`mint_${e}_${q}`];if(!at)continue;const V=at.split("|");if(V.length<6)continue;k.push({id:q,f:V});const lt=Math.floor((W(V[2])+Number(V[3])*d-h)/d);f>lt&&p.add("accAt_"+lt)}const I=p.size?await this.state([...p]):{};for(const{id:q,f:at}of k){const[V,lt,At,vr,xs,je]=at,Cs=at[6]??"0",ze=W(At),Qe=Number(vr),Ce=ze+Qe*d,Te=Math.floor((Ce-h)/d),Ye=r>=Ce,Ts=Math.floor((r-h)/d),br=Ye&&Ts>Te,kr=Ye?f>Te?I["accAt_"+Te]||"0":Ts>Te?g:Cs:g,Ps=Fr(lt??"0",Cs,kr),Pe=Qr({principal:M(V),shares:M(lt),start_height:ze,days:Qe,good_accounting:xs==="1"},r,H(Ps).toString());m.push({id:q,principal:M(V),shares:M(lt),start_height:ze,days:Qe,maturity_height:Ce,maturity_time:new Date(Date.now()+(Ce-r)*3e3).toISOString(),mature:Ye,claimable:br,good_accounting:xs==="1",can_arm_good_accounting:Pe.canArmGoodAccounting&&je!=="1",ended:je==="1",pending_yield:je==="1"?"0.00000000":Ps,if_claimed_now:Pe.toOwner,slashed_if_claimed_now:Pe.toRewardPool,bleed_remaining_pct:Pe.bleedRemaining})}const E=(s.gov_board??"").split("|").filter(Boolean);let $=0,K=0;try{const q=await this.query("query($a: String!) { getAccountBalance(account: $a) { hbd hive } }",{a:e});$=(((Is=q.getAccountBalance)==null?void 0:Is.hbd)??0)*1e5,K=(((As=q.getAccountBalance)==null?void 0:As.hive)??0)*1e5}catch{}const Z=q=>{const at=s[`vp_${e}_${q}`];if(!at)return M(mt().multScale);const[V="0",lt="0"]=at.split("|");return Jr(V,W(lt),r,q)},wt=[];for(let q=u;q>=1;q--){const at=l[`lp_${e}_${q}`];if(!at)continue;const V=at.split("|");if(V.length<4)continue;const lt=V[5]??V[1],At=js({shares:V[0]??"0",startHeight:W(V[1]),weight:V[2]??"0",accStart:V[4]??"0",height:r,totalShares:s.amm_shares||"0",lcReserve:s.amm_lc||"0",hbdReserve:s.amm_hbd||"0",poolLiq:s.pool_liq||"0",accSeen:s.amm_accseen||"0",accHeld:s.amm_accheld||"0",acc:s.amm_acc||"0",totalWeight:s.amm_weight||"0"});wt.push({id:q,shares:M(V[0]),start_height:W(V[1]),age_days:At.age_days,loyalty_multiplier:At.loyalty,weight:M(V[2]),closed:V[3]==="1",value_lc:At.value_lc,value_hbd:At.value_hbd,pending_reward:At.pending_reward,last_touch:W(lt)})}return{account:e,balance:M(a),shares:M(s["shr_"+e]),pending:M((s["pend_"+e]??"0").split("|")[0]),pending_curation:0,mint_duration_days:W(s["set_"+e+"_days"])||mt().migrationMintDays,hbd:$,hive:K,vote_power:{viral:Z(0),deep:Z(1)},mints:m,tranches:wt,is_consensus_member:E.includes(e)}}async postsMeta(t=50){const e=await y(this,C,He).call(this,t);if(e.length===0)return y(this,C,qe).call(this,e);const[s,r]=await Promise.all([this.state(e.map(a=>`post_${a.author}_${a.permlink}`)),this.height()]),n=[];for(const{author:a,permlink:o}of e){const c=s[`post_${a}_${o}`];if(!c)continue;const u=c.split("|");if(u.length<6||u[9])continue;const l=Number(u[1]??0)||0;n.push({author:a,permlink:o,window:u[0]==="1"?"deep":"viral",created_height:l,created_time:new Date(Date.now()-(r-l)*3e3).toISOString(),title:"",summary:"",body_excerpt:"",tags:null,registered:!0})}return[...await y(this,C,Ne).call(this,n),...await y(this,C,qe).call(this,e)]}async posts(t=50){const e=await y(this,C,He).call(this,t),[s,r]=await Promise.all([y(this,C,ds).call(this,e).then(n=>y(this,C,Ne).call(this,n)),y(this,C,qe).call(this,e)]);return[...s.filter(n=>!n.parent_author),...r]}async mappedBalance(t,e){var s;try{const r=`${Rr}${ot(e)}`,a=(s=(await this.query('query($c: String!, $k: [String!]!) { getStateByKeys(contractId: $c, keys: $k, encoding: "hex") }',{c:t,k:[r]})).getStateByKeys)==null?void 0:s[r];return a==null||a===""?0n:BigInt("0x"+a)}catch{return null}}async magiPoolReserves(t){var e,s;try{const r=await this.query('query($c: String!) { getStateByKeys(contractId: $c, keys: ["r0","r1"], encoding: "hex") }',{c:t}),n=(e=r.getStateByKeys)==null?void 0:e.r0,a=(s=r.getStateByKeys)==null?void 0:s.r1;if(!n||!a)return null;const o=BigInt("0x"+n),c=BigInt("0x"+a);return o<=0n||c<=0n?null:{r0:o,r1:c}}catch{return null}}async hiveBalances(t){const e=t.replace(/^hive:/,"");try{const s=await y(this,C,Ut).call(this,"condenser_api.get_accounts",[[e]
4]),r=s==null?void 0:s[0];return r?{hbd:(r.hbd_balance??"0").split(" ")[0]??"0",hive:(r.balance??"0").split(" ")[0]??"0"}:null}catch{return null}}async hiveResourceCredits(t){var s;const e=t.replace(/^hive:/,"");try{const r=await y(this,C,Ut).call(this,"rc_api.find_rc_accounts",{accounts:[e]}),n=(s=r==null?void 0:r.rc_accounts)==null?void 0:s[0];if(!n)return null;const a=Number(n.max_rc),o=Number(n.rc_manabar.last_update_time),c=Math.max(0,Math.floor(Date.now()/1e3)-o),u=5*24*60*60,l=Number(n.rc_manabar.current_mana)+a*c/u,h=Math.min(a,l);return!Number.isFinite(h)||!Number.isFinite(a)||a<=0?null:{amount:h,max:a}}catch{return null}}async accountOps(t,e=30){var c,u,l,h,d,g,f;const s=ot(t),r=await this.query(`query($a: String!, $l: Int!) { findTransaction(filterOptions: {byAccount: $a, limit: $l}) { 5 id anchr_ts status required_auths required_posting_auths ops { type data } } }`,{a:s,l:Math.min(100,e)}),n=[];for(const m of r.findTransaction??[])for(const p of m.ops??[])p.type!=="call"||!((c=p.data)!=null&&c.action)||n.push({id:m.id,time:m.anchr_ts,action:p.data.action,payload:p.data.payload??"",status:m.status==="CONFIRMED"?"confirmed":m.status==="FAILED"?"failed":"pending"});const a=ot(t);try{const[m,p]=await Promise.all([this.query(`query($c: String!) { findTransaction(filterOptions: {byContract: $c, limit: 100}) { 6 id anchr_ts status required_auths required_posting_auths ops { type data } } }`,{c:w(this,nt)}),this.query(`query($a: String!) { findTransaction(filterOptions: {byLedgerToFrom: $a, limit: 30}) { 7 id anchr_ts status ops { type data } } }`,{a})]);for(const k of m.findTransaction??[])if(k.status==="CONFIRMED")for(const I of k.ops??[]){if(I.type!=="call"||((u=I.data)==null?void 0:u.action)!=="transfer")continue;const E=I.data.payload??"";if(!E.startsWith(`${a}|`)||n.some(K=>K.id===k.id))continue;const $=(k.required_auths??[])[0]??(k.required_posting_auths??[])[0]??"";n.push({id:k.id,time:k.anchr_ts,action:"+transfer",payload:`${E}|${$}`,status:"confirmed"})}for(const k of p.findTransaction??[])for(const I of k.ops??[]){if(I.type!=="transfer")continue;const E=((l=I.data)==null?void 0:l.to)===a;n.push({id:k.id,time:k.anchr_ts,action:E?"+ledger":"ledger",payload:`${((h=I.data)==null?void 0:h.from)??""}|${((d=I.data)==null?void 0:d.to)??""}|${((g=I.data)==null?void 0:g.amount)??""}|${((f=I.data)==null?void 0:f.asset)??""}`,status:k.status==="CONFIRMED"?"confirmed":k.status==="FAILED"?"failed":"pending"})}}catch{}const o=new Set;return n.filter(m=>{const p=`${m.id}:${m.action}`;return o.has(p)?!1:(o.add(p),!0)}).sort((m,p)=>p.time.localeCompare(m.time)).slice(0,e)}async poolOps(t=500){var n,a;const e=new Set(["add_liquidity","remove_liquidity","swap_lassecash_hbd","swap_hbd_lassecash","swap_lc_hbd","swap_hbd_lc"]),s=[],r=100;for(let o=0;o<t;o+=r){const u=(await this.query(`query($c: String!, $o: Int!, $l: Int!) { findTransaction(filterOptions: {byContract: $c, offset: $o, limit: $l}) { 8 anchr_ts anchr_height status required_auths required_posting_auths ops { type data } } }`,{c:w(this,nt),o,l:r})).findTransaction??[];for(const l of u)if(l.status==="CONFIRMED")for(const h of l.ops??[]){const d=(n=h.data)==null?void 0:n.action;h.type!=="call"||!d||!e.has(d)||s.push({time:l.anchr_ts,height:Number(l.anchr_height)||0,action:d,payload:((a=h.data)==null?void 0:a.payload)??"",signer:(l.required_auths??[])[0]??(l.required_posting_auths??[])[0]??""})}if(u.length<r)break}return s.reverse()}async poolLedger(t=500){return y(this,C,hs).call(this,new Set(["add_liquidity","remove_liquidity","swap_lassecash_hbd","swap_hbd_lassecash","swap_lc_hbd","swap_hbd_lc"]),t)}async payoutLedger(t=500){const e=new Map;for(const s of await y(this,C,hs).call(this,new Set(["payout"]),t)){if(!s.ok)continue;const r=/paid author\s+(\d+)/.exec(s.ret),[n="",a=""]=s.payload.split("|");!r||!n||!a||e.set(`${n}|${a}`,{units:r[1],height:s.height,txId:s.txId})}return e}async activity(t=2e3){var r;const e=new Map,s=50;for(let n=0;n<t;n+=s){const o=(await this.query(`query($c: String!, $o: Int!, $l: Int!) { findTransaction(filterOptions: {byContract: $c, offset: $o, limit: $l}) { 9 anchr_ts status required_auths required_posting_auths ops { type data } } }`,{c:w(this,nt),o:n,l:s})).findTransaction??[];for(const c of o){if(c.status!=="CONFIRMED")continue;const u=(c.required_auths??[])[0]??(c.required_posting_auths??[])[0]??"";if(u)for(const l of c.ops??[]){const h=(r=l.data)==null?void 0:r.action;if(l.type!=="call"||!h)continue;const d=e.get(u)??{actions:{},calls:0,lastSeen:c.anchr_ts};d.actions[h]=(d.actions[h]??0)+1,d.calls+=1,d.lastSeen<c.anchr_ts&&(d.lastSeen=c.anchr_ts),e.set(u,d)}}if(o.length<s)break}return[...e.entries()].map(([n,a])=>({account:n,...a})).sort((n,a)=>a.calls-n.calls)}async comments(t,e){const s=await y(this,C,He).call(this,200,"comment"),r=new Map;for(const l of s){const h=l.payload.split("|");r.set(`${l.author}/${l.permlink}`,`${h[1]}/${h[2]}`)}const n=`${t}/${e}`,a=new Set;for(let l=!0;l;){l=!1;for(const[h,d]of r)a.has(h)||d!==n&&!a.has(d)||(a.add(h),l=!0)}const o=s.filter(l=>a.has(`${l.author}/${l.permlink}`)),c=await y(this,C,Ne).call(this,await y(this,C,ds).call(this,o)),u=await y(this,C,tr).call(this,t,e,c);return[...c,...sn(c,u)]}async postVotes(t,e){var l,h,d;const n=`${t}|${e}|`,a=[],o=new Set;for(let g=0;g<3e3;g+=100){const m=(await this.query(`query($c: String!, $o: Int!, $l: Int!) { findTransaction(filterOptions: {byContract: $c, offset: $o, limit: $l}) { 10 required_auths required_posting_auths ops { type data } } }`,{c:w(this,nt),o:g,l:100})).findTransaction??[];for(const p of m)for(const k of p.ops??[]){if(k.type!=="call"||((l=k.data)==null?void 0:l.action)!=="vote"||!(k.data.payload??"").startsWith(n))continue;const I=((h=p.required_auths)==null?void 0:h[0])??((d=p.required_posting_auths)==null?void 0:d[0]);!I||o.has(I)||(o.add(I),a.push(I))}if(m.length<100)break}if(a.length===0)return[];const c=await this.state(a.map(g=>`pv_${t}_${e}_${g}`)),u=[];for(const g of a){const f=c[`pv_${t}_${e}_${g}`];f&&u.push({voter:g,rshares:f})}return u.sort((g,f)=>
10{const m=BigInt(g.rshares),p=BigInt(f.rshares);return m!==p?m>p?-1:1:g.voter<f.voter?-1:g.voter>f.voter?1:0}),u}async content(t,e){const s=t.replace(/^hive:/,""),a=(await(await w(this,Tt).call(this,"https://api.hive.blog",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"condenser_api.get_content",params:[s,e],id:1})})).json()).result;if(!(a!=null&&a.author))return null;let o=[],c="",u;try{const h=JSON.parse(a.json_metadata||"{}");h&&typeof h=="object"&&!Array.isArray(h)&&(u=h),Array.isArray(h.tags)&&(o=h.tags.slice(0,21)),typeof h.description=="string"&&(c=h.description)}catch{}const l=a.category||a.parent_permlink||"";return{title:a.title??"",body:a.body??"",tags:o,summary:c,...l?{category:l}:{},...u?{metadata:u}:{}}}async publish(t){const e=t.signer;if(!(e!=null&&e.publishToHive))throw new x("publishing needs a wallet that can write to Hive");const s=Hs(t.permlink??"")||Hs(t.title);return s?e.publishAndRegister?{...await e.publishAndRegister({permlink:s,title:t.title,body:t.body,tags:t.tags,summary:t.summary,image:es(t.body),window:t.window,payoutMode:t.payoutMode,sideCalls:t.sideCalls??[]}),permlink:s}:(await e.publishToHive({permlink:s,title:t.title,body:t.body,tags:t.tags,summary:t.summary,image:es(t.body)}),{...await e.submit("post",`${s}|${t.window}
10|${t.payoutMode}`),permlink:s}):{ok:!1,msg:"title must contain letters or numbers",height:0,permlink:""}}async editPost(t){const e=t.signer;if(!(e!=null&&e.editOnHive))throw new x("editing needs a wallet that can write to Hive");return t.permlink?(await e.editOnHive({permlink:t.permlink,title:t.title,body:t.body,tags:t.tags,summary:t.summary,image:es(t.body),...t.category?{category:t.category}:{},...t.metadata?{metadata:t.metadata}:{}}),{ok:!0,msg:"updated",height:0,permlink:t.permlink}):{ok:!1,msg:"no post to edit",height:0,permlink:""}}async publishComment(t){const e=t.signer;if(!(e!=null&&e.publishCommentToHive))throw new x("commenting needs a wallet that can write to Hive");const s=t.parentAuthor.replace(/^@/,"");if(e.commentAndRegister)return{...await e.commentAndRegister({permlink:t.permlink,body:t.body,parentAuthor:s,parentPermlink:t.parentPermlink,payoutMode:t.payoutMode,sideCalls:t.sideCalls??[]}),permlink:t.permlink};await e.publishCommentToHive({permlink:t.permlink,body:t.body,parentAuthor:s,parentPermlink:t.parentPermlink});const r=s.startsWith("hive:")?s:`hive:${s}`;return{...await e.submit("comment",`${t.permlink}|${r}|${t.parentPermlink}|${t.payoutMode}`),permlink:t.permlink}}async quoteSwap(t,e){const s=await this.state(["amm_lc","amm_hbd"]),r=s.amm_lc??"0",n=s.amm_hbd??"0",[a,o]=t==="hbd_lc"?[n,r]:[r,n],c=zs(a,o,e);return{amount_in:M(e),amount_out:c.amountOut,rate:c.rate,price_impact_pct:c.priceImpactPct,reserve_in:M(a),reserve_out:M(o),ok:c.ok,msg:c.ok?"":"swap not possible at this size"}}async quoteMint(t,e){const s=mt(),[r,n,a]=await Promise.all([this.state(["cfg_genesis"]),this.height(),y(this,C,Oe).call(this,[s.paramVolumeStart,s.paramVolumeEnd])]),o=W(r.cfg_genesis),c=Gr(o,n),u=Dr(t,e,H(c).toString(),a[s.paramVolumeStart],a[s.paramVolumeEnd]),l=n+e*Number(s.heightsPerDay);return{principal:M(t),days:e,shares:u.shares,share_rate:c,duration_multiplier:u.durationMultiplier,volume_multiplier:u.volumeMultiplier,combined_multiplier:u.combinedMultiplier,maturity_height:l,maturity_time:new Date(Date.now()+(l-n)*3e3).toISOString(),ok:u.ok,msg:u.ok?"":"mint not valid: check amount and duration (1..1095 days)"}}async quoteLiquidity(t){const e=await this.state(["amm_lc","amm_hbd","amm_shares"]),s=e.amm_lc??"0",r=e.amm_hbd??"0",n=e.amm_shares??"0",a=Qs(t,s,r,n);let o="0.00000000";if(a.ok){const c=H(a.shares),u=BigInt(n||"0")+c;if(u>0n){const l=(100n*BigInt(mt().unit)).toString();o=Ms(l,c.toString(),u.toString())}}return{lc_in:M(t),hbd_needed:a.hbdNeeded,shares:a.shares,pool_share_pct:o,is_first_deposit:a.isFirstDeposit,ok:a.ok,msg:a.ok?"":"liquidity deposit not valid: check amount and pool reserves"}}}ue=new WeakMap,nt=new WeakMap,Tt=new WeakMap,le=new WeakMap,C=new WeakSet,Oe=async function(t){const e=await this.governance(t),s={};for(const r of t){const n=Kr(r,e.map(a=>({account:a.account,shares:a.shares,preference:a.preferences[r]??null})));if(!n.ok)throw new x(`${r} is not a governable parameter`);s[r]=H(n.value).toString()}return s},He=async function(t,e="post",s){var c;let r=31;try{r=Number(mt().deepPayoutDays)+1}catch{}const n=Date.now()-r*24*36e5,a=10,o=[];for(let u=0;u<a;u++){const h=(await this.query(`query($c: String!, $o: Int!) { findTransaction(filterOptions: {byContract: $c, limit: 100, offset: $o}) { 11 anchr_ts status required_auths required_posting_auths ops { type data } } }`,{c:w(this,nt),o:u*100})).findTransaction??[];if(o.push(...h),h.length<100)break;const d=(c=h[h.length-1])==null?void 0:c.anchr_ts;if(d&&Date.parse(gs(d))<n)break}return en(o,t,e,s)},qe=async function(t){try{const e=await y(this,C,Ys).call(this);if(e.length===0)return[];const s=[...new Set(e.map(g=>ot(g.author)))],r=mt(),[n,a]=await Promise.all([this.state(s.map(g=>`shr_${g}`)),y(this,C,Oe).call(this,[r.paramPostThresholdViral])]),o={};for(const g of s)o[g]=n[`shr_${g}`]||"0";const c=Number(r.viralPayoutDays)*Number(r.heightsPerDay)*3e3,[u,l]=await Promise.all([this.state(["cfg_genesis"]),this.height()]),h=Date.now()-(l-W(u.cfg_genesis))*3e3,d=Math.max(Date.now()-c,h);return Zr(t,e,o,a[r.paramPostThresholdViral]??"0",d)}catch{return[]}},he=new WeakMap,jt=new WeakMap,Ys=function(){const t=Date.now();return(!w(this,jt)||t-w(this,he)>=Xr)&&(D(this,he,t),D(this,jt,y(this,C,Xs).call(this).catch(()=>[]))),w(this,jt)},Xs=async function(t=50){const[e,s]=await Promise.all([y(this,C,Ut).call(this,"bridge.get_ranked_posts",{sort:"created",tag:Os,limit:t}),y(this,C,Zs).call(this)]),r=new Set,n=[];for(const a of[...e??[],...s]){const o=`${a.author}/${a.permlink}`;
11r.has(o)||(r.add(o),n.push(a))}return n},de=new WeakMap,Zs=async function(){const e=((await this.state(["gov_board"])).gov_board||"").split("|").filter(Boolean).slice(0,20);return(await Promise.all(e.map(async r=>{const n=await y(this,C,Ut).call(this,"bridge.get_account_posts",{sort:"posts",account:r.replace(/^hive:/,""),limit:10}).catch(()=>null);if(n===null)return w(this,de).get(r)??[];const a=(n??[]).filter(o=>{const c=o.json_metadata,u=typeof c=="string"?(()=>{try{return JSON.parse(c).tags??[]}catch{return[]}})():(c==null?void 0:c.tags)??[];return Array.isArray(u)&&u.includes(Os)});return w(this,de).set(r,a),a}))).flat()},Ut=async function(t,e){return(await(await w(this,Tt).call(this,"https://api.hive.blog",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:t,params:e,id:1})})).json()).result??null},hs=async function(t,e){var l,h;const r=[];for(let d=0;d<e;d+=100){const f=(await this.query(`query($c: String!, $o: Int!, $l: Int!) { findTransaction(filterOptions: {byContract: $c, offset: $o, limit: $l}) { 12 id anchr_ts anchr_height status required_auths required_posting_auths ops { type data } } }`,{c:w(this,nt),o:d,l:100})).findTransaction??[];if(r.push(...f),f.length<100)break}if(r.length===0)return[];const n=new Map;for(const d of r)n.set(d.id,(d.ops??[]).filter(g=>g.type==="call").length);const a=Math.min(...r.map(d=>Number(d.anchr_height)||0)),o=new Map,c=Math.ceil(e/100)+2;for(let d=0;d<c;d++){const f=(await this.query(`query($c: String!, $o: Int!, $l: Int!) { findContractOutput(filterOptions: {byContract: $c, offset: $o, limit: $l}) { 13 block_height inputs results { ok ret } } }`,{c:w(this,nt),o:d*100,l:100})).findContractOutput??[];let m=!1;for(const p of f){const k=(p.results??[]).map(E=>({ok:!!E.ok,ret:E.ret??""})),I=p.inputs??[];if(I.length===1)o.set(I[0],k);else if(I.every(E=>n.has(E))){let E=0;for(const $ of I){const K=n.get($);o.set($,k.slice(E,E+K)),E+=K}}Number(p.block_height)<a&&(m=!0)}if(f.length<100||m)break}const u=[];for(const d of r){if(d.status!=="CONFIRMED")continue;const g=o.get(d.id)??[];let f=0;for(const m of d.ops??[]){if(m.type!=="call")continue;const p=f++,k=(l=m.data)==null?void 0:l.action;if(!k||!t.has(k))continue;const I=g[p];u.push({time:d.anchr_ts,height:Number(d.anchr_height)||0,action:k,payload:((h=m.data)==null?void 0:h.payload)??"",signer:(d.required_auths??[])[0]??(d.required_posting_auths??[])[0]??"",txId:d.id,ok:(I==null?void 0:I.ok)??!1,ret:(I==null?void 0:I.ret)??""})}}return u.reverse()},tr=async function(t,e,s){try{const n=new Set(s.map(p=>`${p.author}/${p.permlink}`)),a=[{author:t,permlink:e},...s.map(p=>({author:p.author,permlink:p.permlink}))],o=new Set(a.map(p=>`${p.author}/${p.permlink}`)),c=[];let u=0;for(;a.length>0&&u<30;){const p=a.shift();u++;const k=await y(this,C,Ut).call(this,"condenser_api.get_content_replies",[p.author.replace(/^hive:/,""),p.permlink]);for(const I of k??[]){const E=`${ot(I.author)}/${I.permlink}`;o.has(E)||(o.add(E),n.has(E)||c.push(I),a.push({author:ot(I.author),permlink:I.permlink}))}}if(c.length===0)return[];const l=[...new Set(c.map(p=>ot(p.author)))],h=mt(),[d,g]=await Promise.all([this.state(l.map(p=>`shr_${p}`)),y(this,C,Oe).call(this,[h.paramPostThresholdComment])]),f=g[h.paramPostThresholdComment]??"0",m=[];for(const p of c){const k=ot(p.author),I=Js(d[`shr_${k}`]||"0",f);m.push({qualifies:I,view:{author:k,permlink:p.permlink,title:"",body:p.body??"",summary:"",image:null,tags:[],created:p.created?`${p.created}Z`:"",created_time:p.created?`${p.created}Z`:"",payout_time:"",body_excerpt:(p.body??"").slice(0,220),curation_expires_at:0,created_height:0,payout_height:0,window:"viral",payout_mode:0,rshares:"0",votes:0,pending_payout:"0.00000000",curator_pot:"0.00000000",paid_out:!1,payable:!1,promoted:"0.00000000",parent_author:ot(p.parent_author),parent_permlink:p.parent_permlink,registered:!1}})}return m}catch{return[]}},ds=async function(t){if(t.length===0)return[];const[e,s]=await Promise.all([this.state(t.map(o=>`post_${o.author}_${o.permlink}`)),this.height()]),r=await this.state(["pool_viral","pool_deep","rsh_viral","rsh_deep"]),n=mt(),a=[];for(const{author:o,permlink:c}of t){const u=e[`post_${o}_${c}`];if(!u)continue;const l=u.split("|");if(l.length<6)continue;const h=l[0]==="1"?"deep":"viral",d=W(l[1]),g=h==="deep"?n.deepPayoutDays:n.viralPayoutDays,f=d+g*Number(n.heightsPerDay),m=l[3]==="1",p=h==="deep"?"pool_deep":"pool_viral",k=h==="deep"?"rsh_deep":"rsh_viral";a.push({author:o,permlink:c,window:h,created_height:d,created_time:new Date(Date.now()-(s-d)*3e3).toISOString(),payout_height:f,payout_time:new Date(Date.now()+(f-s)*3e3).toISOString(),rshares:l[2]??"0",payout_mode:W(l[7]),parent_author:l[9]??"",parent_permlink:l[10]??"",promoted:M(l[11]??"0"),title:c,summary:"",body_excerpt:"",tags:null,votes:W(l[6]),paid_out:m,payable:!m&&s>=f,pending_payout:m?"0.00000000":Ms(r[p]||"0",l[2]||"0",r[k]||"0"),curator_pot:M(l[4]),curation_expires_at:W(l[8])>0?W(l[8])+365*Number(n.heightsPerDay):0,registered:!0})}return a},ge=new WeakMap,er=function(t,e){const s=`${t}/${e}`;let r=w(this,ge).get(s);return r||(r=this.content(t,e).catch(()=>null),w(this,ge).set(s,r)),r},Ne=async function(t){return await Promise.all(t.map(async e=>{const s=await y(this,C,er).call(this,e.author,e.permlink);s&&(e.title=s.title||e.permlink,e.summary=s.summary,e.body_excerpt=s.body.slice(0,2e3),e.tags=s.tags)})),t};const Os="lassecash",Xr=6e4;function ot(i){const t=i.replace(/^@/,"");return t.includes(":")?t:`hive:${t}`}function Zr(i,t,e,s,r=0){const n=new Set(i.map(o=>`${o.author}/${o.permlink}`)),a=[];for(const o of t){if(!(o!=null&&o.author)||!o.permlink||(o.depth??0)>0||o.parent_author)continue;const c=ot(o.author),u=`${c}/${o.permlink}`;if(n.has(u)||r>0&&Date.parse(gs(o.created))<r||(n.add(u),!Js(e[c]||"0",s)))continue;const l=o.body??"",h=tn(o.json_metadata);a.push({author:c,permlink:o.permlink,window:"viral",created_height:0,created_time:gs(o.created),payout_height:0,payout_time:"",rshares:"0",payout_mode:0,parent_author:"",parent_permlink:"",promoted:"0.00000000",title:o.title||o.permlink,summary:h.summary,body_excerpt:l.slice(0,2e3),tags:h.tags,votes:0,paid_out:!1,payable:!1,pending_payout:"0.00000000",curator_pot:"0.00000000",curation_expires_at:0,registered:!1})}return a}function tn(i){let t={};try{typeof i=="string"?t=JSON.parse(i||"{}"):i&&typeof i=="object"&&(t=i)}catch{return{summary:"",tags:null}}const e=t.tags;
13return{summary:typeof t.description=="string"?t.description:"",tags:Array.isArray(e)?e.slice(0,21):null}}function gs(i){if(!i)return new Date(0).toISOString();const t=Date.parse(i.endsWith("Z")?i:i+"Z");return Number.isNaN(t)?new Date(0).toISOString():new Date(t).toISOString()}function M(i){const t=BigInt(i||"0"),e=t<0n?"-":"",s=t<0n?-t:t;return`${e}${s/100000000n}.${(s%100000000n).toString().padStart(8,"0")}`}function W(i){return Number(i||"0")}function Hs(i){let t="",e=!0;for(const s of i.toLowerCase())s>="a"&&s<="z"||s>="0"&&s<="9"?(t+=s,e=!1):(s===" "||s==="-"||s==="_")&&(e||(t+="-",e=!0));return t=t.replace(/^-+|-+$/g,""),t.length>80&&(t=t.slice(0,80).replace(/^-+|-+$/g,"")),t}function es(i){const t=/!\[[^\]]*\]\(((?:\\.|[^)\s])+)\)/i.exec(i),e=r=>r.replace(/\\([!-\/:-@\[-`{-~])/g,"$1");if(t!=null&&t[1])return e(t[1]);const s=/^(https?:\/\/\S+\.(?:png|jpe?g|gif|webp))\s*$/im.exec(i);return s!=null&&s[1]?e(s[1]):null}function en(i,t,e,s){var a,o,c,u,l;const r=new Set,n=[];for(const h of i)if(h.status!=="FAILED"){for(const d of h.ops??[]){if(d.type!=="call")continue;const g=((a=d.data)==null?void 0:a.payload)??"";let f,m;if(((o=d.data)==null?void 0:o.action)===e){if(s&&!s(g))continue;f=((c=h.required_auths)==null?void 0:c[0])??((u=h.required_posting_auths)==null?void 0:u[0]),m=g.split("|")[0]}else if(e==="post"&&((l=d.data)==null?void 0:l.action)==="vote"){const k=g.split("|");f=k[0],m=k[1]}else continue;if(!f||!m)continue;const p=f+"/"+m;r.has(p)||(r.add(p),n.push({author:f,permlink:m,payload:g}))}if(n.length>=t)break}return n}function sn(i,t){const e=new Set(i.map(s=>`${s.author}/${s.permlink}`));for(const s of t)s.qualifies&&e.add(`${s.view.author}/${s.view.permlink}`);for(let s=!0;s;){s=!1;for(const r of t){const n=`${r.view.author}/${r.view.permlink}`;if(e.has(n))continue;(i.some(o=>`${o.parent_author}/${o.parent_permlink}`===n)||t.some(o=>e.has(`${o.view.author}/${o.view.permlink}`)&&`${o.view.parent_author}/${o.view.parent_permlink}`===n))&&(e.add(n),s=!0)}}return t.filter(s=>e.has(`${s.view.author}/${s.view.permlink}`)).map(s=>s.qualifies?s.view:{...s.view,shown_for_context:!0})}const sr="lassecash/2.0";function ms(i){const t=i.siteUrl.replace(/\/+$/,""),e=i.author.replace(/^hive:/,"").replace(/^@/,""),s={app:sr,format:"markdown",tags:i.tags,description:i.summary??"",canonical_url:`${t}/@${e}/${i.permlink}`};return i.image&&(s.image=[i.image]),s}function rn(i,t,e=Date.now()){const s=i.replace(/^hive:/,"").replace(/^@/,""),r=new Date(e).toISOString().replace(/[^0-9]/g,""),n=`re-${s}-${t}-${r}`.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-");return n.length<=255?n:n.slice(n.length-255).replace(/^-+/,"")}function qs(i){const t=i.siteUrl.replace(/\/+$/,""),e=i.parentAuthor.replace(/^hive:/,"").replace(/^@/,"");return{app:sr,format:"markdown",tags:i.tags,description:i.summary??"",canonical_url:`${t}/@${e}/${i.parentPermlink}#@${i.author.replace(/^hive:/,"").replace(/^@/,"")}/${i.permlink}`}}function nn(i,t){const e=ms(t),s={...i??{}};return s.tags=e.tags,s.description=e.description,e.image?s.image=e.image:delete s.image,s.format||(s.format=e.format),typeof s.app=="string"&&s.app.startsWith("lassecash/")&&(s.app=e.app,s.canonical_url||(s.canonical_url=e.canonical_url)),s}let ee,Bt;var T;(function(i){i.CONNECTED="connected",i.AUTH_REQ="auth_req",i.AUTH_WAIT="auth_wait",i.AUTH_ACK="auth_ack",i.AUTH_NACK="auth_nack",i.AUTH_ERR="auth_err",i.SIGN_REQ="sign_req",i.SIGN_WAIT="sign_wait",i.SIGN_ACK="sign_ack",i.SIGN_NACK="sign_nack",i.SIGN_ERR="sign_err",i.CHALLENGE_REQ="challenge_req",i.CHALLENGE_WAIT="challenge_wait",i.CHALLENGE_ACK="challenge_ack",i.CHALLENGE_NACK="challenge_nack",i.CHALLENGE_ERR="challenge_err",i.ATTACH_REQ="attach_req",i.ATTACH_ACK="attach_ack",i.ATTACH_NACK="attach_nack",i.ERROR="error"})(T||(T={}));const an=250,Ue=250,Be="wss://hive-auth.arcange.eu/",on=[.8,1],Dt={host:Be};let Ct=!1,Gt=60*1e3,Ft=[],ft,X=!1;function Q(i,t){Ft=Ft.filter(s=>!s.expire||s.expire>=Date.now());const e=Ft.find(s=>s.cmd==i&&(t?s.uuid==t:!0));return e&&(Ft=Ft.filter(s=>!(s.cmd==i&&(!t||s.uuid==e.uuid)))),e}function cn(){ft=new WebSocket(Dt.host),ft.onopen=function(){Ct=!0,X&&console.log("WebSocket connected")},ft.onmessage=function(i){X&&console.log(`[RECV] ${i.data}`);
13const t=typeof i.data=="string"?JSON.parse(i.data):i.data;if(t.cmd)switch(t.cmd){case T.CONNECTED:Gt=t.timeout*1e3,on.includes(t.protocol)||console.error("unsupported HAS protocol");break;case T.AUTH_WAIT:case T.AUTH_ACK:case T.AUTH_NACK:case T.AUTH_ERR:case T.SIGN_WAIT:case T.SIGN_ACK:case T.SIGN_NACK:case T.SIGN_ERR:case T.CHALLENGE_WAIT:case T.CHALLENGE_ACK:case T.CHALLENGE_NACK:case T.CHALLENGE_ERR:case T.ATTACH_ACK:case T.ATTACH_NACK:case T.ERROR:Ft.push(t);break}},ft.onclose=function(i){ft=null,Ct=!1,X&&console.log("WebSocket disconnected",i)}}function De(i){ft&&(X&&console.log(`[SEND] ${i}`),ft.send(i))}function un(i){return new Promise(t=>setTimeout(t,i))}class Kt extends Error{constructor(t){super(t),this.name="HiveAuthInternalError"}}async function ln(i){return new Promise(async(t,e)=>{if(typeof i!="string")return e(new Kt("invalid uuid"));const s={cmd:T.ATTACH_REQ,uuid:i};De(JSON.stringify(s));let r=Date.now()+Gt;const n=setInterval(()=>{const a=Q(T.ATTACH_ACK,i),o=Q(T.ATTACH_NACK,i);a?(clearInterval(n),X&&console.log(`attach_ack found: ${JSON.stringify(a)}`),t(a)):o&&(clearInterval(n),e(o)),r<=Date.now()&&(clearInterval(n),e(new Error("expired")))},Ue)})}async function se(i){const t=await Ke(()=>import("./C-Ixlze-.js"),[],import.meta.url);if(ee=t.aesEncrypt,Bt=t.aesDecrypt,"WebSocket"in window){if(Ct)return!0;if(ft||cn(),!Ct)do await un(an);while(ft&&ft.readyState==0);if(Ct&&i)try{await ln(i),X&&console.log(`Request attached ${i}`)}catch{return!1}return Ct}else return!1}class hn{constructor(t){if(!t||typeof t.name!="string")throw new Error("missing or invalid app metadata name");this.appMeta=t}getAppMetadata(){return this.appMeta}setUsername(t){this.username=t}logout(){delete this.username,delete this.expire,delete this.key}}const ss=async(i,t)=>{if(i){if(!i.username&&typeof i.username!="string")return"invalid auth.username";if(!i.key||typeof i.key!="string")return"missing or invalid auth.key";if(!i.token||typeof i.token!="string")return"missing or invalid token"}if(t){if(t.key_type&&typeof t.key_type!="string")return"missing or invalid challenge_data.key_type";if(t.challenge&&typeof t.challenge!="string")return"missing or invalid challenge_data.challenge"}return await se()?null:"failed to connect to HiveAuth server"},rs={setOptions:function(i){if(i.host&&!i.host.match("^((ws|wss)?://)"))throw new Error("invalid host URL");if(i.auth_key_secret&&(typeof i.auth_key_secret!="string"||i.auth_key_secret===""))throw new Error("invalid auth_key_secret");i.host&&(Dt.host=i.host),i.auth_key_secret&&(console.warn("Warning: do not enable SendAuthKey unless you run your own PKSA in service mode!"),Dt.auth_key_secret=i.auth_key_secret)},traceOn:function(){X=!0},traceOff:function(){X=!1},status:function(){return{host:Dt.host,connected:Ct,timeout:Gt}},connect:async function(){return await se()},authenticate:function(i,t,e,s){return new Promise(async(r,n)=>{try{const a=await ss(null,e);if(typeof a=="string")return n(new Kt(a));if(typeof t!="string"||t.length<3)return n(new Kt("invalid username"));const o=i.key||window.crypto.randomUUID(),c=await ee(JSON.stringify({app:i.getAppMetadata(),challenge:e,token:i.token}),o),u={cmd:T.AUTH_REQ,account:t,data:c,token:i.token};Dt.auth_key_secret&&(u.auth_key=await ee(o,Dt.auth_key_secret)),De(JSON.stringify(u));let l=Date.now()+Gt,h,d=!1;const g=setInterval(async()=>{if(!d)if(d=!0,h){await se(h);const f=Q(T.AUTH_ACK,h),m=Q(T.AUTH_NACK,h),p=Q(T.AUTH_ERR,h);if(f)try{const k=JSON.parse(await Bt(f.data,o));clearInterval(g),X&&console.log(`auth_ack found: ${JSON.stringify(f)}`),i.setUsername(t),i.token=k.token,i.expire=k.expire,i.key=o,r(k)}catch(k){n(k)}else m?h==await Bt(m.data,o)&&(clearInterval(g),n(m)):p&&(clearInterval(g),n(p))}else{const f=Q(T.AUTH_WAIT),m=Q(T.ERROR);if(f){if(X&&console.log(`auth_wait found: ${JSON.stringify(f)}`),h=f.uuid,l=f.expire,f.key=o,s){const p={account:t,uuid:h,key:o,host:Be};s("has://auth_req/"+window.btoa(JSON.stringify(p)),f,()=>{clearInterval(g),n(new Error("cancelled"))})}}else m&&(X&&console.log(`error found: ${JSON.stringify(m)}`),n(m))}d=!1,l<=Date.now()&&(clearInterval(g),n(new Error("expired")))},Ue)}catch(a){n(a)}})},signTx:function(i,t,e,s,r){return new Promise(async(n,a)=>{const o=await ss(i);
13if(typeof o=="string")return a(new Kt(o));if(!e||!Array.isArray(e)||e.length===0)return a(new Kt("missing or invalid ops"));const c=await ee(JSON.stringify({key_type:t,ops:e,broadcast:s,nonce:Date.now()}),i.key),u={cmd:T.SIGN_REQ,account:i.username,data:c,token:i.token};De(JSON.stringify(u));let l=Date.now()+Gt,h,d=!1;const g=setInterval(async()=>{if(!d)if(d=!0,h){await se(h);const f=Q(T.SIGN_ACK,h),m=Q(T.SIGN_NACK,h),p=Q(T.SIGN_ERR,h);if(f)X&&console.log(`sign_ack found: ${JSON.stringify(f)}`),clearInterval(g),n(f);else if(m)clearInterval(g),a(m);else if(p){clearInterval(g);const k=await Bt(p.error,i.key);a(new Error(k))}}else{const f=Q(T.SIGN_WAIT),m=Q(T.ERROR);if(f){if(X&&console.log(`sign_wait found: ${JSON.stringify(f)}`),h=f.uuid,l=f.expire,typeof r=="function"){const p={account:i.username,uuid:h,key:i.key,host:Be};r("has://sign_req/"+window.btoa(JSON.stringify(p)),f,()=>{clearInterval(g),a(new Error("cancelled"))})}}else m&&(X&&console.log(`error found: ${JSON.stringify(m)}`),a(m))}d=!1,l<=Date.now()&&(clearInterval(g),a(new Error("expired")))},Ue)})},challenge:function(i,t,e){return new Promise(async(s,r)=>{const n=await ss(i,t);if(typeof n=="string")return r(new Kt(n));const a=await ee(JSON.stringify(t),i.key),o={cmd:T.CHALLENGE_REQ,account:i.username,data:a,token:i.token};De(JSON.stringify(o));let c=Date.now()+Gt,u,l=!1;const h=setInterval(async()=>{if(!l)if(l=!0,u){await se(u);const d=Q(T.CHALLENGE_ACK,u),g=Q(T.CHALLENGE_NACK,u),f=Q(T.CHALLENGE_ERR,u);if(d)try{const m=JSON.parse(await Bt(d.data,i.key));clearInterval(h),X&&console.log(`challenge_ack found: ${JSON.stringify(d)}`),s(m)}catch{}else if(g)clearInterval(h),r(g);else if(f){clearInterval(h);const m=await Bt(f.error,i.key);r(new Error(m))}}else{const d=Q(T.CHALLENGE_WAIT),g=Q(T.ERROR);if(d){if(X&&console.log(`challenge_wait found: ${JSON.stringify(d)}`),u=d.uuid,c=d.expire,e){const f={account:i.username,uuid:u,key:i.key,host:Be};e("has://challenge_req/"+window.btoa(JSON.stringify(f)),d,()=>{clearInterval(h),r(new Error("cancelled"))})}}else g&&(X&&console.log(`error found: ${JSON.stringify(g)}`),r(g))}l=!1,c<=Date.now()&&(clearInterval(h),r(new Error("expired")))},Ue)})}};var b;(function(i){i.Keychain="keychain",i.HiveSigner="hivesigner",i.HiveAuth="hiveauth",i.Ledger="ledger",i.PeakVault="peakvault",i.MetaMaskSnap="metamasksnap",i.ViewOnly="viewonly",i.Custom="custom"})(b||(b={}));var v;(function(i){i.Posting="posting",i.Active="active",i.Owner="owner",i.Memo="memo"})(v||(v={}));var it;(function(i){i.HIVE="HIVE",i.HBD="HBD"})(it||(it={}));var Wt;(function(i){i[i.Consensus=0]="Consensus",i[i.HBD=1]="HBD"})(Wt||(Wt={}));class Rt extends Error{constructor(t,e){super(e),this.code=t,this.name="AiohaRpcError"}}const pt="https://techcoderx.com",yt=["https://api.hive.blog","https://api.deathwing.me","https://hive-api.arcange.eu","https://api.openhive.network","https://rpc.mahdiyari.info","https://hive-api.3speak.tv","https://api.c0ff33a.uk","https://anyx.io","https://hiveapi.actifit.io"],dn="beeab0de00000000000000000000000000000000000000000000000000000000";class rr{constructor(t=pt,e=yt,s=dn){this.call=(r,n)=>St(r,n,this.api,[...this.fallbackApis]),this.callRest=r=>_s(r,this.api,[...this.fallbackApis]),this.api=t,this.fallbackApis=e,this.chainId=s}}const St=async(i,t,e=pt,s=yt)=>{try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:i,params:t})});if(r.status>=400){if(s.length===0)throw new Rt(-32603,"Failed to fetch");return await St(i,t,s[0],s.slice(1,s.length))}return await r.json()}catch{if(s.length===0)throw new Rt(-32603,"Failed to fetch");return await St(i,t,s[0],s.slice(1,s.length))}},_s=async(i,t=pt,e=yt)=>{const s=await fetch(t+i);if(s.status>=400){if(e.length===0)throw new Rt(-32603,"Failed to fetch");return await _s(i,e[0],e.slice(1,e.length))}return await s.json()},vs=(i,t=pt,e=yt)=>St("condenser_api.get_accounts",[i],t,e),gn=i=>!!i.error||!Array.isArray(i.result)||i.result.length===0,nr=(i=pt,t=yt)=>St("condenser_api.get_dynamic_global_properties",[],i,t),bs=(i,t=pt,e=yt)=>St("account_by_key_api.get_key_references",{keys:i},t,e),ir=async(i=pt,t=yt)=>{const e=await nr(i,t);if(e.error)throw new Error(e.error);return parseFloat(e.result.total_vesting_fund_hive)/parseFloat(e.result.total_vesting_shares)},mn=(i,t=pt,e=yt)=>St("condenser_api.broadcast_transaction",[i],t,e),fn=(i,t=pt,e=yt)=>St("network_broadcast_api.broadcast_transaction",{trx:i,max_block_age:-1},t,e),ns=6,Ns=10,ar=(i,t,e,s)=>["vote",{voter:i,author:t,permlink:e,weight:s}],pn=i=>
13["comment_options",i],yn=(i,t,e,s,r,n,a,o)=>{typeof a=="object"&&(a=JSON.stringify(a));const c=[["comment",{parent_author:i??"",parent_permlink:t??"",author:e,permlink:s,title:r,body:n,json_metadata:a}]];return o&&c.push(pn(o)),c},wn=async(i,t)=>{const e=await vs([i]),s=await ir();if(e.error)throw new Error(e.error);let r=t/s;const n=(Math.round(parseFloat(e.result[0].vesting_shares)*Math.pow(10,ns))-Math.round(parseFloat(e.result[0].delegated_vesting_shares)*Math.pow(10,ns)))/Math.pow(10,ns);return r>=n&&(r=n),or(i,r)},or=(i,t)=>["withdraw_vesting",{account:i,vesting_shares:t.toFixed(6)+" VESTS"}],_n=i=>{const t=new Uint8Array(i.match(/[\da-f]{2}/gi).map(r=>parseInt(r,16)));return new DataView(t.buffer).getUint32(4,!0)},ks=async(i,t=pt,e=6e5,s=0)=>{if(s>Ns)throw new Error("Failed to get dgp despite "+Ns+" tries");const r=await nr(t);if(r.error)return await new Promise(a=>{setTimeout(async()=>{a(await ks(i,t,e,s+1))},1e3)});const n=r.result;return{ref_block_num:n.head_block_number&65535,ref_block_prefix:_n(n.head_block_id),expiration:new Date(new Date(n.time+"Z").getTime()+e).toISOString().slice(0,-5),operations:i,extensions:[]}};class cr{constructor(){this.events={},this.eventOnce={}}on(t,e){this.events[t]?this.events[t].push(e):this.events[t]=[e]}once(t,e){this.eventOnce[t]?this.eventOnce[t].push(e):this.eventOnce[t]=[e]}off(t,e){if(!e)delete this.events[t];else for(let s in this.events[t])if(this.events[t][s]===e){this.events[t].splice(parseInt(s),1);break}}emit(t,...e){for(let s in this.eventOnce[t])this.eventOnce[t][s](...e);delete this.eventOnce[t];for(let s in this.events[t])this.events[t][s](...e)}}const _=(i,t)=>({success:!1,errorCode:i,error:t}),F=(i,t,e)=>({provider:e,success:!1,errorCode:i,error:t}),Vt="vsc-mainnet",Us=_(4200,"HF26 serialized tx signing is not supported for this provider");class Mt{constructor(t,e){this.api="",this.rpc=typeof t=="string"?new rr(t):t,this.eventEmitter=e||new cr}setApi(t,e){}setChainId(t){}setEventEmitter(t){this.eventEmitter=t}async signTxHF26(t,e){return Us}async signAndBroadcastTxHF26(t,e){return Us}loginNonInteractive(t,e){return _(4200,"non-interactive login is not supported for this provider")}async discoverAccounts(t,e){return _(4200,"account discovery is not supported for this provider")}request(t){return Promise.reject(new Rt(4200,"Method not found"))}async vote(t,e,s){return await this.signAndBroadcastTx([ar(this.getUser(),t,e,s)],v.Posting)}async comment(t,e,s,r,n,a,o){return await this.signAndBroadcastTx(yn(t,e,this.getUser(),s,r,n,a,o),v.Posting)}async deleteComment(t){return await this.signAndBroadcastTx([["delete_comment",{author:this.getUser(),permlink:t}]],v.Posting)}customJSON(t,e,s,r){const n=t===v.Active?[this.getUser()]:[],a=t===v.Posting?[this.getUser()]:[];return this.signAndBroadcastTx([["custom_json",{required_auths:n,required_posting_auths:a,id:e,json:s}]],t)}async transfer(t,e,s,r){return await this.signAndBroadcastTx([["transfer",{from:this.getUser(),to:t,amount:e.toFixed(3)+" "+s,memo:r??""}]],v.Active)}async recurrentTransfer(t,e,s,r,n,a,o){return await this.signAndBroadcastTx([["recurrent_transfer",{from:this.getUser(),to:t,amount:e.toFixed(3)+" "+s,recurrence:r,executions:n,memo:a??"",extensions:typeof o=="number"?[[1,{pair_id:o}]]:[]}]],v.Active)}async stakeHive(t,e){return await this.signAndBroadcastTx([["transfer_to_vesting",{from:this.getUser(),to:e??this.getUser(),amount:t.toFixed(3)+" HIVE"}]],v.Active)}async unstakeHive(t){let e;try{e=await wn(this.getUser(),t)}catch{return _(-32603,"Failed to retrieve VESTS from staked HIVE")}return await this.signAndBroadcastTx([e],v.Active)}async unstakeHiveByVests(t){return await this.signAndBroadcastTx([or(this.getUser(),t)],v.Active)}async delegateStakedHive(t,e){let s;try{s=await ir(this.rpc.api,[...this.rpc.fallbackApis])}catch{return _(-32603,"Failed to retrieve HIVE per VESTS")}return await this.delegateVests(t,e/s)}async delegateVests(t,e){return await this.signAndBroadcastTx([["delegate_vesting_shares",{delegator:this.getUser(),delegatee:t,vesting_shares:e.toFixed(6)+" VESTS"}]],v.Active)}async voteWitness(t,e){return await this.signAndBroadcastTx([["account_witness_vote",{account:this.getUser(),witness:t,approve:e}]],v.Active)}async voteProposals(t,e){return await this.signAndBroadcastTx([["update_proposal_votes",{voter:this.getUser(),proposal_ids:t,approve:e,extensions:[]}]],v.Active)}async setProxy(t){return await this.signAndBroadcastTx([["account_witness_proxy",{account:this.getUser(),proxy:t}]],v.Active)}addAccountAuthority(t,e,s){return this.modifyAuth("add","account",t,e,s)}removeAccountAuthority(t,e){return this.modifyAuth("remove","account",t,e,0)}addKeyAuthority(t,e,s){return this.modifyAuth("add","key",t,e,s)}removeKeyAuthority(t,e){return this.modifyAuth("remove","key",t,e,0)}async modifyAuth(t,e,s,r,n){if(r===v.Memo)return _(5005,`cannot ${t} ${e} memo auth`);if(t==="add"&&n<=0)return _(-32003,"weight must be greater than 0");if(e==="account"&&this.getUser()===s)return _(5201,`cannot ${t} itself as account auth`);try{const a=await vs([this.getUser()],this.rpc.api,[...this.rpc.fallbackApis]);if(gn(a))return _(-32603,`Failed to fetch current ${e} auths`);const o=a.result[0][r],c=o[`${e}_auths`].findIndex(u=>u[0]===s);if(t==="add")if(c>-1)if(o[`${e}_auths`][c][1]!==n)o[`${e}_auths`][c][1]=n;else return _(5200,"Nothing to update");else o[`${e}_auths`].push([s,n]),o[`${e}_auths`].sort((u,l)=>u[0].localeCompare(l[0]));else if(t==="remove")if(c>
13-1)o[`${e}_auths`].splice(c,1);else return _(5200,"Nothing to remove");return await this.signAndBroadcastTx([["account_update",{account:this.getUser(),posting:a.result[0].posting,active:a.result[0].active,memo_key:a.result[0].memo_key,json_metadata:a.result[0].json_metadata}]],v.Active)}catch{return _(5e3,`Failed to ${t} ${e} auth due to unknown error`)}}async vscCallContract(t,e,s,r,n,a,o=Vt){return await this.customJSON(a,"vsc.call",JSON.stringify({net_id:o,contract_id:t,action:e,payload:s,rc_limit:r,intents:n}))}vscTransfer(t,e,s,r,n=Vt){return this.vscFer("transfer",n,t,e,s,r)}vscWithdraw(t,e,s,r,n=Vt){return this.vscFer("withdraw",n,t,e,s,r)}vscStake(t,e,s,r,n=Vt){switch(t){case Wt.Consensus:return this.vscFer("consensus_stake",n,s??this.getUser(),e,it.HIVE,r);case Wt.HBD:return this.vscFer("stake_hbd",n,s??this.getUser(),e,it.HBD,r)}}vscUnstake(t,e,s,r,n=Vt){switch(t){case Wt.Consensus:return this.vscFer("consensus_unstake",n,s??this.getUser(),e,it.HIVE,r);case Wt.HBD:return this.vscFer("unstake_hbd",n,s??this.getUser(),e,it.HBD,r)}}async vscFer(t,e,s,r,n,a){return await this.customJSON(v.Active,`vsc.${t}`,JSON.stringify({to:s.startsWith("did:")||s.startsWith("hive:")?s:`hive:${s}`,from:`hive:${this.getUser()}`,amount:r.toFixed(3),asset:n.toLowerCase(),memo:a,net_id:e}))}emitSignTx(){this.eventEmitter.emit("sign_tx_request")}emitMemoReq(){this.eventEmitter.emit("memo_request")}emitLoginReq(){this.eventEmitter.emit("login_request")}rmItems(t){for(let e in t)localStorage.removeItem(t[e])}}const is=i=>i.name==="HiveAuthInternalError"?i.message:i.toString()==="Error: expired"?"HiveAuth authentication request expired":i.toString()==="Error: cancelled"?"HiveAuth authentication request cancelled":i.cmd==="auth_nack"?"HiveAuth authentication request rejected":i.cmd==="sign_nack"?"HiveAuth broadcast request rejected":i.cmd==="auth_err"||i.cmd==="sign_err"?i.error:i.toString(),as=i=>i.toString()==="Error: expired"?4002:i.toString()==="Error: cancelled"||i.cmd==="auth_nack"||i.cmd==="sign_nack"?4001:i.cmd==="auth_err"||i.cmd==="sign_err"?5903:5e3,vn="Memo operations are unavailable in HiveAuth";class bn extends Mt{constructor(t,e,s){super(t,e),this.provider=new hn(s)}async login(t,e){var s;try{const r=await rs.authenticate(this.provider,t,{key_type:e.keyType,challenge:(s=e.msg)!==null&&s!==void 0?s:window.crypto.randomUUID(),nonce:Date.now()},(n,a,o)=>{this.eventEmitter.emit("hiveauth_login_request",n,a,o),e.hiveauth&&typeof e.hiveauth.cbWait=="function"&&e.hiveauth.cbWait(n,a,o)});return this.provider.token&&localStorage.setItem("hiveauthToken",this.provider.token),localStorage.setItem("hiveauthKey",this.provider.key),localStorage.setItem("hiveauthExp",this.provider.expire.toString()),{provider:b.HiveAuth,success:!0,result:r.challenge.challenge,publicKey:r.challenge.pubkey,username:t}}catch(r){return F(as(r),is(r),b.HiveAuth)}}async loginAndDecryptMemo(t,e){return Object.assign({provider:b.HiveAuth},await this.decryptMemo())}async logout(){this.provider.logout(),this.rmItems(["hiveauthToken","hiveauthKey","hiveauthExp"])}loadAuth(t){const e=localStorage.getItem("hiveauthToken"),s=localStorage.getItem("hiveauthKey"),r=localStorage.getItem("hiveauthExp");if(!s||!r)return!1;const n=parseInt(r);return isNaN(n)||new Date().getTime()>=n?!1:(this.provider.username=t,this.provider.key=s,this.provider.expire=n,e&&(this.provider.token=e),!0)}getUser(){return this.provider.username}getLoginInfo(){if(this.getUser())return{provider:b.HiveAuth,token:this.provider.token,key:this.provider.key,exp:this.provider.expire}}loadLogin(t,e){if(e.provider!==b.HiveAuth)return!1;const s=e;return s.token&&localStorage.setItem("hiveauthToken",s.token),localStorage.setItem("hiveauthKey",s.key),localStorage.setItem("hiveauthExp",s.exp.toString()),this.loadAuth(t)}encryptMemo(){return this.decryptMemo()}encryptMemoWithKeys(){return this.encryptMemo()}async decryptMemo(){return _(4200,vn)}async signMessage(t,e){try{this.eventEmitter.emit("sign_msg_request");const s=await rs.challenge(this.provider,{key_type:e,challenge:t,nonce:Date.now()},(r,n,a)=>{this.eventEmitter.emit("hiveauth_challenge_request",r,n,a)});return{success:!0,result:s.challenge,publicKey:s.pubkey}}catch(s){return _(as(s),is(s))}}async signTx(t,e){return _(4200,"Not implemented")}async signAndBroadcastTx(t,e){try{return this.emitSignTx(),{success:!0,result:(await rs.signTx(this.provider,e,t,!0,(r,n,a)=>{this.eventEmitter.emit("hiveauth_sign_request",r,n,a)})).data}}catch(s){return _(as(s),is(s))}}}const kn="https://hivesigner.com",Sn="https://hivesigner.com";
13class In{constructor(t){this.apiURL=t.apiURL||kn,this.app=t.app,this.callbackURL=t.callbackURL,this.accessToken=t.accessToken,this.scope=t.scope,this.responseType=t.responseType}setAccessToken(t){return this.accessToken=t,this}removeAccessToken(){return delete this.accessToken,this}getLoginURL(t,e){const s=encodeURIComponent(this.callbackURL);let r=`${Sn}/oauth2/authorize?client_id=${this.app}&redirect_uri=${s}`;return this.responseType==="code"&&(r+=`&response_type=${this.responseType}`),this.scope&&(r+=`&scope=${this.scope.join(",")}`),t&&(r+=`&state=${encodeURIComponent(t)}`),e&&(r+=`&account=${encodeURIComponent(e)}`),r}decode(t,e){return this.send("decode","POST",{memo:t},e)}async revokeToken(t){return await this.send("oauth2/token/revoke","POST",{token:this.accessToken},t),this.removeAccessToken()}async send(t,e,s,r){const n=`${this.apiURL}/api/${t}`;if(!r)return this.makeRequest(n,e,s);try{const a=await this.makeRequest(n,e,s);return r(null,a)}catch(a){return r(a,null)}}broadcast(t,e){return this.send("broadcast","POST",{operations:t},e)}async makeRequest(t,e,s){const r=await fetch(t,{method:e,headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json",Authorization:this.accessToken||""},body:JSON.stringify(s)}),n=await r.json();if(r.status!==200||n.error)throw n;return n}}const ur={"/":"_",_:"/","+":"-","-":"+","=":".",".":"="},lr=i=>btoa(unescape(encodeURIComponent(i))).replace(/(\+|\/|=)/g,t=>ur[t]),Bs=i=>decodeURIComponent(escape(atob(i.replace(/(-|_|\.)/g,t=>ur[t]))));function An(i){const t=i.slice(0,5),e=new URL(i.replace(/^hive:/,"http:"));if(t!=="hive:")throw new Error(`Invalid protocol, expected 'hive:' got '${t}'`);if(e.host!=="sign")throw new Error(`Invalid action, expected 'sign' got '${e.host}'`);const[s,r]=e.pathname.split("/").slice(1);let n;try{n=JSON.parse(Bs(r))}catch(c){throw c.message=`Invalid payload: ${c.message}`,c}let a;switch(s){case"tx":a=n;break;case"op":case"ops":a={ref_block_num:"__ref_block_num",ref_block_prefix:"__ref_block_prefix",expiration:"__expiration",extensions:[],operations:s==="ops"?n:[n]};break;default:throw new Error(`Invalid signing action '${s}'`)}const o={};return e.searchParams.has("cb")&&(o.callback=Bs(e.searchParams.get("cb"))),e.searchParams.has("nb")&&(o.no_broadcast=!0),e.searchParams.has("s")&&(o.signer=e.searchParams.get("s")),{tx:a,params:o}}const xn=/(__(ref_block_(num|prefix)|expiration|signer))/g;function Cn(i,t,e){const s=t.signer||e.preferred_signer;if(!e.signers.includes(s))throw new Error(`Signer '${s}' not available`);const r={__ref_block_num:e.ref_block_num,__ref_block_prefix:e.ref_block_prefix,__expiration:e.expiration,__signer:s},n=o=>{let c=typeof o;switch(c==="object"&&Array.isArray(o)?c="array":o===null&&(c="null"),c){case"string":return o.replace(xn,u=>r[u]);case"array":return o.map(n);case"object":{const u={};for(const[l,h]of Object.entries(o))u[l]=n(h);return u}default:return o}};let a=n(i);return{signer:s,tx:a}}function Tn(i){const t=new URLSearchParams;i.no_broadcast===!0&&t.set("nb",""),i.signer&&t.set("s",i.signer),i.callback&&t.set("cb",lr(i.callback));let e=t.toString();return e.length>0&&(e="?"+e),e}function Pn(i){return lr(JSON.stringify(i,null,0))}function En(i,t={}){return`hive://sign/ops/${Pn(i)}${Tn(t)}`}const $n=["vote","comment","delete_comment","comment_options","custom_json","claim_reward_balance","account_update2"],Ln=i=>i==="server_error"?-32603:4100,Ds=i=>isNaN(i)||new Date().getTime()/1e3>=i;class Rn extends Mt{constructor(t,e,s){var r;if(super(t,e),!(!((r=s.callbackURL)===null||r===void 0)&&r.startsWith(window.location.origin)))throw new Error("callback URL must be in the same domain or subdomain as the current page");this.provider=new In(s)}async login(t,e){return new Promise(s=>{this.emitLoginReq();let r,n;const a=this.getLoginURL(e,t??void 0),o=window.open(a);let c=setInterval(()=>{o&&o.closed&&(clearInterval(c),n=localStorage.getItem("hivesignerToken"),r=localStorage.getItem("hivesignerUsername"),n&&r?(this.provider.setAccessToken(n),this.username=r,s({provider:b.HiveSigner,success:!0,result:n,username:r})):s(F(5e3,"Failed to obtain HiveSigner access token",b.HiveSigner)))},1e3)})}async loginAndDecryptMemo(t,e){const s=await this.login(t,e);if(!s.success)return s;const r=await this.decryptMemo(e.msg,v.Posting);return r.success?{provider:b.HiveSigner,success:!0,username:s.username,result:r.result}:F(5e3,r.error,b.HiveSigner)}loginNonInteractive(t,e){return!e||!e.hivesigner||typeof e.hivesigner.accessToken!="string"||typeof e.hivesigner.expiry!="number"?F(5003,"hivesigner options are required",b.HiveSigner):Ds(e.hivesigner.expiry)?F(5003,"already expired",b.HiveSigner):(this.provider.setAccessToken(e.hivesigner.accessToken),this.username=t,localStorage.setItem("hivesignerToken",e.hivesigner.accessToken),localStorage.setItem("hivesignerExpiry",e.hivesigner.expiry.toString()),localStorage.setItem("hivesignerUsername",t),{provider:b.HiveSigner,success:!0,result:"",username:t})}async logout(){try{await this.provider.revokeToken(),this.rmItems(["hivesignerToken","hivesignerExpiry","hivesignerUsername"]),this.provider.removeAccessToken(),delete this.username}catch{}}getLoginURL(t,e){var s;return this.provider.getLoginURL((s=t&&t.hivesigner&&t.hivesigner.state)!==null&&s!==void 0?s:"",e)}loadAuth(t){const e=localStorage.getItem("hivesignerToken"),s=localStorage.getItem("hivesignerExpiry"),r=localStorage.getItem("hivesignerUsername");if(!e||!s||!r||r!==t)return!1;const n=parseInt(s);return Ds(n)?!1:(this.provider.setAccessToken(e),this.username=r,!0)}getUser(){return this.username}getLoginInfo(){if(this.getUser())return{provider:b.HiveSigner,token:this.provider.accessToken,exp:parseInt(localStorage.getItem("hivesignerExpiry"))*1e3}}loadLogin(t,e){if(e.provider!==b.HiveSigner)return!1;const s=e;return this.loginNonInteractive(t,{hivesigner:{accessToken:s.token,expiry:s.exp/1e3}}).success}async encryptMemo(){return _(4200,"Memo encryption is not supported in HiveSigner")}encryptMemoWithKeys(){return this.encryptMemo()}async decryptMemo(t,e){if(e!==v.Posting)return _(5005,"Memo must be decrypted using @hivesigner account posting key");const s=await this.provider.decode(t);return s.memoDecoded?{success:!0,result:s.memoDecoded}:_(5e3,"Failed to decrypt memo")}async signMessage(){return _(4200,"message signing is unsupported in HiveSigner")}async signTx(t,e){return _(4200,"tx signing without broadcast is unsupported in HiveSigner")}async signAndBroadcastTx(t,e){var s;for(let r in t)if(!$n.includes(t[r][0]))return await this.signTxInWindow(t);try{return{success:!0,result:(await this.provider.broadcast(t)).result.id}}catch(r){const n=r;return n.error==="invalid_scope"?await this.signTxInWindow(t):_(n.error_description?Ln(n.error):5e3,(s=n.error_description)!==null&&s!==void 0?s:"Failed to broadcast tx due to unknown error")}}async signTxInWindow(t){return new Promise(e=>{this.emitSignTx();const s=En(t).replace("hive://","https://hivesigner.com/")+`?redirect_uri=${encodeURIComponent(this.provider.callbackURL)}`,r=localStorage.getItem("hivesignerTxId"),n=window.open(s);let a=setInterval(()=>{if(n&&n.closed){clearInterval(a);const o=localStorage.getItem("hivesignerTxId");e(o&&o!==r?{success:!0,result:o}:_(5e3,"Failed to broadcast transaction."))}},1e3)})}}var Jt;(function(i){i.owner="Owner",i.posting="Posting",i.active="Active",i.memo="Memo"})(Jt||(Jt={}));class Mn{async encode(t,e,s,r,n){return new Promise(async a=>{const o=`requestEncode${t?"WithKeys":"Message"}`;try{window.hive_keychain[o](e,s,r,n,c=>{a(c)})}catch(c){throw c}})}async challenge(t,e,s,r,n){return new Promise(async a=>{const o=`request${t?"VerifyKey":"SignBuffer"}`;try{window.hive_keychain[o](e,s,r,c=>{a(c)},void 0,n)}catch(c){throw c}})}async addAuth(t,e,s,r,n){return new Promise(async a=>{try{window.hive_keychain[`requestAdd${t}Authority`](e,s,r,n,o=>{a(o)})}catch(o){throw o}})}async rmAuth(t,e,s,r){return new Promise(async n=>{try{window.hive_keychain[`requestRemove${t}Authority`](e,s,r,a=>{n(a)})}catch(a){throw a}})}async broadcast(t,e,s){return new Promise(async r=>{try{window.hive_keychain.requestBroadcast(t,e,s,n=>{r(n)})}catch(n){throw n}})}async signTx(t,e,s){return new Promise(async r=>{try{window.hive_keychain.requestSignTx(t,e,s,n=>{r(n)})}catch(n){throw n}})}async post(t,e,s,r,n,a,o,c){return new Promise(async u=>{try{window.hive_keychain.requestPost(t,e,s,r,n,a,o,c,l=>{u(l)})}catch(l){throw l}})}async vote(t,e,s,r){return new Promise(async n=>{try{window.hive_keychain.requestVote(t,s,e,r,a=>{n(a)})}catch(a){throw a}})}async custom(t,e,s,r,n){return new Promise(async a=>{try{window.hive_keychain.requestCustomJson(t,s,e,r,n,o=>{a(o)})}catch(o){throw o}})}async transfer(t,e,s,r,n){return new Promise(async a=>{try{window.hive_keychain.requestTransfer(t,e,s,n,r,o=>{a(o)},!0)}catch(o){throw o}})}async recurrentTransfer(t,e,s,r,n,a,o,c){return new Promise(async u=>{try{window.hive_keychain.requestRecurrentTransfer(t,e,s,r,n,a,o,l=>{u(l)},void 0,c)}catch(l){throw l}})}async delegation(t,e,s,r){return new Promise(async n=>{try{window.hive_keychain.requestDelegation(t,e,s,r,a=>{n(a)})}catch(a){throw a}})}async witnessVote(t,e,s){return new Promise(async r=>{try{window.hive_keychain.requestWitnessVote(t,e,s,n=>{r(n)})}catch(n){throw n}})}async proxy(t,e){return new Promise(async s=>{try{window.hive_keychain.requestProxy(t,e,r=>{s(r)})}catch(r){throw r}})}async powerUp(t,e,s){return new Promise(async r=>{try{window.hive_keychain.requestPowerUp(t,e,s,n=>{r(n)})}catch(n){throw n}})}async powerDown(t,e){return new Promise(async s=>{try{window.hive_keychain.requestPowerDown(t,e,r=>{s(r)})}catch(r){throw r}})}async updateProposalVote(t,e,s){return new Promise(async r=>{try{window.hive_keychain.requestUpdateProposalVote(t,e,s,[],n=>{r(n)})}catch(n){throw n}})}}const _t=i=>typeof i.error=="string"&&i.error==="user_cancel"?4001:typeof i.error=="object"&&typeof i.error.code=="number"?i.error.code:5e3,st={owner:Jt.owner,active:Jt.active,posting:Jt.posting,memo:Jt.memo};class ce extends Mt{constructor(t,e){super(t,e),this.provider=new Mn,this.username=""}async login(t,e){var s;
13if(!ce.isInstalled())return F(5001,"Keychain extension is not installed",b.Keychain);this.emitLoginReq();const r=await this.provider.challenge(!1,t,(s=e.msg)!==null&&s!==void 0?s:"",st[e.keyType],e.loginTitle);return r.success&&(this.username=t),{provider:b.Keychain,success:r.success,error:r.success?void 0:r.message,result:r.result,publicKey:r.publicKey,username:t}}async loginAndDecryptMemo(t,e){if(!ce.isInstalled())return F(5001,"Keychain extension is not installed",b.Keychain);this.emitLoginReq();const s=await this.provider.challenge(!0,t,e.msg,st[e.keyType]);return s.success&&(this.username=t),s.success?{provider:b.Keychain,success:!0,result:s.result,username:t}:F(_t(s),s.message,b.Keychain)}async logout(){this.username=""}loadAuth(t){return this.username=t,!0}getUser(){return this.username}getLoginInfo(){if(this.getUser())return{provider:b.Keychain}}loadLogin(t){return this.loadAuth(t)}static isInstalled(){return!!window.hive_keychain}async encryptMemo(t,e,s){this.emitMemoReq();const r=await this.provider.encode(!1,this.getUser(),s,t,st[e]);return r.success?{success:!0,result:r.result}:_(_t(r),r.message)}async encryptMemoWithKeys(t,e,s){this.emitMemoReq();const r=await this.provider.encode(!0,this.getUser(),s,t,st[e]);return r.success?{success:!0,result:r.result}:_(_t(r),r.message)}async decryptMemo(t,e){this.emitMemoReq();const s=await this.provider.challenge(!0,this.getUser(),t,st[e]);return s.success?{success:!0,result:s.result}:_(_t(s),s.message)}async signMessage(t,e){this.eventEmitter.emit("sign_msg_request");const s=await this.provider.challenge(!1,this.getUser(),t,st[e]);return s.success?{success:s.success,result:s.result,publicKey:s.publicKey}:_(_t(s),s.error)}async signTx(t,e){this.emitSignTx();const s=await this.provider.signTx(this.username,t,st[e]);return s.success?{success:s.success,result:s.result}:_(_t(s),s.error)}async signAndBroadcastTx(t,e){try{this.emitSignTx();const s=await this.provider.broadcast(this.username,t,st[e]);return this.txResult(s)}catch(s){return _(_t(s),s.message)}}txResult(t){return t.success?{success:t.success,result:t.result.id}:_(_t(t),t.message)}async vote(t,e,s){this.emitSignTx();const r=await this.provider.vote(this.username,t,e,s);return this.txResult(r)}async comment(t,e,s,r,n,a,o){if(t&&e)return await super.comment(t,e,s,r,n,a,o);this.emitSignTx();const c=await this.provider.post(this.username,r,n,e??"",t??"",a,s,o?JSON.stringify(o):"");return this.txResult(c)}async customJSON(t,e,s,r){return this.emitSignTx(),this.txResult(await this.provider.custom(this.username,st[t],e,s,r??"Custom JSON"))}async transfer(t,e,s,r){return this.emitSignTx(),this.txResult(await this.provider.transfer(this.username,t,e.toFixed(3),s,r??""))}async recurrentTransfer(t,e,s,r,n,a,o){return this.emitSignTx(),this.txResult(await this.provider.recurrentTransfer(this.username,t,e.toFixed(3),s,a??"",r,n,o))}async stakeHive(t,e){return this.emitSignTx(),this.txResult(await this.provider.powerUp(this.username,e??this.username,t.toFixed(3)))}async unstakeHive(t){return this.emitSignTx(),this.txResult(await this.provider.powerDown(this.username,t.toFixed(3)))}async delegateStakedHive(t,e){return this.emitSignTx(),this.txResult(await this.provider.delegation(this.username,t,e.toFixed(3),"HP"))}async delegateVests(t,e){return this.emitSignTx(),this.txResult(await this.provider.delegation(this.username,t,e.toFixed(6),"VESTS"))}async voteWitness(t,e){return this.emitSignTx(),this.txResult(await this.provider.witnessVote(this.username,t,e))}async voteProposals(t,e){return this.emitSignTx(),this.txResult(await this.provider.updateProposalVote(this.username,t,e))}async setProxy(t){return this.emitSignTx(),this.txResult(await this.provider.proxy(this.username,t))}async addAccountAuthority(t,e,s){return this.emitSignTx(),this.txResult(await this.provider.addAuth("Account",this.getUser(),t,st[e],s))}async removeAccountAuthority(t,e){return this.emitSignTx(),this.txResult(await this.provider.rmAuth("Account",this.getUser(),t,st[e]))}async addKeyAuthority(t,e,s){return this.emitSignTx(),this.txResult(await this.provider.addAuth("Key",this.getUser(),t,st[e],s))}async removeKeyAuthority(t,e){return this.emitSignTx(),this.txResult(await this.provider.rmAuth("Key",this.getUser(),t,st[e]))}}
13const On=async i=>new Uint8Array(await window.crypto.subtle.digest("SHA-256",i)),Hn=async i=>Array.from(await On(new TextEncoder().encode(i))).map(e=>e.toString(16).padStart(2,"0")).join(""),hr="Failed to establish connection to the device",qn="Memo cryptography is not supported in Ledger provider";var kt;(function(i){i[i.owner=0]="owner",i[i.active=1]="active",i[i.memo=3]="memo",i[i.posting=4]="posting"})(kt||(kt={}));const Nn=["owner","active","","memo","posting"],Ee={maxAccountGap:2,maxKeyGap:2},Un=(i,t,e)=>`m/48'/13'/${i}'/${t}'/${e}'`,rt={27013:{code:4001,msg:"Request has been rejected"},45062:{code:5904,msg:"Hash signing is not enabled"}},dr=async(i,t,e,s,r)=>{const n=[];t:for(let a=0,o=0;o<Ee.maxAccountGap;a++)for(let c=0,u=0;u<Ee.maxKeyGap;c+=1){if(r&&r.stopped)return n;const l=Un(i,a,c),h=await t.getPublicKey(l,!1);if(r&&r.stopped)return n;const d=await bs([h],s);let g=!1;if(!d.error&&d.result&&Array.isArray(d.result.accounts)){for(let f in d.result.accounts)if(Array.isArray(d.result.accounts[f]))for(let m in d.result.accounts[f]){g=!0;const p={username:d.result.accounts[f][m],path:l,pubkey:h};if(n.push(p),r&&typeof r.stream=="function"&&r.stream(Object.assign(Object.assign({},p),{role:Nn[i]}),()=>r.stopped=!0),e===d.result.accounts[f][m])break t}}g?(o=0,u=0):(u++,u===Ee.maxKeyGap&&c===Ee.maxKeyGap-1&&(o+=1))}return n},Bn=async(i,t,e)=>{const s=[kt.owner,kt.active,kt.posting];for(let r in s){const a=(await dr(s[r],i,t,e)).find(o=>o.username===t);if(a)return a}return null},Dn=async(i,t,e,s)=>{if(e.length===0||typeof e[0]!="string")return null;const r=await i.getPublicKey(e[0],!1),n=await bs([r],s);return n.result&&n.result.accounts&&Array.isArray(n.result.accounts[0])&&n.result.accounts[0].includes(t)?{username:t,path:e[0],pubkey:r}:null},os=_(5900,hr);class Fn extends Mt{constructor(t,e){super(t,e),this.sha256=Hn}async getLib(){let t=(await Ke(async()=>{const{default:e}=await import("./DmmBUNbX.js").then(s=>s.H);return{default:e}},__vite__mapDeps([0,1]),import.meta.url)).default;return typeof t.default<"u"&&t.__esModule&&(t=t.default),t}async checkConnection(){try{if(!this.provider){const t=(await Ke(async()=>{const{default:r}=await import("./DYuROC2c.js").then(n=>n.w);return{default:r}},__vite__mapDeps([2,1]),import.meta.url)).default,e=await this.getLib(),s=await t.create();this.provider=new e(s),s.on("disconnect",()=>delete this.provider)}return!0}catch{return!1}}async closeConnection(){this.provider&&(await this.provider.transport.close(),delete this.provider)}async login(t,e){var s,r,n;if(!await this.checkConnection())return F(5900,hr,b.Ledger);try{try{const a=Array.isArray(e.paths)&&e.paths.length>0,o=a?await Dn(this.provider,t,e.paths,this.rpc.api):await Bn(this.provider,t,this.rpc.api);if(!o)return await this.closeConnection(),F(5901,"Username is not associated with the device"+(a?" for the specified path":""),b.Ledger);try{this.emitLoginReq();const c=await this.provider.signHash(await this.sha256((s=e.msg)!==null&&s!==void 0?s:"Aioha app login"),o.path);return this.username=t,this.path=o.path,localStorage.setItem("ledgerPath",this.path),{provider:b.Ledger,success:!0,result:c,publicKey:o.pubkey,username:t}}catch(c){await this.closeConnection();const u=c.statusCode;return F(rt[u]?rt[u].code:5903,rt[u]?rt[u].msg:(r=c.message)!==null&&r!==void 0?r:c.toString(),b.Ledger)}}catch{return await this.closeConnection(),F(5902,"Failed to search accounts",b.Ledger)}}catch(a){return F(5e3,(n=a.message)!==null&&n!==void 0?n:"Failed to login",b.Ledger)}}async loginAndDecryptMemo(t,e){return Object.assign({provider:b.Ledger},await this.decryptMemo())}async logout(){try{await this.closeConnection(),delete this.username,delete this.path,this.rmItems(["ledgerPath"])}catch{}}async discoverAccounts(t,e){if(!await this.checkConnection())return os;const s={owner:kt.owner,active:kt.active,posting:kt.posting},r={},n={stopped:!1,stream:t};try{for(let a in s)if(!e||!Array.isArray(e.roles)||e.roles.length===0||e.roles.includes(a)){const o=await dr(s[a],this.provider,void 0,this.rpc.api,n);for(let c in o){const u={pubkey:o[c].pubkey,path:o[c].path,role:a};r[o[c].username]?r[o[c].username].push(u):r[o[c].username]=[u]}}return{success:!0,result:r}}catch{return _(5902,"Failed to search accounts")}}loadAuth(t){const e=localStorage.getItem("ledgerPath");return e?(this.username=t,this.path=e,!0):!1}getUser(){return this.username}getLoginInfo(){if(this.getUser())return{provider:b.Ledger,path:this.path}}loadLogin(t,e){const s=e.path;return this.username=t,this.path=s,localStorage.setItem("ledgerPath",s),!0}encryptMemo(){return this.decryptMemo()}encryptMemoWithKeys(){return this.encryptMemo()}async decryptMemo(){return _(4200,qn)}async signMessage(t,e){var s;if(!await this.checkConnection())return os;if(!this.path)throw new Error("no path?");try{return this.eventEmitter.emit("sign_msg_request"),{success:!0,result:await this.provider.signHash(await this.sha256(t),this.path)}}catch(r){const n=r.statusCode;return _(rt[n]?rt[n].code:5903,rt[n]?rt[n].msg:(s=r.message)!==null&&s!==void 0?s:r.toString())}}async signTx(t,e){var s;if(!await this.checkConnection())return os;if(!this.path)throw new Error("no path?");try{return this.emitSignTx(),{success:!0,result:await this.provider.signTransaction(t,this.path,this.rpc.chainId)}}catch(r){const n=r.statusCode;return _(rt[n]?rt[n].code:5903,rt[n]?rt[n].msg:(s=r.message)!==null&&s!==void 0?s:r.toString())}}async signAndBroadcastTx(t,e){var s,r;try{const n=await ks(t,this.rpc.api),a=await this.signTx(n,v.Active);if(!a.success)return a;const c=(await this.getLib()).getTxId(n),u=await mn(a.result,this.rpc.api);return u.error?_((s=u.error.code)!==null&&s!==void 0?s:-32603,(r=u.error.message)!==null&&r!==void 0?r:"Failed to broadcast transaction due to unknown error"):{success:!0,result:c}}catch{return _(5e3,"Failed to sign or broadcast tx due to unknown error")}}}class Ge extends Mt{constructor(t,e){super(t,e)}
13async login(t,e){if(!Ge.isInstalled())return F(5001,"Peak Vault extension is not installed",b.PeakVault);try{this.emitLoginReq();const s=await window.peakvault.requestSignBuffer(t,e.keyType,e.msg);return this.username=t,{provider:b.PeakVault,success:!0,result:s.result,username:t,publicKey:s.publicKey}}catch(s){return F(5e3,s.message,b.PeakVault)}}async loginAndDecryptMemo(t,e){this.emitLoginReq();const s=await this.decryptMemo(e.msg||window.crypto.randomUUID(),e.keyType||v.Posting,t,!1);return s.success&&(this.username=t),Object.assign({provider:b.PeakVault},s.success?{success:!0,result:s.result,username:t}:_(s.errorCode,s.error))}async logout(){delete this.username}loadAuth(t){return this.username=t,!0}getUser(){return this.username}getLoginInfo(){if(this.getUser())return{provider:b.PeakVault}}loadLogin(t){return this.loadAuth(t)}static isInstalled(){return!!window.peakvault}async encryptMemo(t,e,s){if(e!==v.Memo)return _(5005,"keyType must be memo for peakvault memo encryption");try{this.emitMemoReq();const r=await window.peakvault.requestEncode(this.getUser(),s,t);return{success:!0,result:r.result,publicKey:r.publicKey}}catch(r){return _(5e3,r.message)}}async encryptMemoWithKeys(t,e,s){try{this.emitMemoReq();const r=await window.peakvault.requestEncodeWithKeys(this.getUser(),e,s,t),n={};for(let a in s)n[s[a]]=r.result[a];return{success:!0,result:n,publicKey:r.publicKey}}catch(r){return _(5e3,r.message)}}async decryptMemo(t,e,s,r=!0){try{r&&this.emitMemoReq();const n=await window.peakvault.requestDecode(this.getUser()||s,t,e);return{success:!0,result:n.result,publicKey:n.publicKey}}catch(n){return _(5e3,n.message)}}async signMessage(t,e){try{this.eventEmitter.emit("sign_msg_request");const s=await window.peakvault.requestSignBuffer(this.getUser(),e,t);return{success:!0,result:s.result,publicKey:s.publicKey}}catch(s){return _(5e3,s.message)}}async signTx(t,e){try{return this.emitSignTx(),{success:!0,result:(await window.peakvault.requestSignTx(this.getUser(),t,e)).result}}catch(s){return _(5e3,s.message)}}async signAndBroadcastTx(t,e){try{return this.emitSignTx(),{success:!0,result:(await window.peakvault.requestBroadcast(this.getUser(),t,e)).result.tx_id}}catch(s){return _(5e3,s.message)}}}const Ot=_(4200,"Cannot sign or transact in view only mode");class Kn extends Mt{constructor(){super("")}async login(t){return this.user=t,{provider:b.ViewOnly,success:!0,username:t,result:""}}loginAndDecryptMemo(t){return this.login(t)}async logout(){delete this.user}loadAuth(t){return this.user=t,!0}getUser(){return this.user}getLoginInfo(){return{provider:b.ViewOnly}}loadLogin(t,e){return this.loadAuth(t)}async encryptMemo(){return Ot}async encryptMemoWithKeys(){return Ot}async decryptMemo(){return Ot}async signMessage(){return Ot}async signTx(){return Ot}async signAndBroadcastTx(){return Ot}}const $e=async i=>{try{return await i.request({method:"wallet_getSnaps"}),!0}catch{return!1}},Vn=()=>new Promise(i=>{const t=setTimeout(()=>{e(null)},500),e=r=>{window.removeEventListener("eip6963:announceProvider",s),clearTimeout(t),i(r)};function s({detail:r}){if(!r)return;const{info:n,provider:a}=r;n.rdns.includes("io.metamask")&&e(a)}window.addEventListener("eip6963:announceProvider",s),window.dispatchEvent(new Event("eip6963:requestProvider"))}),Gn=async()=>{var i,t;if(typeof window>"u")return null;if(window.ethereum&&await $e(window.ethereum))return window.ethereum;if(!((i=window.ethereum)===null||i===void 0)&&i.detected){for(const s of window.ethereum.detected)if(await $e(s))return s}if(!((t=window.ethereum)===null||t===void 0)&&t.providers){for(const s of window.ethereum.providers)if(await $e(s))return s}const e=await Vn();return e&&await $e(e)?e:null},J=i=>{i=i.toString();const[t,e]=i.split(" "),s=parseFloat(t);switch(e){case"HIVE":case"TESTS":return{amount:Math.round(s*1e3).toString(),nai:"@@000000021",precision:3};case"HBD":case"TBD":return{amount:Math.round(s*1e3).toString(),nai:"@@000000013",precision:3};case"VESTS":return{amount:Math.round(s*1e6).toString(),nai:"@@000000037",precision:6};default:throw new Error("invalid asset")}},Fs=i=>({base:J(i.base),quote:J(i.quote)}),gr=i=>{const t=i[0],e=t+"_operation",s=structuredClone(i[1]);switch(t){case"account_create":s.fee=J(s.fee);break;case"claim_reward_balance":s.reward_hive=J(s.reward_hive),s.reward_hbd=J(s.reward_hbd),s.reward_vests=J(s.reward_vests);break;case"claim_account":s.fee=J(s.fee);break;case"comment_options":s.max_accepted_payout=J(s.max_accepted_payout),s.extensions=s.extensions.map(r=>({type:"comment_payout_beneficiaries",value:r[1]}));break;
13case"recurrent_transfer":s.extensions=s.extensions.map(r=>({type:"recurrent_transfer_pair_id",value:r[1]}));case"convert":case"transfer":case"transfer_from_savings":case"transfer_to_savings":case"transfer_to_vesting":case"collateralized_convert":s.amount=J(s.amount);break;case"delegate_vesting_shares":case"withdraw_vesting":s.vesting_shares=J(s.vesting_shares);break;case"escrow_transfer":s.fee=J(s.fee);case"escrow_release":s.hbd_amount=J(s.hbd_amount),s.hive_amount=J(s.hive_amount);break;case"feed_publish":s.exchange_rate=Fs(s.exchange_rate);break;case"limit_order_create":s.amount_to_sell=J(s.amount_to_sell),s.min_to_receive=J(s.min_to_receive);break;case"limit_order_create2":s.amount_to_sell=J(s.amount_to_sell),s.exchange_rate=Fs(s.exchange_rate);break;case"witness_update":s.fee=J(s.fee),s.props.account_creation_fee=J(s.props.account_creation_fee);break;case"create_proposal":s.daily_pay=J(s.daily_pay);break;case"update_proposal":s.daily_pay=J(s.daily_pay),s.extensions=s.extensions.map(r=>({type:"update_proposal_end_date",value:r[1]}));break}return{type:e,value:s}},Wn=i=>({ref_block_num:i.ref_block_num,ref_block_prefix:i.ref_block_prefix,expiration:i.expiration,operations:i.operations.map(t=>gr(t)),extensions:i.extensions}),Le="npm:@hiveio/metamask-snap",Jn="1.7.0",Ht=_(4900,"Snap is not connected");class jn extends Mt{constructor(t,e){super(t,e)}
13async initProvider(){if(!this.provider){const t=await Gn();if(!t)return!1;this.provider=t}return!0}async initSnap(){if(!await this.initProvider())return!1;if(!this.snap)try{let t=await this.provider.request({method:"wallet_getSnaps"});t[Le]||(t=await this.provider.request({method:"wallet_requestSnaps",params:{[Le]:{version:Jn}}})),this.snap=t[Le]}catch{return!1}return!!this.snap}async invokeSnap(t,e){if(!this.snap)throw new Rt(5001,"The snap is not connected");return this.provider.request({method:"wallet_invokeSnap",params:{snapId:Le,request:e?{method:t,params:e}:{method:t}}})}isInstalled(){return!!this.provider}async checkAssociation(t,e,s){const r=await this.discoverAccounts(void 0,{accountIndex:s,roles:[e]});if(!r.success)return Object.assign({provider:b.MetaMaskSnap},r);const n=r.result;if(n.length===0||!n[0].accounts||!n[0].accounts.includes(t))return F(5901,"Username is not associated with the snap",b.MetaMaskSnap)}async login(t,e){var s,r;if(this.emitLoginReq(),!await this.initSnap())return Ht;const n=(r=(s=e==null?void 0:e.metamask)===null||s===void 0?void 0:s.accountIdx)!==null&&r!==void 0?r:0;if(e.metamask&&e.metamask.validateUser){const a=await this.checkAssociation(t,e.keyType,n);if(a)return a}return this.accountIdx=n,this.username=t,localStorage.setItem("mmHiveSnapAccIdx",n.toString()),{provider:b.MetaMaskSnap,success:!0,username:t,result:""}}async loginAndDecryptMemo(t,e){var s,r;if(this.emitLoginReq(),!await this.initSnap())return Ht;const n=(r=(s=e==null?void 0:e.metamask)===null||s===void 0?void 0:s.accountIdx)!==null&&r!==void 0?r:0;if(e.metamask&&e.metamask.validateUser){const o=await this.checkAssociation(t,e.keyType,n);if(o)return o}const a=await this.decryptMemo(e.msg,e.keyType,!1);return a.success?(this.accountIdx=n,this.username=t,localStorage.setItem("mmHiveSnapAccIdx",n.toString()),{provider:b.MetaMaskSnap,success:!0,username:t,result:a.result}):a}async logout(){delete this.accountIdx,delete this.username,this.rmItems(["mmHiveSnapAccIdx"])}async discoverAccounts(t,e){var s;if(!await this.initSnap())return Ht;try{const r=!e||!Array.isArray(e.roles)||e.roles.length===0?[v.Owner,v.Active,v.Posting]:e.roles,n=(s=e==null?void 0:e.accountIndex)!==null&&s!==void 0?s:0,a=await this.invokeSnap("hive_getPublicKeys",{keys:r.map(c=>({role:c,accountIndex:n}))}),o=await bs(a.publicKeys.map(c=>c.publicKey),this.rpc.api,[...this.rpc.fallbackApis]);if(!o.error&&o.result&&Array.isArray(o.result.accounts))for(let c in a.publicKeys)a.publicKeys[c].accounts=o.result.accounts[c],typeof t=="function"&&a.publicKeys[c].accounts.forEach(u=>{t({username:u,index:n,pubkey:a.publicKeys[c].publicKey,role:a.publicKeys[c].role},()=>{})});return{success:!0,result:a.publicKeys}}catch(r){return _(5902,r.message)}}loadAuth(t){const e=parseInt(localStorage.getItem("mmHiveSnapAccIdx")||"");return isNaN(e)?!1:(this.accountIdx=e,this.username=t,!0)}getUser(){return this.username}getLoginInfo(){return{provider:b.MetaMaskSnap,accIdx:this.accountIdx}}loadLogin(t,e){const s=e.accIdx;return localStorage.setItem("mmHiveSnapAccIdx",s.toString()),this.loadAuth(t)}async encryptMemo(t,e,s){try{const r=await _s(`/hafbe-api/accounts/${s}/authority`);if(!r[e])throw"";const n=e===v.Memo?r.memo:r[e].key_auths[0][0],a=await this.encryptMemoWithKeys(t,e,[n]);return a.success?{success:!0,result:Object.values(a.result)[0]}:a}catch{return _(5e3,"Failed to encrypt memo")}}async encryptMemoWithKeys(t,e,s){if(!await this.initSnap())return Ht;const r={};this.emitMemoReq();try{for(let n in s){const a=await this.invokeSnap("hive_encrypt",{buffer:t,firstKey:{role:e,accountIndex:this.accountIdx},secondKey:s[n]});r[s[n]]=a.buffer}}catch(n){return _(n.code,n.message)}return{success:!0,result:r}}async decryptMemo(t,e,s=!0){s&&this.emitMemoReq();try{return{success:!0,result:(await this.invokeSnap("hive_decrypt",{buffer:t,firstKey:{role:e,accountIndex:this.accountIdx}})).buffer}}catch(r){return _(r.code,r.message)}}async signMessage(t,e){if(!await this.initSnap())return Ht;this.eventEmitter.emit("sign_msg_request");try{const s=Array.from(new TextEncoder().encode(t));return{success:!0,result:(await this.invokeSnap("hive_encrypt",{buffer:s,firstKey:{role:e,accountIndex:this.accountIdx}})).buffer}}catch(s){return _(s.code,s.message)}}async signTx(t,e){const s=await this.signTxHF26(Wn(t),e);if(!s.success)return s;const r=structuredClone(t);return r.signatures=s.result.signatures,{success:!0,result:r}}async signAndBroadcastTx(t,e){return await this.signAndBroadcastTxHF26(t.map(s=>gr(s)),e)}async signTxHF26(t,e){try{if(!await this.initSnap())return Ht;this.emitSignTx();const s=await this.invokeSnap("hive_signTransaction",{transaction:JSON.stringify(t),keys:[{role:e,accountIndex:this.accountIdx}],chainId:this.rpc.chainId}),r=structuredClone(t);return r.signatures=s.signatures,{success:!0,result:r}}catch(s){return _(s.code,s.message)}}async signAndBroadcastTxHF26(t,e){var s,r;try{const n=await ks(t,this.rpc.api),a=await this.signTxHF26(n,e);if(!a.success)return a;const{transactionDigest:o}=await Ke(async()=>{const{transactionDigest:l}=await import("./BSXmGwlb.js");return{transactionDigest:l}},[],import.meta.url),c=(await o(n)).txId,u=await fn(a.result,this.rpc.api,[...this.rpc.fallbackApis]);return u.error?_((s=u.error.code)!==null&&s!==void 0?s:-32603,(r=u.error.message)!==null&&r!==void 0?r:"Failed to broadcast transaction due to unknown error"):{success:!0,result:c}}catch{return _(5e3,"Failed to sign or broadcast tx due to unknown error")}}}const R=_(4900,"Not logged in"),xt=_(5005,"key type cannot be memo"),qt="Provider only available in browser env";class zn{constructor(t,e,s){this.vscNetId=Vt,this.getPI=this.getCurrentProviderInstance,this.connect=this.login,this.disconnect=this.logout,this.providers={},this.rpc=new rr(t,e,s),this.otherLogins={},this.eventEmitter=new cr}isBrowser(){return typeof window<"u"&&typeof window.localStorage<"u"}setPublicKey(t){typeof t<"u"?(this.publicKey=t,this.isBrowser()&&localStorage.setItem("aiohaPubKey",t)):(delete this.publicKey,this.isBrowser()&&localStorage.removeItem("aiohaPubKey"))}getPublicKey(){return this.publicKey}setup(t){this.isLoggedIn()||(t||(t={}),t.hiveauth||(t.hiveauth={name:"Aioha Generic App"}),this.registerKeychain(),this.registerLedger(),this.registerPeakVault(),this.registerMetaMaskSnap(),this.registerHiveAuth(t.hiveauth),t.hivesigner&&this.registerHiveSigner(t.hivesigner),this.loadAuth())}registerKeychain(){if(!this.isBrowser())throw new Error(qt);this.providers.keychain=new ce(this.rpc,this.eventEmitter)}registerHiveSigner(t){if(!this.isBrowser())throw new Error(qt);this.providers.hivesigner=new Rn(this.rpc,this.eventEmitter,t)}registerHiveAuth(t){if(!this.isBrowser())throw new Error(qt);this.providers.hiveauth=new bn(this.rpc,this.eventEmitter,t)}registerLedger(){if(!this.isBrowser())throw new Error(qt);this.providers.ledger=new Fn(this.rpc,this.eventEmitter)}
13registerPeakVault(){if(!this.isBrowser())throw new Error(qt);this.providers.peakvault=new Ge(this.rpc,this.eventEmitter)}registerMetaMaskSnap(){if(!this.isBrowser())throw new Error(qt);return this.providers.metamasksnap=new jn(this.rpc,this.eventEmitter),this.providers.metamasksnap.initProvider()}registerViewOnly(){this.providers.viewonly=new Kn}registerCustomProvider(t){this.providers.custom=t,this.providers.custom.setEventEmitter(this.eventEmitter)}deregisterProvider(t){return!this.providers[t]||this.isLoggedIn()?!1:(delete this.providers[t],!0)}isProviderRegistered(t){return!!this.providers[t]}isProviderEnabled(t){switch(t){case b.Keychain:return!!this.providers.keychain&&ce.isInstalled();case b.PeakVault:return!!this.providers.peakvault&&Ge.isInstalled();case b.MetaMaskSnap:return!!this.providers.metamasksnap&&this.providers.metamasksnap.isInstalled();default:return!!this.providers[t]}}getProviders(){return Object.keys(this.providers)}getCurrentProvider(){return this.currentProvider}getCurrentUser(){return this.currentProvider?this.providers[this.currentProvider].getUser():void 0}isLoggedIn(){return!!this.currentProvider}getOtherLogins(){const t={};for(let e in this.otherLogins)t[e]=this.otherLogins[e].provider;return t}getLoginExpiration(t){var e;if(this.getCurrentUser()===t)return(e=this.getPI().getLoginInfo())===null||e===void 0?void 0:e.exp;if(this.otherLogins[t])return this.otherLogins[t].exp}getCurrentProviderInstance(){if(!this.currentProvider)throw new Error("Not logged in");return this.providers[this.currentProvider]}setApi(t,e){var s;if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error("api must start from http:// or https://");this.rpc.api=t,e&&(this.rpc.fallbackApis=e);for(let r in this.providers)(s=this.providers[r])===null||s===void 0||s.setApi(t,e)}getApi(){return[this.rpc.api,...this.rpc.fallbackApis]}setChainId(t){var e;this.rpc.chainId=t;for(let s in this.providers)(e=this.providers[s])===null||e===void 0||e.setChainId(t)}getChainId(){return this.rpc.chainId}setUserAndProvider(t,e,s){const r=this.isLoggedIn();this.currentProvider=e,this.isBrowser()&&(localStorage.setItem("aiohaUsername",this.getCurrentUser()),localStorage.setItem("aiohaProvider",this.currentProvider)),this.setPublicKey(s),this.otherLogins[t]&&delete this.otherLogins[t],r?this.eventEmitter.emit("account_changed"):this.eventEmitter.emit("connect")}addOtherLogin(t,e){this.otherLogins[t]=e,this.isBrowser()&&localStorage.setItem("aiohaOtherLogins",JSON.stringify(this.otherLogins))}removeOtherLogin(t,e=!0){if(!this.otherLogins[t])throw new Error("Cannot remove non-existent login");const s=this.otherLogins[t];return delete this.otherLogins[t],this.isBrowser()&&localStorage.setItem("aiohaOtherLogins",JSON.stringify(this.otherLogins)),e&&this.eventEmitter.emit("account_changed"),s}loginCheck(t,e,s){return this.getCurrentUser()===e||this.otherLogins[e]?F(4901,"Already logged in"):this.providers[t]?!e&&t!==b.HiveSigner?F(5002,"username is required"):typeof s!="object"?F(5003,"options are required"):!s.keyType&&t!==b.HiveSigner&&t!==b.Ledger&&t!==b.ViewOnly&&t!==b.Custom?F(5003,"keyType options are required",t):{provider:b.Custom,success:!0,result:"",username:e}:F(4201,t+" provider is not registered")}async request(t){if(typeof t!="object"||typeof t.method!="string"||t.params&&typeof t.params!="object")return Promise.reject(new Rt(-32600,"Invalid request"));if(this.isLoggedIn())try{return await this.getPI().request(t)}catch(s){if(s.name!=="AiohaRpcError"||s.code!==4200)throw s}if(t.method.startsWith("aioha_api."))throw new Rt(4200,"Use AiohaJsonRpc class in extras instead");const e=await this.rpc.call(t.method,t.params);if(e.error)throw new Error(e.error);return e.result}async discoverAccounts(t,e,s){return this.providers[t]?await this.providers[t].discoverAccounts(e,s):_(4201,t+" provider is not registered")}switchUser(t){if(!this.otherLogins[t]||!this.providers[this.otherLogins[t].provider])return!1;const e=this.getCurrentUser();if(this.isLoggedIn()){if(this.getCurrentUser()===t)return!1;const n=this.getPI().getLoginInfo();if(!n)throw new Error("Failed to get current login info");this.addOtherLogin(this.getCurrentUser(),n)}const s=this.removeOtherLogin(t,!1);if(!this.providers[s.provider].loadLogin(t,s)){if(e){const n=this.removeOtherLogin(e);this.providers[n.provider].loadLogin(e,n)}return!1}return this.setUserAndProvider(t,s.provider,s.pubKey),!0}async login(t,e,s){var r;const n=this.loginCheck(t,e,s);if(!n.success)return n;let a,o;this.isLoggedIn()&&(a=this.getPI().getLoginInfo(),o=this.getCurrentUser());const c=await this.providers[t].login(e,s);return c.success&&(a&&o&&o!==e&&this.addOtherLogin(o,a),this.setUserAndProvider((r=c.username)!==null&&r!==void 0?r:e,t,c.publicKey)),c}async loginAndDecryptMemo(t,e,s){var r;const n=this.loginCheck(t,e,s);if(!n.success)return n;if(!s||typeof s.msg!="string"||!s.msg.startsWith("#"))return F(5004,"memo to decode must start with #");let a,o;this.isLoggedIn()&&(a=this.getPI().getLoginInfo(),o=this.getCurrentUser());const c=await this.providers[t].loginAndDecryptMemo(e,s);return c.success&&(a&&o&&o!==e&&this.addOtherLogin(o,a),this.setUserAndProvider((r=c.username)!==null&&r!==void 0?r:e,t)),c}loginNonInteractive(t,e,s){var r;if(this.isLoggedIn())throw new Error("already logged in");const n=this.loginCheck(t,e,s);if(!n.success)return n;if(!s.ignorePersistence&&this.loadAuth())return{success:!0,provider:this.getCurrentProvider(),username:this.getCurrentUser(),result:""};const a=this.providers[t].loginNonInteractive(e,s);return a.success&&this.setUserAndProvider((r=a.username)!==null&&r!==void 0?r:e,t,a.publicKey),a}async logout(){this.currentProvider&&await this.providers[this.currentProvider].logout(),this.handleLogout()}async logoutAll(){this.otherLogins={},this.isBrowser()&&localStorage.removeItem("aiohaOtherLogins"),await this.logout()}handleLogout(){delete this.currentProvider,this.isBrowser()&&(localStorage.removeItem("aiohaUsername"),localStorage.removeItem("aiohaProvider")),this.setPublicKey(),this.eventEmitter.emit("disconnect")}loadAuth(){if(this.isLoggedIn())return!0;
13if(this.isBrowser()){try{const r=localStorage.getItem("aiohaOtherLogins");r&&(this.otherLogins=JSON.parse(r));for(let n in this.otherLogins)typeof this.otherLogins[n].exp=="number"&&new Date().getTime()>=this.otherLogins[n].exp&&delete this.otherLogins[n]}catch{}const t=localStorage.getItem("aiohaUsername"),e=localStorage.getItem("aiohaProvider"),s=localStorage.getItem("aiohaPubKey");return!e||!t||!this.providers[e]||!this.providers[e].loadAuth(t)?!1:(s&&this.setPublicKey(s),this.currentProvider=e,this.eventEmitter.emit("connect"),!0)}return!1}async encryptMemo(t,e,s){return this.isLoggedIn()?(t.startsWith("#")||(t="#"+t),await this.getPI().encryptMemo(t,e,s)):R}async encryptMemoWithKeys(t,e,s){return this.isLoggedIn()?(t.startsWith("#")||(t="#"+t),await this.getPI().encryptMemoWithKeys(t,e,s.map(r=>r.trim()))):R}async decryptMemo(t,e){return this.isLoggedIn()?await this.getPI().decryptMemo(t,e):R}async signMessage(t,e){return this.isLoggedIn()?await this.getPI().signMessage(t,e):R}async signTx(t,e){if(this.isLoggedIn()){if(e===v.Memo)return xt}else return R;return await this.getPI().signTx(t,e)}async signAndBroadcastTx(t,e){if(this.isLoggedIn()){if(e===v.Memo)return xt}else return R;return await this.getPI().signAndBroadcastTx(t,e)}async signTxHF26(t,e){if(this.isLoggedIn()){if(e===v.Memo)return xt}else return R;return await this.getPI().signTxHF26(t,e)}async signAndBroadcastTxHF26(t,e){if(this.isLoggedIn()){if(e===v.Memo)return xt}else return R;return await this.getPI().signAndBroadcastTxHF26(t,e)}async signAndBroadcastUri(t,e){if(this.isLoggedIn()){if(e===v.Memo)return xt}else return R;let s;try{const r=An(t);s=Cn(r.tx,r.params,{ref_block_num:1234,ref_block_prefix:5678900,expiration:"2020-01-01T00:00:00",signers:[this.getCurrentUser()],preferred_signer:this.getCurrentUser()})}catch(r){return{success:!1,errorCode:-32600,error:r.toString()}}return await this.signAndBroadcastTx(s.tx.operations,e)}async vote(t,e,s){return this.isLoggedIn()?await this.getPI().vote(t,e,s):R}async voteMany(t){if(!this.isLoggedIn())return R;const e=[];for(let s in t)e.push(ar(this.getCurrentUser(),t[s].author,t[s].permlink,t[s].weight));return await this.signAndBroadcastTx(e,v.Posting)}async comment(t,e,s,r,n,a,o){return this.isLoggedIn()?(typeof a=="object"&&(a=JSON.stringify(a)),await this.getPI().comment(t,e,s,r,n,a,o)):R}async deleteComment(t){return this.isLoggedIn()?await this.getPI().deleteComment(t):R}async customJSON(t,e,s,r){if(!this.isLoggedIn())return R;if(typeof s=="object")s=JSON.stringify(s);else if(t==="memo")return xt;return await this.getPI().customJSON(t,e,s,r)}reblog(t,e,s){return this.customJSON(v.Posting,"reblog",["reblog",{account:this.getCurrentUser(),author:t,permlink:e,delete:s?"delete":void 0}],s?"Remove reblog":"Reblog")}follow(t,e){return this.customJSON(v.Posting,"follow",["follow",{follower:this.getCurrentUser(),following:t,what:e?[]:["blog"]}],e?"Unfollow":"Follow")}ignore(t){return this.customJSON(v.Posting,"follow",["follow",{follower:this.getCurrentUser(),following:t,what:["ignore"]}],"Ignore")}async claimRewards(){if(!this.isLoggedIn())return R;const t=await vs([this.getCurrentUser()],this.rpc.api,[...this.rpc.fallbackApis]);return t.error||!Array.isArray(t.result)||t.result.length===0?_(-32603,"Failed to fetch pending account rewards"):t.result[0].reward_hive_balance==="0.000 HIVE"&&t.result[0].reward_hbd_balance==="0.000 HBD"&&t.result[0].reward_vesting_balance==="0.000000 VESTS"?_(5200,"There are no pending rewards to claim"):await this.signAndBroadcastTx([["claim_reward_balance",{account:this.getCurrentUser(),reward_hive:t.result[0].reward_hive_balance,reward_hbd:t.result[0].reward_hbd_balance,reward_vests:t.result[0].reward_vesting_balance}]],v.Posting)}async transfer(t,e,s,r){return this.isLoggedIn()?await this.getPI().transfer(t,e,s,r):R}async recurrentTransfer(t,e,s,r,n,a,o){return this.isLoggedIn()?r<24?_(-32003,"recurrence must be at least 24 hours"):await this.getPI().recurrentTransfer(t,e,s,r,n,a,o):R}cancelRecurrentTransfer(t,e,s){return this.recurrentTransfer(t,0,e,24,2,s)}async stakeHive(t,e){return this.isLoggedIn()?await this.getPI().stakeHive(t,e):R}async unstakeHive(t){return this.isLoggedIn()?await this.getPI().unstakeHive(t):R}async unstakeHiveByVests(t){return this.isLoggedIn()?await this.getPI().unstakeHiveByVests(t):R}async delegateStakedHive(t,e){return this.isLoggedIn()?await this.getPI().delegateStakedHive(t,e):R}async delegateVests(t,e){return this.isLoggedIn()?await this.getPI().delegateVests(t,e):R}async voteWitness(t,e){return this.isLoggedIn()?await this.getPI().voteWitness(t,e):R}async voteProposals(t,e){return this.isLoggedIn()?await this.getPI().voteProposals(t,e):R}async setProxy(t){return this.isLoggedIn()?await this.getPI().setProxy(t):R}async clearProxy(){return await this.setProxy("")}async addAccountAuthority(t,e,s){return this.isLoggedIn()?await this.getPI().addAccountAuthority(t,e,s):R}async removeAccountAuthority(t,e){return this.isLoggedIn()?await this.getPI().removeAccountAuthority(t,e):R}async addKeyAuthority(t,e,s){return this.isLoggedIn()?await this.getPI().addKeyAuthority(t,e,s):R}async removeKeyAuthority(t,e){return this.isLoggedIn()?await this.getPI().removeKeyAuthority(t,e):R}vscSetNetId(t){this.vscNetId=t}async vscCallContract(t,e,s,r,n,a=v.Posting){return a==="memo"?xt:this.isLoggedIn()?await this.getPI().vscCallContract(t,e,s,r,n,a,this.vscNetId):R}async vscTransfer(t,e,s,r){return this.isLoggedIn()?await this.getPI().vscTransfer(t,e,s,r,this.vscNetId):R}async vscWithdraw(t,e,s,r){return this.isLoggedIn()?await this.getPI().vscWithdraw(t,e,s,r,this.vscNetId):R}async vscStake(t,e,s,r){return this.isLoggedIn()?await this.getPI().vscStake(t,e,s,r,this.vscNetId):R}async vscUnstake(t,e,s,r){return this.isLoggedIn()?await this.getPI().vscUnstake(t,e,s,r,this.vscNetId):R}on(t,e){return this.eventEmitter.on(t,e),this}once(t,e){return this.eventEmitter.once(t,e),this}off(t,e){return this.eventEmitter.off(t,e),this}}function Ks(i){return i.includes(":")?i:`hive:${i}`}function Qn(i){return`${i/1000n}.${(i%1000n).toString().padStart(3,"0")}`}var Pt,me,Et,$t,Lt,fe,et,fs,mr,zt,Fe,re;const tt=class tt{constructor(t){L(this,et);G(this,"aioha");L(this,Pt);
13L(this,me);G(this,"siteUrl");L(this,Et);L(this,$t);L(this,Lt);L(this,fe,!1);L(this,zt,null);this.aioha=new zn,D(this,Pt,t.contractId),this.siteUrl=(t.siteUrl??"https://lassecash.com").replace(/\/+$/,""),D(this,me,t.rcLimit??1500),t.keychain!==!1&&this.aioha.registerKeychain(),t.hiveAuth!==!1&&this.aioha.registerHiveAuth(t.hiveAuth??{name:"LasseCash",description:"AnCap society tools"}),t.peakVault!==!1&&this.aioha.registerPeakVault(),t.hiveSigner&&this.aioha.registerHiveSigner(t.hiveSigner),D(this,Et,t.netId??"vsc-mainnet"),D(this,$t,t.chainUrl),t.netId&&this.aioha.vscSetNetId(t.netId)}wallets(){const t={[b.Keychain]:"Hive Keychain",[b.PeakVault]:"PeakVault",[b.HiveAuth]:"HiveAuth",[b.HiveSigner]:"HiveSigner"};return Object.keys(t).map(e=>({id:e,label:t[e]??e,available:this.aioha.isProviderRegistered(e)&&this.aioha.isProviderEnabled(e)}))}restore(){return this.aioha.loadAuth(),this.aioha.isLoggedIn()?this.aioha.getCurrentUser()??null:null}get user(){return this.aioha.isLoggedIn()?this.aioha.getCurrentUser()??null:null}async login(t,e){const s=await this.aioha.login(t,e,{msg:`Sign in to LasseCash as @${e}`,keyType:v.Posting,loginTitle:"LasseCash"});if(!s.success)throw new x(s.error||"login failed",s.errorCode);const r=this.aioha.getCurrentUser();if(!r)throw new x("logged in but no user returned");return r}logout(){return this.aioha.logout()}async depositHbd(t,e="HBD"){const s=this.aioha.getCurrentUser();if(!s)throw new x("not signed in");const r=await this.aioha.transfer(tt.HBD_GATEWAY,t,e==="HIVE"?it.HIVE:it.HBD,`to=${s}`);return{ok:!!r.success,msg:r.success?"submitted":tt.hiveReason(r.error),height:0,txId:r.success&&typeof r.result=="string"?r.result:void 0}}async withdrawHbd(t,e,s="HBD"){const r=this.aioha.getCurrentUser();if(!r)throw new x("not signed in");const n=await this.aioha.vscWithdraw(e||r,t,s==="HIVE"?it.HIVE:it.HBD);return{ok:!!n.success,msg:n.success?"submitted":tt.hiveReason(n.error),height:0,txId:n.success&&typeof n.result=="string"?n.result:void 0}}async withdrawBtc(t,e){const s=this.aioha.getCurrentUser();if(!s)throw new x("not signed in");const r=JSON.stringify({net_id:w(this,Et),caller:`hive:${s}`,contract_id:tt.BTC_MAPPING_CONTRACT,action:"unmap",payload:{amount:t.toString(),to:e,deduct_fee:!0},rc_limit:1e4});return y(this,et,re).call(this,[["custom_json",{required_auths:[s],required_posting_auths:[],id:"vsc.call",json:r}]],v.Active)}async sendNative(t,e,s,r=""){if(!this.aioha.getCurrentUser())throw new x("not signed in");const n=await this.aioha.vscTransfer(t,e,s==="HIVE"?it.HIVE:it.HBD,r);return{ok:!!n.success,msg:n.success?"submitted":tt.hiveReason(n.error),height:0,txId:n.success&&typeof n.result=="string"?n.result:void 0}}async sendBtc(t,e){const s=this.aioha.getCurrentUser();if(!s)throw new x("not signed in");const r=JSON.stringify({net_id:w(this,Et),caller:`hive:${s}`,contract_id:tt.BTC_MAPPING_CONTRACT,action:"transfer",payload:{amount:e.toString(),to:t},rc_limit:2e3});return y(this,et,re).call(this,[["custom_json",{required_auths:[s],required_posting_auths:[],id:"vsc.call",json:r}]],v.Active)}async publishToHive(t){return y(this,et,fs).call(this,t)}async editOnHive(t){return y(this,et,fs).call(this,t,t.category,t.metadata??{})}async publishCommentToHive(t){var o;const e=this.aioha.getCurrentUser();if(!e)throw new x("not signed in");const s=t.parentAuthor.replace(/^hive:/,"").replace(/^@/,""),r=(o=t.tags)!=null&&o.length?t.tags.slice(0,10):["lassecash"],n=qs({author:e,permlink:t.permlink,tags:r,siteUrl:this.siteUrl,parentAuthor:s,parentPermlink:t.parentPermlink}),a=await this.aioha.comment(s,t.parentPermlink,t.permlink,"",t.body,n);if(!a.success)throw new x(a.error||"publish comment to Hive failed",a.errorCode)}async simulate(t,e,s,r,n=1e5,a){var f;const o=Ks(t),l=((f=(await(await Me(JSON.stringify({query:`query($i: SimulateContractCallsInput!) { 14 simulateContractCalls(input: $i) { success err_msg gas_used } }`,variables:{i:{tx_id:"sim",required_auths:o,calls:[...a?[{contract_id:a.contractId,action:a.action,payload:a.payload,rc_limit:n,intents:[]}]:[],{contract_id:w(this,Pt),action:e,payload:s,rc_limit:n,intents:r}]}}}),{url:w(this,$t)})).json()).data)==null?void 0:f.simulateContractCalls)??[],h=l[0];if(a&&h&&!h.success){const m=h.err_msg??"the allowance call was refused";
14return{ok:!1,msg:m,gasLimitHit:/gas_limit|cost limit/i.test(m)}}const d=l[l.length-1];if(!d)throw new x("simulation returned nothing");if(d.success)return{ok:!0,gas:d.gas_used};const g=d.err_msg??"refused";return{ok:!1,msg:g,gasLimitHit:/gas_limit|cost limit/i.test(g)}}async availableRc(t){const e=w(this,zt);if(e&&e.account===t&&Date.now()-e.at<tt.RC_CACHE_MS)return e.p;const s=y(this,et,mr).call(this,t);return D(this,zt,{account:t,p:s,at:Date.now()}),s}forgetRc(){D(this,zt,null)}async broadcastWithCall(t,e,s,r=[]){return y(this,et,re).call(this,[...t,y(this,et,Fe).call(this,e,s,v.Posting),...r.map(n=>y(this,et,Fe).call(this,n,s,v.Posting))],v.Posting)}async rawCall(t,e,s,r){return this.broadcastCalls([{action:e,payload:s,rcLimit:r,intents:[],contractId:t}],t,v.Active)}async seedNativePool(t,e,s){const r=await this.tokenContract();if(!r)return{ok:!1,height:0,msg:"token contract unknown"};const n=this.aioha.isLoggedIn()?this.aioha.getCurrentUser():null;if(!n)return{ok:!1,height:0,msg:"not signed in"};if(!/^\d+$/.test(e)||e==="0"||!(s>0))return{ok:!1,height:0,msg:"amounts must be positive"};const a=`${Math.floor(s/1e3)}.${String(s%1e3).padStart(3,"0")}`;return this.broadcastCalls([{action:"increaseAllowance",payload:JSON.stringify({spender:`contract:${t}`,amount:e}),rcLimit:1500,intents:[],contractId:r},{action:"add_liquidity",payload:JSON.stringify({amount0:String(s),amount1:e,recipient:`hive:${n}`,min_lp_out:"0"}),rcLimit:4e3,intents:[{type:"transfer.allow",args:{token:"hbd",limit:a}}],contractId:t}],t,v.Active)}async swapNativePool(t,e,s,r){const n=this.aioha.isLoggedIn()?this.aioha.getCurrentUser():null;if(!n)return{ok:!1,height:0,msg:"not signed in"};if(s<=0n)return{ok:!1,height:0,msg:"amount must be positive"};const a=`hive:${n}`,o={action:"swap",payload:JSON.stringify(e==="lc_hbd"?{asset_in:"lassecash",amount_in:s.toString(),asset_out:"hbd",to:a,min_amount_out:r.toString()}:{asset_in:"hbd",amount_in:s.toString(),asset_out:"lassecash",to:a,min_amount_out:r.toString()}),rcLimit:4e3,intents:e==="hbd_lc"?[{type:"transfer.allow",args:{token:"hbd",limit:Qn(s)}}]:[],contractId:t};if(e==="hbd_lc")return this.broadcastCalls([o],t,v.Active);const c=await this.tokenContract();return c?this.broadcastCalls([{action:"increaseAllowance",payload:JSON.stringify({spender:`contract:${t}`,amount:s.toString()}),rcLimit:1500,intents:[],contractId:c},o],t,v.Active):{ok:!1,height:0,msg:"token contract unknown"}}async broadcastCalls(t,e,s,r=[]){return y(this,et,re).call(this,[...r,...t.map(n=>y(this,et,Fe).call(this,n,n.contractId??e,s))],s)}static hiveReason(t){const e=(t??"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return e?/identical to this vote|vote is the same/i.test(e)?"you have already voted on this at that weight on Hive â move the slider to a different weight and cast again. A vote is replaced by re-voting, never removed.":/only.*vote.*once|cannot vote again|vote_regeneration/i.test(e)?"Hive is rate-limiting your votes â wait a few seconds and cast again.":/exceeded.*bandwidth|resource credits|insufficient rc/i.test(e)?"your Hive account is out of resource credits for now. Hive RC refills on its own over the next hours.":/comment.*same as before|Comment already exists/i.test(e)?"this text is identical to what you already published â change something and try again.":/missing required (posting|active) authority/i.test(e)?"your wallet did not grant the authority this needs. Sign in again, or unlock the wallet and retry.":e:"rejected"}articleOp(t){const e=this.aioha.getCurrentUser();if(!e)throw new x("not signed in");const s=["lassecash",...t.tags.filter(n=>n!=="lassecash")].slice(0,21),r=ms({author:e,permlink:t.permlink,tags:s,summary:t.summary??"",image:t.image??null,siteUrl:this.siteUrl});return["comment",{parent_author:"",parent_permlink:s[0]??"lassecash",author:e,permlink:t.permlink,title:t.title,body:t.body,json_metadata:typeof r=="string"?r:JSON.stringify(r)}]}replyOp(t){const e=this.aioha.getCurrentUser();if(!e)throw new x("not signed in");const s=t.parentAuthor.replace(/^hive:/,"").replace(/^@/,""),r=qs({author:e,permlink:t.permlink,tags:["lassecash"],siteUrl:this.siteUrl,parentAuthor:s,parentPermlink:t.parentPermlink});return["comment",{parent_author:s,parent_permlink:t.parentPermlink,author:e,permlink:t.permlink,title:"",body:t.body,json_metadata:typeof r=="string"?r:JSON.stringify(r)}]}async uploadImage(t,e){const s=new Uint8Array(await t.arrayBuffer()),r=new TextEncoder().encode("ImageSigningChallenge"),n=new Uint8Array(r.length+s.length);n.set(r,0),n.set(s,r.length);const a=JSON.stringify({type:"Buffer",data:Array.from(n)}),o=await this.aioha.signMessage(a,v.Posting);if(!o.success)throw new x(o.error||"image signing failed",o.errorCode);const c=new FormData;c.append("file",t);const u=await fetch(`https://images.hive.blog/${e}/${o.result}`,{method:"POST",body:c});if(!u.ok)throw new x(`image upload failed (${u.status})`,u.status);const l=await u.json();if(!l.url)throw new x("image server returned no url");return l.url}async tokenContract(){var t,e;if(w(this,fe))return w(this,Lt);D(this,fe,!0);try{const n=(e=(t=(await(await Me(JSON.stringify({query:'query($id: String!) { getStateByKeys(contractId: $id, keys: ["cfg_token"]) }',variables:{id:w(this,Pt)}}),{url:w(this,$t)})).json()).data)==null?void 0:t.getStateByKeys)==null?void 0:e.cfg_token;D(this,Lt,n&&n!==""?n:void 0)}catch{D(this,Lt,void 0)}return w(this,Lt)}signer(){const t=this.user;if(!t)throw new x("not logged in");return new ps(this,t,w(this,Pt),w(this,me))}};Pt=new WeakMap,me=new WeakMap,Et=new WeakMap,$t=new WeakMap,Lt=new WeakMap,fe=new WeakMap,et=new WeakSet,fs=async function(t,e,s){const r=this.aioha.getCurrentUser();if(!r)throw new x("not signed in");const n=["lassecash",...t.tags.filter(u=>u!=="lassecash")].slice(0,21),a={author:r,permlink:t.permlink,tags:n,summary:t.summary??"",image:t.image??null,siteUrl:this.siteUrl},o=s===void 0?ms(a):nn(s,a),c=await this.aioha.comment(null,e||n[0]||"lassecash",t.permlink,t.title,t.body,o);if(!c.success)throw new x(c.error||"publish to Hive failed",c.errorCode)}
14,mr=async function(t){var s;const e=Ks(t);try{const a=(s=(await(await Me(JSON.stringify({query:"query($a: String!) { getAccountRC(account: $a) { amount max_rcs } }",variables:{a:e}}),{url:w(this,$t)})).json()).data)==null?void 0:s.getAccountRC;return a&&typeof a.amount=="number"&&a.max_rcs?a.amount:tt.FREE_RC}catch{return null}},zt=new WeakMap,Fe=function(t,e,s){const r=this.aioha.getCurrentUser();if(!r)throw new x("not signed in");return["custom_json",{required_auths:s===v.Active?[r]:[],required_posting_auths:s===v.Posting?[r]:[],id:"vsc.call",json:JSON.stringify({net_id:w(this,Et),contract_id:e,action:t.action,payload:t.payload,rc_limit:t.rcLimit,intents:t.intents})}]},re=async function(t,e){this.forgetRc();const s=await this.aioha.signAndBroadcastTx(t,e);return{ok:!!s.success,msg:s.success?"submitted":tt.hiveReason(s.error),height:0,txId:s.success&&typeof s.result=="string"?s.result:void 0}},G(tt,"HBD_GATEWAY","vsc.gateway"),G(tt,"BTC_MAPPING_CONTRACT","vsc1BdrQ6EtbQ64rq2PkPd21x4MaLnVRcJj85d"),G(tt,"BTC_DUST_SATS",546n),G(tt,"FREE_RC",1e4),G(tt,"RC_CACHE_MS",2500);let We=tt;const P=class P{constructor(t,e,s,r){this.wallet=t,this.account=e,this.contractId=s,this.rcLimit=r}async magiSwap(t){if(!this.wallet.aioha.getCurrentUser())throw new x("not signed in");const s=[];return t.approve&&s.push({action:"increaseAllowance",payload:t.approve.payload,rcLimit:t.approve.rcLimit,intents:[],contractId:t.approve.contractId}),s.push({action:"execute",payload:t.payload,rcLimit:t.rcLimit,intents:t.intents}),this.wallet.broadcastCalls(s,t.router,v.Active)}depositHbd(t,e){return this.wallet.depositHbd(t,e)}withdrawBtc(t,e){return this.wallet.withdrawBtc(t,e)}sendNative(t,e,s,r){return this.wallet.sendNative(t,e,s,r)}sendBtc(t,e){return this.wallet.sendBtc(t,e)}withdrawHbd(t,e,s){return this.wallet.withdrawHbd(t,e,s)}static hbdLimit(t){const s=(BigInt(t)+99999n)/100000n,r=s/1000n,n=(s%1000n).toString().padStart(3,"0");return`${r}.${n}`}async publishAndRegister(t){const e=`${t.permlink}|${t.window}
14|${t.payoutMode}`,s=await this.sizeRc("post",e,[],P.RC_LIMITS.post);return typeof s!="number"?s:this.wallet.broadcastWithCall([this.wallet.articleOp(t)],{action:"post",payload:e,rcLimit:s,intents:[]},this.contractId,await this.sizedSideCalls(t.sideCalls))}async sizedSideCalls(t){const e=[],s=Math.min(us,te-1);for(const r of(t??[]).slice(0,s)){const n=await this.sizeRc(r.entrypoint,r.args,[],P.RC_LIMITS[r.entrypoint]??this.rcLimit);typeof n=="number"&&e.push({action:r.entrypoint,payload:r.args,rcLimit:n,intents:[]})}return e}async commentAndRegister(t){const e=t.parentAuthor.replace(/^@/,""),s=e.startsWith("hive:")?e:`hive:${e}`,r=`${t.permlink}|${s}|${t.parentPermlink}|${t.payoutMode}`,n=await this.sizeRc("comment",r,[],P.RC_LIMITS.comment);return typeof n!="number"?n:this.wallet.broadcastWithCall([this.wallet.replyOp(t)],{action:"comment",payload:r,rcLimit:n,intents:[]},this.contractId,await this.sizedSideCalls(t.sideCalls))}publishToHive(t){return this.wallet.publishToHive(t)}publishCommentToHive(t){return this.wallet.publishCommentToHive(t)}editOnHive(t){return this.wallet.editOnHive(t)}static drawMilli(t,e){const s=P.HBD_DRAW_OPS[t];if(s===void 0)return null;const r=(e.split("|")[s]??"").trim();return/^\d+$/.test(r)?Number((BigInt(r)+99999n)/100000n):null}async sizeRc(t,e,s,r){let n;const a=this.wallet.availableRc(this.account);let o;if(t in P.HBD_DRAW_OPS){o=P.RC_CEILING;const g=P.drawMilli(t,e),f=await a;if(f!==null&&g!==null){const m=Math.max(0,Math.trunc(f)-g-P.PROBE_MARGIN_MILLI);o=Math.max(r,Math.min(P.RC_CEILING,m))}else o=r}const c=await this.allowanceCall(t,e);try{n=await this.wallet.simulate(this.account,t,e,s,o,c&&{contractId:c.contractId,action:c.action,payload:c.payload})}catch{const g=await a;return g!==null&&g<r?P.rcRefusal(r,g):r}if(!n.ok)return/wasm function not found/i.test(n.msg)?{ok:!1,height:0,msg:"This page is out of date â reload it (Ctrl+Shift+R, or Cmd+Shift+R on a Mac) and try again."}:n.gasLimitHit?{ok:!1,msg:"this call would exceed the per-call gas ceiling â call advance first to close the accrual gap",height:0}:/Insufficient balance/.test(n.msg)?{ok:!1,height:0,msg:"Claiming is paused while we fix a backing error â the contract cannot pay out large claims yet. Your position is safe and recorded on chain, and nothing expires: grace runs to 29 December. The fix is queued and activates 4 October."}:t in P.HBD_DRAW_OPS&&/insufficient balance/i.test(n.msg)?{ok:!1,height:0,msg:"Not enough RC â hold more HBD on MAGI, it's free RC."}:{ok:!1,msg:n.msg,height:0};const u=Math.ceil(n.gas/P.GAS_PER_RC),l=Math.min(P.RC_CEILING,Math.max(r,u*P.RC_HEADROOM)),h=t==="advance"?0:Math.ceil(r*.6),d=await a;if(d!==null&&l>d){const g=Math.max(Math.ceil(u*1.3),h);return d<g?P.rcRefusal(g,d):d}return l}static rcRefusal(t,e){const s=(Math.ceil((t-e)/10)/100).toFixed(2);return{ok:!1,height:0,msg:`Not enough resource credits (needs ~${t.toLocaleString()}, you have ${e.toLocaleString()}). Deposit about ${s} more HBD to your MAGI balance â Wallet â Move funds between Hive and MAGI â then try again; it takes effect immediately.`}}async claimAllOf(t,e){const s=P.ACTIVE_OPS.has(t)?v.Active:v.Posting,r=P.RC_LIMITS[t]??this.rcLimit,n=e.slice(0,P.MaxClaimAllBatch),a=[];let o=null;for(const h of n){const d=String(h),g=await this.sizeRc(t,d,[],r);if(typeof g!="number"){a.length===0&&(o=g);break}a.push({action:t,payload:d,rcLimit:g,intents:[]})}if(a.length===0)return o??{ok:!1,height:0,msg:"nothing to claim"};let c={ok:!1,height:0,msg:"nothing to claim"},u=0;for(let h=0;h<a.length;h+=te){h>0&&await new Promise(g=>setTimeout(g,3500));const d=a.slice(h,h+te);if(c=await this.wallet.broadcastCalls(d,this.contractId,s),!c.ok)return u>0?{...c,msg:`claimed ${u} of ${e.length}, then: ${c.msg}`}:c;u+=d.length}return e.length-u>0?{...c,msg:`claimed ${u} of ${e.length} â the rest refused for RC and can be claimed once it recovers, or after depositing more HBD`}:c}async allowanceCall(t,e){const s=P.TOKEN_DEBIT_OPS[t];if(s===void 0)return;const r=await this.wallet.tokenContract();if(!r)return;const n=(e.split("|")[s]??"0").trim();if(!(!/^\d+$/.test(n)||n==="0"))return{action:"increaseAllowance",payload:JSON.stringify({spender:`contract:${this.contractId}`,amount:n}),rcLimit:P.ALLOWANCE_RC,intents:[],contractId:r}}async submit(t,e,s){const r=P.ACTIVE_OPS.has(t)?v.Active:v.Posting,
14n=P.HBD_DRAW_OPS[t],a=n===void 0?[]:[{type:"transfer.allow",args:{token:"hbd",limit:P.hbdLimit(e.split("|")[n]??"0")}}],o=[],c=await this.allowanceCall(t,e);c&&o.push(c);const u=(s==null?void 0:s.rcLimit)??P.RC_LIMITS[t]??this.rcLimit,l=Math.max(0,te-1-o.length),h=((s==null?void 0:s.preCalls)??[]).slice(0,l),d=Math.max(0,l-h.length),g=((s==null?void 0:s.sideCalls)??[]).slice(0,Math.min(us,d)),[f,m,p]=await Promise.all([Promise.all(h.map($=>this.sizeRc($.entrypoint,$.args,[],P.RC_LIMITS[$.entrypoint]??this.rcLimit))),this.sizeRc(t,e,a,u),Promise.all(g.map($=>this.sizeRc($.entrypoint,$.args,[],P.RC_LIMITS[$.entrypoint]??this.rcLimit)))]);for(const[$,K]of h.entries()){const Z=f[$];if(typeof Z!="number")break;o.push({action:K.entrypoint,payload:K.args,rcLimit:Z,intents:[]})}if(typeof m!="number"){if(o.length>0&&/accrual is behind|call advance/i.test(m.msg)){const $=await this.wallet.broadcastCalls(o,this.contractId,r);return $.ok?{...$,ok:!1,msg:`the chain is catching up on matured mints â this transaction advanced it ${o.length} step${o.length>1?"s":""}; press again`}:$}return m}const k=[];for(const[$,K]of g.entries()){const Z=p[$];typeof Z=="number"&&k.push({action:K.entrypoint,payload:K.args,rcLimit:Z,intents:[]})}const I=[];if(t==="vote"){const[$="",K="",Z="0"]=e.split("|");I.push(["vote",{voter:this.account.replace(/^hive:/,""),author:$.replace(/^hive:/,""),permlink:K,weight:Math.max(0,Math.min(100,Number(Z)))*100}])}if(o.length>0||k.length>0||I.length>0)return this.wallet.broadcastCalls([...o,{action:t,payload:e,rcLimit:m,intents:a},...k],this.contractId,r,I);this.wallet.forgetRc();const E=await this.wallet.aioha.vscCallContract(this.contractId,t,e,m,a,r);return{ok:!!E.success,msg:E.success?E.result??"submitted":We.hiveReason(E.error),height:0,txId:E.success&&typeof E.result=="string"?E.result:void 0}}};G(P,"ACTIVE_OPS",new Set(["transfer","burn","mint","claim_mint","good_accounting","fund","promote_post","add_liquidity","remove_liquidity","claim_pool","swap_lassecash_hbd","swap_hbd_lassecash","migrate","migrate_batch","claim_migration"])),G(P,"RC_LIMITS",{transfer:2500,burn:600,fund:1500,settle:2e3,advance:1e4,mint:7e3,claim_mint:7e3,sweep_mint:7e3,good_accounting:800,set_duration:400,settle_pending:6e3,promote:3e3,set_param:3e3,post:3e3,comment:5e3,promote_post:2500,vote:7e3,payout:4e3,claim_curation:1200,sweep_curation:1200,add_liquidity:4e3,remove_liquidity:4e3,claim_pool:4e3,sweep_tranche:4e3,swap_lassecash_hbd:3e3,
14swap_hbd_lassecash:3e3,claim_migration:9500,record_burn:1e3}),G(P,"HBD_DRAW_OPS",{add_liquidity:1,swap_hbd_lassecash:0}),G(P,"TOKEN_DEBIT_OPS",{transfer:1,burn:0,fund:1,mint:0,promote_post:2,add_liquidity:0,swap_lassecash_hbd:0}),G(P,"ALLOWANCE_RC",1e3),G(P,"GAS_PER_RC",1e5),G(P,"RC_HEADROOM",3),G(P,"RC_CEILING",3e4),G(P,"PROBE_MARGIN_MILLI",1e3),G(P,"MaxClaimAllBatch",12);let ps=P;function N(...i){return i.map(String).join("|")}function Re(i){return z(BigInt(i||"0"))}var j,A,vt,Qt,fr,pr,Yt,ne,U;const Je=class Je{constructor(t){L(this,A);G(this,"backend");L(this,j);L(this,Qt,null);L(this,Yt,new Map);this.backend=t.backend,D(this,j,t.signer)}get account(){var t;return((t=w(this,j))==null?void 0:t.account)??null}setSigner(t){D(this,j,t)}chain(){return this.backend.chain()}accountOf(t){return this.backend.account(t)}state(t){return this.backend.state(t)}activity(t=2e3){return this.backend.activity?this.backend.activity(t):Promise.resolve([])}txStatus(t){return this.backend.txStatus(t)}async posts(t=50){const e=await this.backend.posts(t);return this.notePayable(e),e}postVotes(t,e){return this.backend.postVotes(t,e)}comments(t,e){return this.backend.comments(t,e)}governance(t){return this.backend.governance(t)}async migrationRoot(){const e=(await this.backend.state(["cfg_migroot"])).cfg_migroot;return e||null}async migrationRecord(t){const e=`mig_${t}`,r=(await this.backend.state([e]))[e];if(!r)return null;const n=r.split("|");return n.length===3&&n[0]==="burned"?{burned:!0,liquid:Re(n[1]),staked:Re(n[2])}:n.length===2?{burned:!1,liquid:Re(n[0]),staked:Re(n[1])}:{burned:!1,liquid:"0.00000000",staked:"0.00000000"}}content(t,e){return this.backend.content(t,e)}async publish(t){const e=y(this,A,vt).call(this);return this.backend.publish({permlink:t.permlink??"",title:t.title,body:t.body,summary:t.summary??"",tags:t.tags??[],window:t.window,payoutMode:t.payoutMode??0,signer:e,sideCalls:y(this,A,ne).call(this),sender:e.account})}async editPost(t){const e=y(this,A,vt).call(this);return this.backend.editPost({permlink:t.permlink,title:t.title,body:t.body,summary:t.summary??"",tags:t.tags??[],...t.category?{category:t.category}:{},...t.metadata?{metadata:t.metadata}:{},signer:e,sender:e.account})}me(){return this.backend.account(y(this,A,vt).call(this).account)}async openMints(t){return(await this.backend.account(t)).mints.filter(s=>!s.ended)}async mintsNeedingAttention(t){return(await this.openMints(t)).filter(s=>s.mature||s.bleed_remaining_pct!=="1.00000000")}async openTranches(t){return(await this.backend.account(t)).tranches.filter(s=>!s.closed)}async postPayout(t,e){const s=this.backend;if(!s.payoutLedger)return null;const r=`${t.startsWith("hive:")?t:`hive:${t}`}|${e}`,n=(await s.payoutLedger()).get(r);return n?{author:z(BigInt(n.units)),txId:n.txId}:null}async poolTrades(t=500){const[e,s]=await Promise.all([this.backend.poolOps(t),this.chain()]),r=[];let n=0n,a=0n;const o=g=>{if(n<=0n||a<=0n||!g)return null;try{return Wr(s.genesis_height,g,n.toString(),a.toString())}catch{return null}},c=()=>{if(n<=0n||a<=0n)return"0.00000000";try{return jr(H("1").toString(),n.toString(),a.toString())??"0.00000000"}catch{return"0.00000000"}};let u=0n;const l=new Map,h=new Map;for(const g of e){const f=g.payload.split("|");if(g.action==="add_liquidity"){const E=H(z(BigInt(f[0]||"0"))),$=Qs(E.toString(),n.toString(),a.toString(),u.toString()),K=$.isFirstDeposit?H(z(BigInt(f[1]||"0"))):H($.hbdNeeded),Z=$.isFirstDeposit?E:H($.shares);n+=E,a+=K,u+=Z;const wt=(h.get(g.signer)??0)+1;h.set(g.signer,wt),l.set(`${g.signer}_${wt}`,Z),r.push({time:g.time,height:g.height,side:$.isFirstDeposit?"open":"deposit",amountIn:z(E),amountOut:z(K),lcReserve:z(n),hbdReserve:z(a),price:c(),shareHbd:o(g.height),trader:g.signer});continue}if(g.action==="remove_liquidity"){const E=`${g.signer}_${(f[0]||"").trim()}`,$=l.get(E)??0n;if($<=0n)continue;const K=zr($.toString(),u.toString(),n.toString(),a.toString()),Z=H(K.lc),wt=H(K.hbd);n-=Z,a-=wt,u-=$,l.delete(E),r.push({time:g.time,height:g.height,side:"withdraw",amountIn:z(Z),amountOut:z(wt),lcReserve:z(n),hbdReserve:z(a),price:c(),shareHbd:o(g.height),trader:g.signer});continue}const m=Cr(g.action)==="swap_lassecash_hbd",p=BigInt(f[0]||"0");if(p<=0n||n<=0n||a<=0n)continue;
14const k=zs((m?n:a).toString(),(m?a:n).toString(),p.toString());if(!k.ok)continue;const I=H(k.amountOut);m?(n+=p,a-=I):(a+=p,n-=I),r.push({time:g.time,height:g.height,side:m?"sell":"buy",amountIn:z(p),amountOut:k.amountOut,lcReserve:z(n),hbdReserve:z(a),price:c(),shareHbd:o(g.height),trader:g.signer})}const d=r.length>0&&n===H(s.amm_lc)&&a===H(s.amm_hbd);return{trades:r,reconciled:d}}async quoteSwap(t,e){return this.backend.quoteSwap(t,Y(e))}async quoteMint(t,e){return this.backend.quoteMint(Y(t),e)}async quoteLiquidity(t){return this.backend.quoteLiquidity(Y(t))}async transfer(t,e,s=""){const r=t.trim().replace(/^@/,""),n=r.includes(":")?r:`hive:${r}`,a=s.replace(/[|\r\n]+/g," ").trim().slice(0,200);return y(this,A,U).call(this,O.Transfer,a?N(n,Y(e),a):N(n,Y(e)))}async burn(t){return y(this,A,U).call(this,O.Burn,N(Y(t)))}async fund(t,e){return y(this,A,U).call(this,O.Fund,N(t,Y(e)))}async claimMigration(t,e,s,r){return y(this,A,U).call(this,O.ClaimMigration,N(t,e,s.join(",")),r!=null&&r.cheap?{rcLimit:2500}:void 0)}async recordBurn(t,e,s,r){return y(this,A,U).call(this,O.RecordBurn,N(t,e,s,r.join(",")))}warmCatchUp(){this.catchUp().catch(()=>{})}catchUp(t=8){const e=w(this,Qt);if(e&&e.max===t&&Date.now()-e.at<Je.CATCHUP_TTL_MS)return e.p;const s=y(this,A,fr).call(this,t);return D(this,Qt,{at:Date.now(),max:t,p:s}),s}async mint(t,e){return y(this,A,U).call(this,O.Mint,N(Y(t),e),{preCalls:await this.catchUp()})}async claimMint(t){return y(this,A,U).call(this,O.ClaimMint,N(t),{preCalls:await this.catchUp()})}async claimAllMintRewards(){const t=y(this,A,vt).call(this),s=(await this.mintsNeedingAttention(t.account)).filter(n=>n.mature).map(n=>n.id);if(s.length===0)return{ok:!1,height:0,msg:"nothing to claim"};if(t.claimAllOf)return t.claimAllOf(O.ClaimMint,s);let r={ok:!1,height:0,msg:"nothing to claim"};for(const n of s)if(r=await this.claimMint(n),!r.ok)return r;return r}async armGoodAccounting(t){return y(this,A,U).call(this,O.GoodAccounting,N(t))}async setMintDuration(t){return y(this,A,U).call(this,O.SetDuration,N(Math.round(t)))}async settlePending(t){return y(this,A,U).call(this,O.SettlePending,N(t??""),{preCalls:await this.catchUp()})}async post(t,e){return y(this,A,U).call(this,O.Post,N(t,e))}async comment(t){const e=y(this,A,vt).call(this);return this.backend.publishComment({permlink:rn(t.parentAuthor,t.parentPermlink),body:t.body,parentAuthor:t.parentAuthor,parentPermlink:t.parentPermlink,payoutMode:t.payoutMode??0,signer:e,sideCalls:y(this,A,ne).call(this),sender:e.account})}async promotePost(t,e,s){return y(this,A,U).call(this,O.PromotePost,N(t,e,Y(s)))}async vote(t,e,s){return y(this,A,U).call(this,O.Vote,N(t,e,s),{sideCalls:y(this,A,ne).call(this)})}notePayable(t){for(const e of t){const s=`${e.author}/${e.permlink}`;e.payable&&!e.paid_out?w(this,Yt).set(s,{author:e.author,permlink:e.permlink}):w(this,Yt).delete(s)}}async unvote(t,e){return y(this,A,U).call(this,O.Vote,N(t,e,0),{sideCalls:y(this,A,ne).call(this)})}async payout(t,e){return y(this,A,U).call(this,O.Payout,N(t,e))}async claimCuration(t,e,s=""){return y(this,A,U).call(this,O.ClaimCuration,N(t,e,s))}async addLiquidity(t,e){return y(this,A,U).call(this,O.AddLiquidity,N(Y(t),Y(e)))}async removeLiquidity(t){return y(this,A,U).call(this,O.RemoveLiquidity,N(t))}async claimPoolRewards(t){return y(this,A,U).call(this,O.ClaimPool,N(t))}async claimAllPoolRewards(){const t=y(this,A,vt).call(this),s=(await this.openTranches(t.account)).filter(n=>Number(n.pending_reward)>0).map(n=>n.id);if(s.length===0)return{ok:!1,height:0,msg:"nothing to claim"};if(t.claimAllOf)return t.claimAllOf(O.ClaimPool,s);let r={ok:!1,height:0,msg:"nothing to claim"};for(const n of s)if(r=await this.claimPoolRewards(n),!r.ok)return r;return r}async swap(t,e,s){const r=t==="lc_hbd"?O.SwapLassecashHbd:O.SwapHbdLassecash;return y(this,A,U).call(this,r,N(Y(e),Y(s)))}async promote(t){return y(this,A,U).call(this,O.Promote,N(t??""))}async setParam(t,e){return y(this,A,U).call(this,O.SetParam,N(t,e))}async depositHbd(t,e="HBD"){var s;if(!((s=w(this,j))!=null&&s.depositHbd))throw new x("moving funds needs a wallet");return w(this,j).depositHbd(Number(t),e)}async withdrawHbd(t,e,s="HBD"){var r;if(!((r=w(this,j))!=null&&r.withdrawHbd))throw new x("moving funds needs a wallet");return w(this,j).withdrawHbd(Number(t),e,s)}async quoteMagi(t,e,s){const r=Tr(t,e);if(!r||!this.backend.magiPoolReserves)return null;const n=await this.backend.magiPoolReserves(r.contractId);if(!n)return null;const a=r.asset0===t,o=a?n.r0:n.r1,c=a?n.r1:n.r0,u=Ze(s||"0",Nt[t]??1000n),l=Pr(o,c,u,r.feeBps,Nt[e]??1000n);return l?{...l,pool:r,reserveIn:o,reserveOut:c}:null}async magiSwap(t,e,s,r){var c;if(!((c=w(this,j))!=null&&c.magiSwap))throw new x("swapping needs a wallet");const n=await this.quoteMagi(t,e,s);if(!n)throw new x("no quote â the pool could not be read");const a=BigInt(Math.round(Math.max(.1,Math.min(50,r))*100)),o=n.amountOutUnits*(10000n-a)/10000n;if(o<=0n)throw new x("amount too small to swap");return w(this,j).magiSwap({router:n.pool.router,payload:$r({assetIn:t,assetOut:e,amountInUnits:n.amountInUnits,minOutUnits:o,recipient:ts(this.account??"")}),intents:[Er(t,n.amountInUnits)],rcLimit:3e3,...$s[t]?{approve:{contractId:$s[t],payload:JSON.stringify({spender:`contract:${n.pool.router}`,amount:n.amountInUnits.toString()}),rcLimit:800}}:{}})}async withdrawBtc(t,e){var n;if(!((n=w(this,j))!=null&&n.withdrawBtc))throw new x("withdrawing BTC needs a wallet");const s=e.trim();if(!s)throw new x("enter a Bitcoin address");const r=Ze(t||"0",Nt.BTC);
14if(r<Rs)throw new x(`below Bitcoin's dust limit â ${Rs} satoshis (0.00000546 BTC) is the smallest spendable output`);return w(this,j).withdrawBtc(r,s)}async sendAsset(t,e,s,r=""){var o,c;const n=e.trim().replace(/^@/,"");if(!n)throw new x("enter an account name");const a=t.toUpperCase();if(a==="LASSECASH"||a==="LC")return this.transfer(n,s,r);if(a==="HBD"||a==="HIVE"){if(!((o=w(this,j))!=null&&o.sendNative))throw new x("sending needs a wallet");return w(this,j).sendNative(ts(n),Number(s),a,r)}if(a==="BTC"){if(!((c=w(this,j))!=null&&c.sendBtc))throw new x("sending needs a wallet");const u=Ze(s||"0",Nt.BTC);if(u<=0n)throw new x("enter an amount");return w(this,j).sendBtc(ts(n),u)}throw new x(`cannot send ${t}`)}async allTranches(){const[t,e]=await Promise.all([this.backend.poolOps(500),this.chain()]),s=new Map,r=[];for(const c of t){if(c.action!=="add_liquidity"||!c.signer)continue;const u=(s.get(c.signer)??0)+1;s.set(c.signer,u),r.push({owner:c.signer,id:u})}if(!r.length)return[];const n=await this.state(r.map(c=>`lp_${c.owner}_${c.id}`)),a=H(e.amm_shares??"0"),o=[];for(const c of r){const u=n[`lp_${c.owner}_${c.id}`];if(!u)continue;const l=u.split("|"),h=BigInt(l[0]||"0");if(BigInt(l[2]||"0")<=0n||h<=0n)continue;const g=js({shares:l[0]??"0",startHeight:Number(l[1]??0),weight:l[2]??"0",accStart:l[4]??"0",height:e.height,totalShares:H(e.amm_shares??"0").toString(),lcReserve:H(e.amm_lc??"0").toString(),hbdReserve:H(e.amm_hbd??"0").toString(),poolLiq:"0",accSeen:"0",accHeld:"0",acc:"0",totalWeight:"0"});o.push({owner:c.owner.replace(/^hive:/,""),id:c.id,shares:z(h),ageDays:g.age_days,loyalty:g.loyalty,valueLc:g.value_lc,valueHbd:g.value_hbd,share:a>0n?Number(h)/Number(a):0})}return o.sort((c,u)=>u.share-c.share)}async btcBalance(t){const e=t??this.account;if(!e||!this.backend.mappedBalance)return null;const s=await this.backend.mappedBalance(Lr,e);return s===null?null:ws(s,Nt.BTC)}accountOps(t=30){const e=this.account;return!e||!this.backend.accountOps?Promise.resolve([]):this.backend.accountOps(e,t)}resourceCredits(t){const e=t??this.account;return!e||!this.backend.resourceCredits?Promise.resolve(null):this.backend.resourceCredits(e)}hiveBalances(t){const e=t??this.account;return!e||!this.backend.hiveBalances?Promise.resolve(null):this.backend.hiveBalances(e)}hiveResourceCredits(t){const e=t??this.account;return!e||!this.backend.hiveResourceCredits?Promise.resolve(null):this.backend.hiveResourceCredits(e)}async hasRcHeadroom(t=.25){const e=await this.resourceCredits();return!e||e.max<=0?!0:e.amount/e.max>t}async sweepCuration(t,e){return y(this,A,U).call(this,"sweep_curation",N(t,e))}async settle(){return y(this,A,U).call(this,O.Settle,"")}async advanceDays(t){return this.backend.advanceDays?this.backend.advanceDays(t):null}};j=new WeakMap,A=new WeakSet,vt=function(){if(!w(this,j))throw new x("not signed in");return w(this,j)},Qt=new WeakMap,fr=async function(t){try{const e=mt(),s=Number(e.heightsPerDay),[r,n]=await Promise.all([this.backend.state(["acc_day","cfg_genesis","cfg_settled"]),y(this,A,pr).call(this)]),a=Number(r.cfg_genesis||0);if(!a||!s)return[];const o=Math.floor((n-a)/s),c=Number(r.acc_day||0);if(c>=o)return[];const u=[];for(let m=c;m<=o&&u.length<64;m++)u.push(`explc_${m}`);const l=await this.backend.state(u);let h=0;for(const m of u)h+=Number(l[m]||0);const d=h*e.expiryChunkSize,g=Math.ceil(d/e.maxRetirePerWalk)+1,f=Math.min(t,Math.max(1,g));return Array.from({length:f},()=>({entrypoint:"advance",args:""}))}catch{return[]}},pr=async function(){const t=this.backend;if(typeof t.height=="function")try{return await t.height()}catch{}return(await this.backend.chain()).height},Yt=new WeakMap,ne=function(){const t=[];for(const e of w(this,Yt).values()){if(t.length>=us)break;t.push({entrypoint:O.Payout,args:N(e.author,e.permlink)})}return t},U=async function(t,e,s){return D(this,Qt,null),y(this,A,vt).call(this).submit(t,e,s)},G(Je,"CATCHUP_TTL_MS",5e3);let ys=Je;const Ss="vsc1Be4TTjUiHgzhHAfqFn6s3PDAExH2X59fXV",Yn=Ss!=="",Xn=new Yr({contractId:Ss}),bt=typeof window<"u"?new We({contractId:Ss,netId:"vsc-mainnet",chainUrl:"https://api.vsc.eco/api/v1/graphql",siteUrl:Ar}):null,ct=new ys({backend:Xn});function Zn(i){const t=(i??"").toLowerCase(),e=i?` (${i})`:"";return t.includes("cost limit")||t.includes("gas_limit")?"Not enough resource credits. More HBD on MAGI fixes it instantly.":t.includes("minimum rc")||t.includes("rcs available")?"Out of resource credits. More HBD on MAGI fixes it instantly.":t.includes("insufficient balance")&&t.includes("ledger")?`MAGI would not release the HB
14D for this. Your HBD is also your resource credits, so not all of it can go out at once â try a smaller amount, or deposit more.${e}`:t.includes("below the minimum required")?"The chain refused this swap due to slippage.":t.includes("no caller intent")?`This call needed permission to draw HBD and the wallet did not grant it.${e}`:i?`The chain refused this: ${i}`:"The chain refused this call."}var pe,ye,we,_e,ve,be,ke,Se,Ie,It,yr,wr,_r,Ae,Xt;class ti{constructor(){L(this,It);L(this,pe,ht(null));L(this,ye,ht(null));L(this,we,ht(null));L(this,_e,ht(!1));L(this,ve,ht(null));L(this,be,ht(0));L(this,ke,ht(!1));L(this,Se,ht(!1));L(this,Ie,ht(null));L(this,Ae,ht(!1));L(this,Xt,0)}get info(){return dt(w(this,pe))}set info(t){gt(w(this,pe),t,!0)}get me(){return dt(w(this,ye))}set me(t){gt(w(this,ye),t,!0)}get account(){return dt(w(this,we))}set account(t){gt(w(this,we),t,!0)}get ready(){return dt(w(this,_e))}set ready(t){gt(w(this,_e),t,!0)}get error(){return dt(w(this,ve))}set error(t){gt(w(this,ve),t,!0)}get failures(){return dt(w(this,be))}set failures(t){gt(w(this,be),t,!0)}get outage(){return this.error!==null&&(this.info===null||this.failures>=2)}get busy(){return dt(w(this,ke))}set busy(t){gt(w(this,ke),t,!0)}get confirming(){return dt(w(this,Se))}set confirming(t){gt(w(this,Se),t,!0)}get rc(){return dt(w(this,Ie))}set rc(t){gt(w(this,Ie),t,!0)}
14async init(){try{Hr({url:"https://api.vsc.eco/api/v1/graphql"}),await Promise.all([Ur("/engine.wasm").then(()=>{this.ready=Br()}),y(this,It,yr).call(this)])}catch(t){this.error=t instanceof Error?t.message:String(t)}}async refresh(){try{this.info=await ct.chain(),this.account&&(this.me=await ct.accountOf(this.account)),this.account?ct.resourceCredits().then(t=>this.rc=t).catch(()=>{}):this.rc=null,this.error=null,this.failures=0}catch(t){this.error=t instanceof Error?t.message:String(t),this.failures++}y(this,It,wr).call(this)}async signInWithWallet(t,e){if(!bt)throw new Error("wallet mode is not enabled");const s=await bt.login(t,e);this.account=`hive:${s}`,ct.setSigner(bt.signer()),await this.refresh()}async signIn(t){const e=t.startsWith("hive:")?t:`hive:${t}`;throw this.account=e,new Error("dev sign-in is disabled against a real chain")}signOut(){bt&&bt.logout(),D(this,Xt,0),this.account=null,this.me=null,ct.setSigner(void 0),localStorage.removeItem("lassecash:account")}async submit(t,e){var s;this.busy=!0;try{const r=JSON.stringify(this.me),n=(s=this.me)==null?void 0:s.hbd,a=await t();if(!a.ok)return await this.refresh(),a.msg;if(Yn&&a.txId){const o=await this.awaitVerdict(a.txId,r);return o===null&&(e!=null&&e.movesHbd)&&await y(this,It,_r).call(this,n),o}return await this.refresh(),null}catch(r){return await this.refresh(),r instanceof Error?r.message:String(r)}finally{this.busy=!1}}async awaitVerdict(t,e){this.confirming=!0;try{let s={status:"PENDING"};for(let r=0;r<24;r++){await new Promise(n=>setTimeout(n,1e4));try{s=await ct.txStatus(t)}catch{}if(s.status==="CONFIRMED"||s.status==="FAILED")break}for(let r=0;r<3&&s.status==="FAILED"&&!s.error;r++){await new Promise(n=>setTimeout(n,1e4));try{s=await ct.txStatus(t)}catch{}}if(await this.refresh(),s.status==="FAILED")return Zn(s.error);if(s.status!=="CONFIRMED")return"Still waiting for MAGI to include this transaction â the figures update when it lands.";for(let r=0;r<6&&JSON.stringify(this.me)===e;r++)await new Promise(n=>setTimeout(n,1e4)),await this.refresh();return await new Promise(r=>setTimeout(r,1e4)),await this.refresh(),null}finally{this.confirming=!1}}get settleStoppedForRc(){return dt(w(this,Ae))}set settleStoppedForRc(t){gt(w(this,Ae),t,!0)}async settleOwed(t=12){var e,s;if(this.account){this.settleStoppedForRc=!1;for(let r=0;r<t;r++){const n=((e=this.me)==null?void 0:e.pending_curation)??0;if(n===0)return;if(!await ct.hasRcHeadroom(.25)){this.settleStoppedForRc=!0;return}try{if(!(await ct.settlePending()).ok)return}catch{return}if(await this.refresh(),(((s=this.me)==null?void 0:s.pending_curation)??0)>=n)return}}}async advanceDays(t){this.busy=!0;try{await ct.advanceDays(t),await this.refresh()}finally{this.busy=!1}}}pe=new WeakMap,ye=new WeakMap,we=new WeakMap,_e=new WeakMap,ve=new WeakMap,be=new WeakMap,ke=new WeakMap,Se=new WeakMap,Ie=new WeakMap,It=new WeakSet,yr=async function(){await this.refresh(),this.error&&(await new Promise(t=>setTimeout(t,1200)),await this.refresh())},wr=function(){var e;const t=((e=this.info)==null?void 0:e.epoch)??0;!this.account||t===0||t===w(this,Xt)||(D(this,Xt,t),this.settleOwed())},_r=async function(t){var e;for(let s=0;s<6;s++){if(((e=this.me)==null?void 0:e.hbd)!==t)return;await new Promise(r=>setTimeout(r,5e3)),await this.refresh()}},Ae=new WeakMap,Xt=new WeakMap;const cs=new ti;function bi(){if(bt){const t=bt.restore();t&&(cs.account=`hive:${t}`,ct.setSigner(bt.signer()),cs.refresh());return}const i=localStorage.getItem("lassecash:account");i&&cs.signIn(i)}function ki(i,t){return xe(i,{decimals:t??ei(i)})}function ei(i){const t=Math.abs(Number(i));return Number.isFinite(t)?t>=1e3?0:t>=100?1:t>=10?2:3:3}function Si(i){const t=Number(i.split(".")[0]??"0");return Math.abs(t)>=1e6?`${(t/1e6).toFixed(2)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}k`:xe(i,{decimals:2})}function Ii(i){return xe(z(BigInt(i)),{decimals:3})}function Ai(i){return`${xe(i,{decimals:2,group:!1})}x`}function xi(i,t=2){return`${xe(i,{decimals:t,group:!1})}%`}function Ci(i,t=1){return`${(Number(i)*100).toFixed(t)}%`}function Ti(i){if(i<=0)return"now";const t=(a,o)=>`${a} ${o}${a===1?"":"s"}`,e=a=>a-Math.floor(a)>=.9?Math.ceil(a):Math.floor(a),s=e(i/28800);if(s>=365){let a=Math.floor(s/365),o=Math.floor(s%365/30);return o>=12&&(a+=1,o=0),o>=1?`${t(a,"year")} ${t(o,"month")}`:t(a,"year")}if(s>=1)return t(s,"day");const r=e(i%28800/1200);if(r>=1)return t(r,"hour");const n=e(i%1200/20);return n>=1?t(n,"minute"):"under a minute"}function Pi(i){return new Date(i).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Ei(i){return i.replace(/^hive:/,"@")}export{xi as A,di as B,Or as C,Ss as D,Me as E,vi as F,mi as G,ci as H,wi as I,yi as J,Ii as K,Ms as L,bi as M,ws as N,Nt as O,li as P,gi as Q,hi as R,Dr as S,Gr as T,Wr as U,ui as W,Vr as a,mt as b,ct as c,cs as d,Kr as e,ki as f,z as g,Ti as h,Ei as i,Hs as j,ai as k,jr as l,H as m,pi as n,Si as o,Qr as p,Ci as q,Qs as r,Pi as s,Y as t,oi as u,fi as v,bt as w,zs as x,Ai as y,_i as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.