@ecency/sdk 2.3.53 → 2.3.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {QueryClient,useQuery,useInfiniteQuery,useMutation,queryOptions,infiniteQueryOptions,useQueryClient}from'@tanstack/react-query';import {hexToBytes,bytesToHex}from'@noble/hashes/utils.js';import {ripemd160}from'@noble/hashes/legacy.js';import Jr from'bs58';import {secp256k1}from'@noble/curves/secp256k1.js';import {sha256,sha512}from'@noble/hashes/sha2.js';import {cbc}from'@noble/ciphers/aes.js';import Mn from'hivesigner';var oi=Object.defineProperty;var ut=(e,t)=>{for(var r in t)oi(e,r,{get:t[r],enumerable:true});};var pt=new ArrayBuffer(0),lt=null,dt=null;function ii(){return lt||(typeof TextEncoder<"u"?lt=new TextEncoder:lt={encode(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<128)t.push(n);else if(n<2048)t.push(192|n>>6,128|n&63);else if(n>=55296&&n<=56319&&r+1<e.length){let o=e.charCodeAt(++r);n=65536+((n&1023)<<10)+(o&1023),t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),lt}function jr(){return dt||(typeof TextDecoder<"u"?dt=new TextDecoder:dt={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n<t.length;){let o=t[n],i;o<128?(i=o,n+=1):(o&224)===192?(i=(o&31)<<6|t[n+1]&63,n+=2):(o&240)===224?(i=(o&15)<<12|(t[n+1]&63)<<6|t[n+2]&63,n+=3):(i=(o&7)<<18|(t[n+1]&63)<<12|(t[n+2]&63)<<6|t[n+3]&63,n+=4),i<=65535?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296+(i>>10),56320+(i&1023)));}return r}}),dt}var q=class e{static LITTLE_ENDIAN=true;static BIG_ENDIAN=false;static DEFAULT_CAPACITY=16;static DEFAULT_ENDIAN=e.BIG_ENDIAN;buffer;view;offset;markedOffset;limit;littleEndian;constructor(t=e.DEFAULT_CAPACITY,r=e.DEFAULT_ENDIAN){this.buffer=t===0?pt:new ArrayBuffer(t),this.view=t===0?new DataView(pt):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new e(t,r)}static concat(t,r){let n=0;for(let a=0;a<t.length;++a){let u=t[a];if(u instanceof e)n+=u.limit-u.offset;else if(u instanceof Uint8Array)n+=u.length;else if(u instanceof ArrayBuffer)n+=u.byteLength;else if(Array.isArray(u))n+=u.length;else throw TypeError("Illegal buffer")}if(n===0)return new e(0,r);let o=new e(n,r),i=new Uint8Array(o.buffer),s=0;for(let a=0;a<t.length;++a){let u=t[a];u instanceof e?(i.set(new Uint8Array(u.buffer,u.offset,u.limit-u.offset),s),s+=u.limit-u.offset):u instanceof Uint8Array?(i.set(u,s),s+=u.length):u instanceof ArrayBuffer?(i.set(new Uint8Array(u),s),s+=u.byteLength):(i.set(u,s),s+=u.length);}return o.limit=o.offset=s,o.offset=0,o}static wrap(t,r){if(t instanceof e){let o=t.clone();return o.markedOffset=-1,o}let n;if(t instanceof Uint8Array)n=new e(0,r),t.length>0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new e(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(pt));else if(Array.isArray(t))n=new e(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}readUInt32=this.readUint32;append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let o;return t instanceof e?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.length),this)}clone(t){let r=new e(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new e(0,this.littleEndian);let n=r-t,o=new e(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return r<t?this.resize((r*=2)>t?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength<t){let r=new ArrayBuffer(t);new Uint8Array(r).set(new Uint8Array(this.buffer)),this.buffer=r,this.view=new DataView(r);}return this}skip(t){return this.offset+=t,this}writeInt64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?pt:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",o=n?this.offset:r,i=ii().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=jr().decode(new Uint8Array(this.buffer,t,i));return t+=i,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let o=jr().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,length:t}}};var x={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://techcoderx.com","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},Qt=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],Ht=e=>{let t=Qt(e);t.length&&(x.nodes=t);},Ut=e=>{let t=Qt(e);t.length&&(x.restNodes=t);},Vt=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=Qt(n);o.length?t[r]=o:delete t[r];}x.restNodesByApi=t;},jt=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},Lt=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var be=class e{data;recovery;compressed;constructor(t,r,n){this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=hexToBytes(t),n=parseInt(bytesToHex(r.subarray(0,1)),16)-31,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=hexToBytes(t));let r=secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1.Signature(r.r,r.s,this.recovery);return new G(n.recoverPublicKey(t).toBytes())}};var G=class e{key;prefix;constructor(t,r){this.key=t,this.prefix=r??x.address_prefix;}static fromString(t){let r=x.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let o;try{o=Jr.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=ripemd160(i).subarray(0,4);if(!ai(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=be.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return si(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},si=(e,t)=>{let r=ripemd160(e);return t+Jr.encode(new Uint8Array([...e,...r.subarray(0,4)]))},ai=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return false;return true};var ft=class e{amount;symbol;constructor(t,r){this.amount=t,this.symbol=r==="HIVE"?"STEEM":r==="HBD"?"SBD":r;}static fromString(t,r=null){let[n,o]=t.split(" ");if(["STEEM","VESTS","SBD","TESTS","TBD","HIVE","HBD"].indexOf(o)===-1)throw new Error(`Invalid asset symbol: ${o}`);if(r&&o!==r)throw new Error(`Invalid asset, expected symbol: ${r} got: ${o}`);let i=Number.parseFloat(n);if(!Number.isFinite(i))throw new Error(`Invalid asset amount: ${n}`);return new e(i,o)}static from(t,r){if(t instanceof e){if(r&&t.symbol!==r)throw new Error(`Invalid asset, expected symbol: ${r} got: ${t.symbol}`);return t}else {if(typeof t=="number"&&Number.isFinite(t))return new e(t,r||"STEEM");if(typeof t=="string")return e.fromString(t,r);throw new Error(`Invalid asset '${String(t)}'`)}}getPrecision(){switch(this.symbol){case "TESTS":case "TBD":case "STEEM":case "SBD":case "HBD":case "HIVE":return 3;case "VESTS":return 6;default:return 3}}toString(){return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`}toJSON(){return this.toString()}};var mt=class e{buffer;static from(t){return t instanceof e?t:t instanceof Uint8Array?new e(t):typeof t=="string"?new e(hexToBytes(t)):new e(new Uint8Array(t))}constructor(t){this.buffer=t;}toString(){return bytesToHex(this.buffer)}toJSON(){return this.toString()}};var C={vote:0,comment:1,transfer:2,transfer_to_vesting:3,withdraw_vesting:4,limit_order_create:5,limit_order_cancel:6,feed_publish:7,convert:8,account_create:9,account_update:10,witness_update:11,account_witness_vote:12,account_witness_proxy:13,custom:15,delete_comment:17,custom_json:18,comment_options:19,set_withdraw_vesting_route:20,limit_order_create2:21,claim_account:22,create_claimed_account:23,request_account_recovery:24,recover_account:25,change_recovery_account:26,escrow_transfer:27,escrow_dispute:28,escrow_release:29,escrow_approve:31,transfer_to_savings:32,transfer_from_savings:33,cancel_transfer_from_savings:34,decline_voting_rights:36,reset_account:37,set_reset_account:38,claim_reward_balance:39,delegate_vesting_shares:40,account_create_with_delegation:41,witness_set_properties:42,account_update2:43,create_proposal:44,update_proposal_votes:45,remove_proposal:46,update_proposal:47,collateralized_convert:48,recurrent_transfer:49},ne=()=>{throw new Error("Void can not be serialized")},w=(e,t)=>{e.writeVString(t);},pi=(e,t)=>{e.writeInt16(t);},Xr=(e,t)=>{e.writeInt64(t);},Yr=(e,t)=>{e.writeUint8(t);},ae=(e,t)=>{e.writeUint16(t);},z=(e,t)=>{e.writeUint32(t);},Zr=(e,t)=>{e.writeUint64(t);},me=(e,t)=>{e.writeByte(t?1:0);},en=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},F=(e,t)=>{let r=ft.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||0);},ve=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},de=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(G.from(t).key);},tn=(e=null)=>(t,r)=>{r=mt.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},rn=tn(),$t=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},U=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},ce=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Oe=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},L=ce([["weight_threshold",z],["account_auths",$t(w,ae)],["key_auths",$t(de,ae)]]),li=ce([["account",w],["weight",ae]]),Wt=ce([["base",F],["quote",F]]),di=ce([["account_creation_fee",F],["maximum_block_size",z],["hbd_interest_rate",ae]]),T=(e,t)=>{let r=ce(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},S={};S.account_create=T(C.account_create,[["fee",F],["creator",w],["new_account_name",w],["owner",L],["active",L],["posting",L],["memo_key",de],["json_metadata",w]]);S.account_create_with_delegation=T(C.account_create_with_delegation,[["fee",F],["delegation",F],["creator",w],["new_account_name",w],["owner",L],["active",L],["posting",L],["memo_key",de],["json_metadata",w],["extensions",U(ne)]]);S.account_update=T(C.account_update,[["account",w],["owner",Oe(L)],["active",Oe(L)],["posting",Oe(L)],["memo_key",de],["json_metadata",w]]);S.account_witness_proxy=T(C.account_witness_proxy,[["account",w],["proxy",w]]);S.account_witness_vote=T(C.account_witness_vote,[["account",w],["witness",w],["approve",me]]);S.cancel_transfer_from_savings=T(C.cancel_transfer_from_savings,[["from",w],["request_id",z]]);S.change_recovery_account=T(C.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",U(ne)]]);S.claim_account=T(C.claim_account,[["creator",w],["fee",F],["extensions",U(ne)]]);S.claim_reward_balance=T(C.claim_reward_balance,[["account",w],["reward_hive",F],["reward_hbd",F],["reward_vests",F]]);S.comment=T(C.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);S.comment_options=T(C.comment_options,[["author",w],["permlink",w],["max_accepted_payout",F],["percent_hbd",ae],["allow_votes",me],["allow_curation_rewards",me],["extensions",U(en([ce([["beneficiaries",U(li)]])]))]]);S.convert=T(C.convert,[["owner",w],["requestid",z],["amount",F]]);S.create_claimed_account=T(C.create_claimed_account,[["creator",w],["new_account_name",w],["owner",L],["active",L],["posting",L],["memo_key",de],["json_metadata",w],["extensions",U(ne)]]);S.custom=T(C.custom,[["required_auths",U(w)],["id",ae],["data",rn]]);S.custom_json=T(C.custom_json,[["required_auths",U(w)],["required_posting_auths",U(w)],["id",w],["json",w]]);S.decline_voting_rights=T(C.decline_voting_rights,[["account",w],["decline",me]]);S.delegate_vesting_shares=T(C.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",F]]);S.delete_comment=T(C.delete_comment,[["author",w],["permlink",w]]);S.escrow_approve=T(C.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",z],["approve",me]]);S.escrow_dispute=T(C.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",z]]);S.escrow_release=T(C.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",z],["hbd_amount",F],["hive_amount",F]]);S.escrow_transfer=T(C.escrow_transfer,[["from",w],["to",w],["hbd_amount",F],["hive_amount",F],["escrow_id",z],["agent",w],["fee",F],["json_meta",w],["ratification_deadline",ve],["escrow_expiration",ve]]);S.feed_publish=T(C.feed_publish,[["publisher",w],["exchange_rate",Wt]]);S.limit_order_cancel=T(C.limit_order_cancel,[["owner",w],["orderid",z]]);S.limit_order_create=T(C.limit_order_create,[["owner",w],["orderid",z],["amount_to_sell",F],["min_to_receive",F],["fill_or_kill",me],["expiration",ve]]);S.limit_order_create2=T(C.limit_order_create2,[["owner",w],["orderid",z],["amount_to_sell",F],["exchange_rate",Wt],["fill_or_kill",me],["expiration",ve]]);S.recover_account=T(C.recover_account,[["account_to_recover",w],["new_owner_authority",L],["recent_owner_authority",L],["extensions",U(ne)]]);S.request_account_recovery=T(C.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",L],["extensions",U(ne)]]);S.reset_account=T(C.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",L]]);S.set_reset_account=T(C.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);S.set_withdraw_vesting_route=T(C.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",ae],["auto_vest",me]]);S.transfer=T(C.transfer,[["from",w],["to",w],["amount",F],["memo",w]]);S.transfer_from_savings=T(C.transfer_from_savings,[["from",w],["request_id",z],["to",w],["amount",F],["memo",w]]);S.transfer_to_savings=T(C.transfer_to_savings,[["from",w],["to",w],["amount",F],["memo",w]]);S.transfer_to_vesting=T(C.transfer_to_vesting,[["from",w],["to",w],["amount",F]]);S.vote=T(C.vote,[["voter",w],["author",w],["permlink",w],["weight",pi]]);S.withdraw_vesting=T(C.withdraw_vesting,[["account",w],["vesting_shares",F]]);S.witness_update=T(C.witness_update,[["owner",w],["url",w],["block_signing_key",de],["props",di],["fee",F]]);S.witness_set_properties=T(C.witness_set_properties,[["owner",w],["props",$t(w,rn)],["extensions",U(ne)]]);S.account_update2=T(C.account_update2,[["account",w],["owner",Oe(L)],["active",Oe(L)],["posting",Oe(L)],["memo_key",Oe(de)],["json_metadata",w],["posting_json_metadata",w],["extensions",U(ne)]]);S.create_proposal=T(C.create_proposal,[["creator",w],["receiver",w],["start_date",ve],["end_date",ve],["daily_pay",F],["subject",w],["permlink",w],["extensions",U(ne)]]);S.update_proposal_votes=T(C.update_proposal_votes,[["voter",w],["proposal_ids",U(Xr)],["approve",me],["extensions",U(ne)]]);S.remove_proposal=T(C.remove_proposal,[["proposal_owner",w],["proposal_ids",U(Xr)],["extensions",U(ne)]]);var fi=ce([["end_date",ve]]);S.update_proposal=T(C.update_proposal,[["proposal_id",Zr],["creator",w],["daily_pay",F],["subject",w],["permlink",w],["extensions",U(en([ne,fi]))]]);S.collateralized_convert=T(C.collateralized_convert,[["owner",w],["requestid",z],["amount",F]]);S.recurrent_transfer=T(C.recurrent_transfer,[["from",w],["to",w],["amount",F],["memo",w],["recurrence",ae],["executions",ae],["extensions",U(ce([["type",Yr],["value",ce([["pair_id",Yr]])]]))]]);var mi=(e,t)=>{let r=S[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},gi=ce([["ref_block_num",ae],["ref_block_prefix",z],["expiration",ve],["operations",U(mi)],["extensions",U(w)]]),yi=ce([["from",de],["to",de],["nonce",Zr],["check",z],["encrypted",tn()]]),ue={Asset:F,Memo:yi,Price:Wt,PublicKey:de,String:w,Transaction:gi,UInt16:ae,UInt32:z};var Ge=e=>new Promise(t=>setTimeout(t,e));var hi=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function an(){return hi?{"User-Agent":x.userAgent}:{}}var J=class extends Error{name="RPCError";data;code;stack=void 0;constructor(t){super(t.message),this.code=t.code,"data"in t&&(this.data=t.data);}},xe=class extends Error{node;rateLimitMs;isRateLimit;constructor(t,r,n={}){super(r),this.node=t,this.rateLimitMs=n.rateLimitMs??0,this.isRateLimit=n.isRateLimit??false;}};function cn(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var wi=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],_i=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function bi(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function vi(e){if(!e)return false;if(e instanceof xe)return true;if(e instanceof J)return false;let t=bi(e);return !!(wi.some(r=>t.includes(r))||_i.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function Gt(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function un(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var Pi=1e4,Ai=6e4,Oi=12e4,nn=2,on=6e4,sn=12e4,xi=30,ze=.3,zt=3,Je=5*6e4,pn=6e4,ln=1e3,dn=2e3,yt=class{health=new Map;getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r<dn||this.recordLatency(this.getOrCreate(t),r,n);}getUsableLatencyMs(t,r){let n=this.health.get(t);if(!n)return;let o=Date.now();if(r!==void 0){let i=n.apiLatency.get(r);return i&&i.sampleCount>=zt&&o-i.updatedAt<=Je?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>Je&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:ze*r+(1-ze)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>Je?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=ze*r+(1-ze)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=nn&&(i.cooldownUntil=o+on),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,nn),i.lastFailureTime=o,i.cooldownUntil=o+on,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>Oi&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(Pi*2**n.rateLimitStreak,Ai);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=sn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=sn&&i-n.headBlock>xi)}getOrderedNodes(t,r){let n=[],o=[];for(let u of t)this.isNodeHealthy(u,r)?n.push(u):o.push(u);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((u,p)=>({node:u,i:p,score:this.scoreNode(u,i)})).sort((u,p)=>u.score-p.score||u.i-p.i).map(u=>u.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(u=>u!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=zt&&r-t.latencyUpdatedAt<=Je}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:ln}pickReprobeCandidate(t,r){let n=r-pn,o,i=1/0;for(let s of t){let a=this.getOrCreate(s),u=Math.max(a.latencyUpdatedAt,a.lastProbeAt);u<=n&&u<i&&(o=s,i=u);}return o&&(this.getOrCreate(o).lastProbeAt=r),o}},V=new yt,Pe=new yt,Jt=class{tokens=x.resilience.hedgeBucketCapacity;trySpend(){return this.clamp(),this.tokens>=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(x.resilience.hedgeBucketCapacity,this.tokens+x.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>x.resilience.hedgeBucketCapacity&&(this.tokens=x.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=x.resilience.hedgeBucketCapacity){this.tokens=t;}},Yt=new Jt;function ht(e,t,r,n,o){let i=x.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function Xt(e,t,r,n){r instanceof xe?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof J?e.recordFailure(t,n):e.recordFailure(t);}function fn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function Ei(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function mn(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(Ei()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function Zt(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var Ye=async(e,t,r,n=x.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:u,cleanup:p}=mn(n),{signal:l,cleanup:f}=Zt(u,i),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...an()},signal:l});if(y.status===429)throw new xe(e,"HTTP 429 Rate Limited",{rateLimitMs:cn(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new xe(e,`HTTP ${y.status} from ${e}`);let A=await y.json();if(!A||typeof A.id>"u"||A.id!==s||A.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in A)return A.result;if("error"in A){let O=A.error;throw "message"in O&&"code"in O?new J(O):A.error}throw A}catch(y){if(y instanceof J||y instanceof xe||i?.aborted)throw y;if(o)return Ye(e,t,r,n,false,i);throw y}finally{m();}};function gt(){return Ge(50+Math.random()*50)}function Si(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:u,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let A=false,O=0,v=false,P=false,I,B,j=0,Q=[],ee=W=>{if(!A){A=true,B!==void 0&&(clearTimeout(B),B=void 0);for(let R of Q)R.signal.aborted||R.abort();W();}},Ie=(W,R)=>{O++;let le=new AbortController;Q.push(le);let We=Zt(le.signal,p),ni=ht(V,W,t,s,a),Nt=Date.now();R||(j=Nt),Ye(W,t,r,ni,false,We.signal).then(re=>{if(We.cleanup(),O--,R||(P=true),!A){if(f&&!f(re)){if(V.recordDefectiveResponse(W,n),I=new Error(`[hive-tx] response validation failed for ${t} from ${W}`),!R&&!v){ee(()=>y(I));return}O===0&&ee(()=>y(I));return}V.recordSuccess(W,n,Date.now()-Nt,t),fn(V,W,t,re),R?P||V.recordCensoredLatency(o,Date.now()-j,t):v||Yt.refill(),ee(()=>m(re));}}).catch(re=>{if(We.cleanup(),O--,R||(P=true),!A){if(p?.aborted){ee(()=>y(re));return}if(re instanceof J&&!Gt(re.code,re.message)){ee(()=>y(re));return}if(Xt(V,W,re,n),V.recordSlowFailure(W,Date.now()-Nt,t),I=re,!R&&!v){ee(()=>y(re));return}O===0&&ee(()=>y(I));}});};Ie(o,false);let Le=V.getUsableLatencyMs(o,t)??0,$e=ht(V,o,t,s,a),Mt=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*Le),.8*$e);B=setTimeout(()=>{if(B=void 0,A||p?.aborted||Date.now()>=u)return;let W=i.filter(le=>V.isNodeHealthy(le,n));if(W.length===0)return;let R=W[Math.floor(Math.random()*W.length)];Yt.trySpend()&&(v=true,l(R),Ie(R,true));},Mt);})}var g=async(e,t=[],r,n=x.retry,o,i)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??x.timeout,u=un(e),p=Date.now()+x.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=V.getOrderedNodes(x.nodes,u),A=y.find(P=>!l.has(P));A||(l.clear(),A=y[0]),l.add(A);let O=[];if(x.resilience.hedge&&V.getUsableLatencyMs(A,e)!==void 0&&(O=y.filter(P=>!l.has(P)&&V.isNodeHealthy(P,u)).slice(0,3)),O.length>0)try{return await Si({method:e,params:t,api:u,primary:A,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:o,onHedgeFired:P=>l.add(P),validate:i})}catch(P){if(P instanceof J&&!Gt(P.code,P.message)||o?.aborted)throw P;f=P,m<n&&await gt();continue}let v=Date.now();try{let P=await Ye(A,e,t,ht(V,A,e,a,s),!1,o);if(i&&!i(P)){V.recordDefectiveResponse(A,u),f=new Error(`[hive-tx] response validation failed for ${e} from ${A}`),m<n&&await gt();continue}return V.recordSuccess(A,u,Date.now()-v,e),Yt.refill(),fn(V,A,e,P),P}catch(P){if(P instanceof J&&!Gt(P.code,P.message)||o?.aborted)throw P;Xt(V,A,P,u),V.recordSlowFailure(A,Date.now()-v,e),f=P,m<n&&await gt();}}throw f},Be=async(e,t=[],r=x.broadcastTimeout,n)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let o=un(e),i=new Set,s;for(let a=0;a<x.nodes.length;a++){let p=V.getOrderedNodes(x.nodes,o).find(l=>!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await Ye(p,e,t,r,!1,n);return V.recordSuccess(p,o),l}catch(l){if(l instanceof J||n?.aborted||(Xt(V,p,l,o),s=l,!vi(l)))throw l}}throw s},ki={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function X(e,t,r,n,o=x.retry,i){if(!Array.isArray(x.restNodes))throw new Error("config.restNodes is not an array");if(x.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??x.timeout,u=Date.now()+x.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=x.restNodesByApi?.[e]?.length?x.restNodesByApi[e]:x.restNodes,f=new Set,m,y=false;for(let A=0;A<=o&&!(A>0&&Date.now()>=u);A++){let O=Pe.getOrderedNodes(l,e),v=O.find(R=>!f.has(R));v||(f.clear(),v=O[0]),f.add(v);let P=v+ki[e],I=t,B=r||{},j=new Set;Object.entries(B).forEach(([R,le])=>{I.includes(`{${R}}`)&&(I=I.replace(`{${R}}`,encodeURIComponent(String(le))),j.add(R));});let Q=new URL(P+I);if(Object.entries(B).forEach(([R,le])=>{j.has(R)||(Array.isArray(le)?le.forEach(We=>Q.searchParams.append(R,String(We))):Q.searchParams.set(R,String(le)));}),i?.aborted)throw new Error("Aborted");y=false;let{signal:ee,cleanup:Ie}=mn(ht(Pe,v,p,a,s)),{signal:Le,cleanup:$e}=Zt(ee,i),Mt=()=>{Ie(),$e();},W=Date.now();try{let R=await fetch(Q.toString(),{signal:Le,headers:an()});if(R.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(R.status===429)throw Pe.recordRateLimit(v,cn(R.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${v}`);if(R.status===503)throw Pe.recordFailure(v,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${v}`);if(!R.ok)throw Pe.recordFailure(v,e),y=!0,new Error(`HTTP ${R.status} from ${v}`);return Pe.recordSuccess(v,e,Date.now()-W,p),R.json()}catch(R){if(R?.message?.includes("HTTP 404")||i?.aborted)throw R;y||Pe.recordFailure(v,e),Pe.recordSlowFailure(v,Date.now()-W,p),m=R,A<o&&await gt();}finally{Mt();}}throw m}var wt=async(e,t=[],r=2,n)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an Array");if(r>x.nodes.length)throw new Error("quorum > config.nodes.length");let i=(u=>{let p=[...u];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(x.nodes),s=Math.min(r,i.length),a=[];for(;s>0&&i.length>0;){let u=i.splice(0,s),p=[],l=[];for(let m=0;m<u.length;m++)p.push(Ye(u[m],e,t,void 0,true,n).then(y=>l.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Ci(a,r);if(f)return f;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Ci(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var Ri=hexToBytes(x.chain_id),Ee=class e{transaction;expiration=6e4;txId;constructor(t){t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let o of t){let i=o.sign(r);this.transaction.signatures.push(i.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await Be("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof J&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await Ge(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o<r;)await Ge(1e3+o*300),n=await this.checkStatus(),o++;return {tx_id:this.txId,status:n?.status??"unknown"}}digest(){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");let t=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN),r={...this.transaction};try{ue.Transaction(t,r);}catch(s){throw new Error("Unable to serialize transaction: "+s)}t.flip();let n=new Uint8Array(t.toBuffer()),o=bytesToHex(sha256(n)).slice(0,40);return {digest:sha256(new Uint8Array([...Ri,...n])),txId:o}}addSignature(t){if(!this.transaction)throw new Error("First create a transaction by .create(operations)");if(typeof t!="string")throw new Error("Signature must be string");if(t.length!==130)throw new Error("Signature must be 130 characters long");return this.transaction.signatures.push(t),this.transaction}async checkStatus(){return this.txId||(this.txId=this.digest().txId),g("transaction_status_api.find_transaction",{transaction_id:this.txId,expiration:this.transaction?.expiration})}createTransaction=async t=>{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,signatures:[]};}};var bn=new Uint8Array([128]),H=class e{key;constructor(t){this.key=t;try{secp256k1.getPublicKey(t);}catch{throw new Error("invalid private key")}}static from(t){return typeof t=="string"?e.fromString(t):new e(t)}static fromString(t){return new e(Di(t).subarray(1))}static fromSeed(t){if(typeof t=="string")if(/^[0-9a-fA-F]+$/.test(t))t=hexToBytes(t);else {let n=[];for(let o=0;o<t.length;o++){let i=t.charCodeAt(o);if(i<128)n.push(i);else if(i<2048)n.push(192|i>>6,128|i&63);else if(i>=55296&&i<=56319&&o+1<t.length){let s=t.charCodeAt(++o);i=65536+((i&1023)<<10)+(s&1023),n.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return be.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new G(secp256k1.getPublicKey(this.key),t)}toString(){return Ki(new Uint8Array([...bn,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1.getSharedSecret(this.key,t.key);return sha512(r.subarray(1))}static randomKey(){return new e(secp256k1.keygen().secretKey)}},vn=e=>sha256(sha256(e)),Ki=e=>{let t=vn(e);return Jr.encode(new Uint8Array([...e,...t.slice(0,4)]))},Di=e=>{let t=Jr.decode(e);if(!wn(t.slice(0,1),bn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=vn(n).slice(0,4);if(!wn(r,o))throw new Error("Private key checksum mismatch");return n},wn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;n<r&&e[n]===t[n];)n++;return n===r};var An=(e,t,r,n=Hi())=>xn(e,t,n,r),On=(e,t,r,n,o)=>xn(e,t,r,n,o).message,xn=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);a.writeUint64(i),a.append(s),a.flip();let u=sha512(new Uint8Array(a.toBuffer())),p=u.subarray(32,48),l=u.subarray(0,32),f=sha256(u).subarray(0,4),m=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(o!==void 0){if(y!==o)throw new Error("Invalid key");n=Ni(n,l,p);}else n=Qi(n,l,p);return {nonce:i,message:n,checksum:y}},Ni=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},Qi=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},tr=null,Hi=()=>{if(tr===null){let r=secp256k1.utils.randomSecretKey();tr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++tr%65536;return e=e<<BigInt(16)|BigInt(t),e};var En=e=>{let t=Wi(e,33);return new G(t)},Vi=e=>e.readUint64(),ji=e=>e.readUint32(),Li=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},$i=e=>t=>{let r={},n=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function Wi(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var Gi=$i([["from",En],["to",En],["nonce",Vi],["check",ji],["encrypted",Li]]),Sn={Memo:Gi};var Cn=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),Rn(),e=Fn(e),t=zi(t);let o=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:u}=An(e,t,i,n),p=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);ue.Memo(p,{check:u,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+Jr.encode(l)},Tn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),Rn(),e=Fn(e);let r=Sn.Memo(Jr.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new G(n.key).toString()?new G(o.key):new G(n.key);r=On(e,p,i,a,s);let l=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},_t,Rn=()=>{if(_t===void 0){let e;_t=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Cn(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Tn(t,n);}finally{_t=e==="#memo\u7231";}}if(_t===false)throw new Error("This environment does not support encryption.")},Fn=e=>typeof e=="string"?H.fromString(e):e,zi=e=>typeof e=="string"?G.fromString(e):e,qn={decode:Tn,encode:Cn};var te={};ut(te,{buildWitnessSetProperties:()=>ts,makeBitMaskFilter:()=>Zi,operations:()=>Xi,validateUsername:()=>Yi});var Yi=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),o=n.length;for(let i=0;i<o;i++){let s=n[i];if(!/^[a-z]/.test(s))return t+"start with a lowercase letter.";if(!/^[a-z0-9-]*$/.test(s))return t+"have only lowercase letters, digits, or dashes.";if(!/[a-z0-9]$/.test(s))return t+"end with a lowercase letter or digit.";if(s.length<3)return t+"be longer."}return null},Xi={vote:0,comment:1,transfer:2,transfer_to_vesting:3,withdraw_vesting:4,limit_order_create:5,limit_order_cancel:6,feed_publish:7,convert:8,account_create:9,account_update:10,witness_update:11,account_witness_vote:12,account_witness_proxy:13,pow:14,custom:15,report_over_production:16,delete_comment:17,custom_json:18,comment_options:19,set_withdraw_vesting_route:20,limit_order_create2:21,claim_account:22,create_claimed_account:23,request_account_recovery:24,recover_account:25,change_recovery_account:26,escrow_transfer:27,escrow_dispute:28,escrow_release:29,pow2:30,escrow_approve:31,transfer_to_savings:32,transfer_from_savings:33,cancel_transfer_from_savings:34,custom_binary:35,decline_voting_rights:36,reset_account:37,set_reset_account:38,claim_reward_balance:39,delegate_vesting_shares:40,account_create_with_delegation:41,witness_set_properties:42,account_update2:43,create_proposal:44,update_proposal_votes:45,remove_proposal:46,update_proposal:47,collateralized_convert:48,recurrent_transfer:49,fill_convert_request:50,author_reward:51,curation_reward:52,comment_reward:53,liquidity_reward:54,interest:55,fill_vesting_withdraw:56,fill_order:57,shutdown_witness:58,fill_transfer_from_savings:59,hardfork:60,comment_payout_update:61,return_vesting_delegation:62,comment_benefactor_reward:63,producer_reward:64,clear_null_account_balance:65,proposal_pay:66,sps_fund:67,hardfork_hive:68,hardfork_hive_restore:69,delayed_voting:70,consolidate_treasury_balance:71,effective_comment_vote:72,ineffective_delete_comment:73,sps_convert:74,expired_account_notification:75,changed_recovery_account:76,transfer_to_vesting_completed:77,pow_reward:78,vesting_shares_split:79,account_created:80,fill_collateralized_convert_request:81,system_warning:82,fill_recurrent_transfer:83,failed_recurrent_transfer:84,limit_order_cancelled:85,producer_missed:86,proposal_fee:87,collateralized_convert_immediate_conversion:88,escrow_approved:89,escrow_rejected:90,proxy_cleared:91,declined_voting_rights:92},Zi=e=>e.reduce(es,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),es=([e,t],r)=>r<64?[e|BigInt(1)<<BigInt(r),t]:[e,t|BigInt(1)<<BigInt(r-64)],ts=(e,t)=>{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let o;switch(n){case "key":case "new_signing_key":o=ue.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=ue.UInt32;break;case "hbd_interest_rate":o=ue.UInt16;break;case "url":o=ue.String;break;case "hbd_exchange_rate":o=ue.Price;break;case "account_creation_fee":o=ue.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,rs(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},rs=(e,t)=>{let r=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function Af(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o<128)r.push(o);else if(o<2048)r.push(192|o>>6,128|o&63);else if(o>=55296&&o<=56319&&n+1<e.length){let i=e.charCodeAt(++n);o=65536+((o&1023)<<10)+(i&1023),r.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function Kn(e){try{return H.fromString(e),!0}catch{return false}}async function Y(e,t){let r=new Ee;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Be("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function Dn(e,t){let r=new Ee;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var os=432e3;function In(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/os,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function is(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function rr(e){let t=is(e)*1e6;return In(t,e.voting_manabar)}function bt(e){return In(Number(e.max_rc),e.rc_manabar)}var Bn=(u=>(u.COMMON="common",u.INFO="info",u.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",u.MISSING_AUTHORITY="missing_authority",u.TOKEN_EXPIRED="token_expired",u.NETWORK="network",u.TIMEOUT="timeout",u.VALIDATION="validation",u))(Bn||{});function Me(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(i(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function ss(e){let t=Me(e);return [t.message,t.type]}function ge(e){let{type:t}=Me(e);return t==="missing_authority"||t==="token_expired"}function as(e){let{type:t}=Me(e);return t==="insufficient_resource_credits"}function cs(e){let{type:t}=Me(e);return t==="info"}function us(e){let{type:t}=Me(e);return t==="network"||t==="timeout"}async function ye(e,t,r,n,o="posting",i,s,a="async"){let u=n?.adapter;switch(e){case "key":{if(!u)throw new Error("No adapter provided for key-based auth");let p=i;if(p===void 0)switch(o){case "owner":if(u.getOwnerKey)p=await u.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":u.getActiveKey&&(p=await u.getActiveKey(t));break;case "memo":if(u.getMemoKey)p=await u.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;case "posting":default:p=await u.getPostingKey(t);break}if(!p)throw new Error(`No ${o} key available for ${t}`);let l=H.fromString(p);return a==="async"?await Dn(r,l):await Y(r,l)}case "hiveauth":{if(!u?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await u.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!u)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await u.getAccessToken(t);if(p)try{return (await new Mn.Client({accessToken:p}).broadcast(r)).result}catch(l){if(u.broadcastWithHiveSigner&&ge(l))return await u.broadcastWithHiveSigner(t,r,o);throw l}if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,o);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!u?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await u.broadcastWithKeychain(t,r,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function ls(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let f=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!ge(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!ge(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!ge(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await ye(l,e,t,r,n,void 0,void 0,o)}catch(m){if(ge(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",A=await i.showAuthUpgradeUI(n,y);if(!A)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ye(A,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(f){if(ge(f)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await i.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await ye(y,e,t,r,n,void 0,void 0,o)}throw f}else if(n==="active"&&i.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ye(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,A;switch(l){case "key":if(!i)f=!0,m="No adapter provided";else {let O;switch(n){case "owner":i.getOwnerKey&&(O=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(O=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(O=await i.getMemoKey(e));break;case "posting":default:O=await i.getPostingKey(e);break}O?y=O:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)f=!0,m="No adapter provided";else {let O=await i.getAccessToken(e);O&&(A=O);}break;case "keychain":i?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await ye(l,e,t,r,n,y,A,o)}catch(f){if(a.set(l,f),!ge(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function b(e=[],t,r,n=()=>{},o,i="posting",s){let a=s?.broadcastMode??"async";return useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async u=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(u);try{if(o?.enableFallback!==!1&&o?.adapter)return await ls(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=H.fromString(l);return await Y(p,m)}let f=o?.accessToken;if(f)return (await new Mn.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof J?new Error(l.message):l}}})}async function Nn(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let a=H.fromString(i);return Y([["custom_json",o]],a)}let s=n?.accessToken;if(s)return (await new Mn.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Nf=4e3;function E(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function he(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Se=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),ms=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},we=1e4,d={privateApiHost:"https://ecency.com",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return x.nodes},heliusApiKey:ms(),queryClient:new QueryClient,pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},N;(O=>{function e(v){d.queryClient=v;}O.setQueryClient=e;function t(v){d.privateApiHost=v;}O.setPrivateApiHost=t;function r(v){d.clientId=v;}O.setClientId=r;function n(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}O.getValidatedBaseUrl=n;function o(v){d.pollsApiHost=v;}O.setPollsApiHost=o;function i(v){d.imageHost=v;}O.setImageHost=i;function s(v){Ht(v);}O.setHiveNodes=s;function a(v){Ut(v);}O.setRestNodes=a;function u(v){Vt(v);}O.setRestNodesByApi=u;function p(v){jt(v);}O.setUserAgent=p;function l(v){Lt(v);}O.setResilience=l;function f(v){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(v))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(v))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(v))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(v)||/\.\+\.\+/.test(v))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let P=/\.?\{(\d+),(\d+)\}/g,I;for(;(I=P.exec(v))!==null;){let[,B,j]=I;if(parseInt(j,10)-parseInt(B,10)>1e3)return {safe:false,reason:`excessive range: {${B},${j}}`}}return {safe:true}}function m(v){let P=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],I=5;for(let B of P){let j=Date.now();try{v.test(B);let Q=Date.now()-j;if(Q>I)return {safe:!1,reason:`runtime test exceeded ${I}ms (took ${Q}ms on input length ${B.length})`}}catch(Q){return {safe:false,reason:`runtime test threw error: ${Q}`}}}return {safe:true}}function y(v,P=200){try{if(!v)return Se&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(v.length>P)return Se&&console.warn(`[SDK] DMCA pattern rejected: length ${v.length} exceeds max ${P} - pattern: ${v.substring(0,50)}...`),null;let I=f(v);if(!I.safe)return Se&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${I.reason}) - pattern: ${v.substring(0,50)}...`),null;let B;try{B=new RegExp(v);}catch(Q){return Se&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${v.substring(0,50)}...`,Q),null}let j=m(B);return j.safe?B:(Se&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${j.reason}) - pattern: ${v.substring(0,50)}...`),null)}catch(I){return Se&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${v.substring(0,50)}...`,I),null}}function A(v={}){let P=Q=>Array.isArray(Q)?Q.filter(ee=>typeof ee=="string"):[],I=v||{},B={accounts:P(I.accounts),tags:P(I.tags),patterns:P(I.posts)};d.dmcaAccounts=B.accounts,d.dmcaTags=B.tags,d.dmcaPatterns=B.patterns,d.dmcaTagRegexes=B.tags.map(Q=>y(Q)).filter(Q=>Q!==null),d.dmcaPatternRegexes=[];let j=B.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Se&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${B.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${B.tags.length} compiled (${j} rejected)`),console.log(` - Post patterns: ${B.patterns.length} (using exact string matching)`),j>0&&console.warn(`[SDK] ${j} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}O.setDmcaLists=A;})(N||={});function Yf(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var _=()=>d.queryClient,ws;(s=>{function e(a){return _().getQueryData(a)}s.getQueryData=e;function t(a){return _().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await _().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await _().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>_().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>_().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(ws||={});function Zf(e){return btoa(JSON.stringify(e))}function em(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var Qn=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(Qn||{}),vt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(vt||{});function k(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:Qn[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:vt[e.nai]}}var nr;function h(){if(!nr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");nr=globalThis.fetch.bind(globalThis);}return nr}function Hn(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function _s(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function oe(e,t){return _s(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Ne(e,t){return e/1e6*t}function Un(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var Vn=60*1e3;function _e(){return queryOptions({queryKey:c.core.dynamicProps(),refetchInterval:Vn,staleTime:Vn,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=k(t.total_vesting_shares).amount,a=k(t.total_vesting_fund_hive).amount,u=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(u=a/s*1e6);let p=k(r.current_median_history.base).amount,l=k(r.current_median_history.quote).amount,f=parseFloat(o.recent_claims),m=k(o.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),A=o.author_reward_curve??"linear",O=Number(o.content_constant??0),v=String(i.current_hardfork_version??"0.0.0"),P=Number(i.last_hardfork??0),I=t.hbd_print_rate,B=t.hbd_interest_rate,j=t.head_block_number,Q=a,ee=s,Ie=k(t.virtual_supply).amount,Le=t.vesting_reward_percent||0,$e=n.account_creation_fee;return {hivePerMVests:u,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:A,contentConstant:O,currentHardforkVersion:v,lastHardfork:P,hbdPrintRate:I,hbdInterestRate:B,headBlock:j,totalVestingFund:Q,totalVestingShares:ee,virtualSupply:Ie,vestingRewardPercent:Le,accountCreationFee:$e,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function ym(e="post"){return queryOptions({queryKey:c.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function ke(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var c={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>ke("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>ke("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>ke("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>ke("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>ke("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>ke("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,o,i)=>ke("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],_prefix:["ai"]}};function vm(e){return queryOptions({queryKey:c.ai.prices(),queryFn:async()=>{let r=await h()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function xm(e,t){return queryOptions({queryKey:c.ai.assistPrices(e),queryFn:async()=>{let n=await h()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function xs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Cm(e,t){return useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let o=await h()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??xs()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let u=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw u.status=o.status,u.data=a,u}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&_().invalidateQueries({queryKey:c.points._prefix(e)});}})}function Ss(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function qm(e,t){return useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let o=await h()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:Ss()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&_().invalidateQueries({queryKey:c.points._prefix(e)}),_().invalidateQueries({queryKey:c.ai.assistPrices(e)}));}})}function or(e){return !e.posting_json_metadata&&!e.json_metadata}function Cs(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function M(e){return queryOptions({queryKey:c.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let o=r[0];if(or(o)&&Cs(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!or(l[0])));if(p[0]&&!or(p[0]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=Ce(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,u=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:u,profile:i}},enabled:!!e,staleTime:6e4})}var Ts=new Set(["__proto__","constructor","prototype"]);function Pt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function jn(e,t){let r={...e};for(let n of Object.keys(t)){if(Ts.has(n))continue;let o=t[n],i=r[n];Pt(o)&&Pt(i)?r[n]=jn(i,o):r[n]=o;}return r}function Rs(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:o,...i}=t;return {...r,meta:i}})}function Ce(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function Ln(e){return Ce(e?.posting_json_metadata)}function $n(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Ce(e.posting_json_metadata)).length;return Object.keys(Ce(t.posting_json_metadata)).length>r?t:e}function Fs(e){if(!e)return {};try{let t=JSON.parse(e);if(Pt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function Wn({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=Fs(e),o=Pt(n.profile)?n.profile:{},i=ir({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function ir({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=jn(e??{},i);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=Rs(s.tokens),s.version=2,s}function At(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=Ce(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function Wm(e){return queryOptions({queryKey:c.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=await g("condenser_api.get_accounts",[e],void 0,void 0,void 0,r=>Array.isArray(r));return At(t??[])}})}function Xm(e){return queryOptions({queryKey:c.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function ng(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function cg(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}function fg(e,t=100){return queryOptions({queryKey:c.accounts.mutedUsers(e),queryFn:async()=>(await g("condenser_api.get_following",[e,"","ignore",t])).map(n=>n.following),enabled:!!e})}function wg(e,t=50){return queryOptions({queryKey:c.accounts.lookup(e,t),queryFn:()=>g("condenser_api.lookup_accounts",[e,t]),enabled:!!e,staleTime:1/0})}function Ag(e,t=5,r=[]){return queryOptions({queryKey:c.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var Hs=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Sg(e,t){return queryOptions({queryKey:c.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await h()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let o=await n.json(),i=Array.isArray(o)?o.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,u=typeof a.token=="string"?a.token:void 0;if(!u)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let A={symbol:u,currency:u,address:f,show:y,type:"CHAIN",meta:l},O=[];for(let[v,P]of Object.entries(p))typeof v=="string"&&(Hs.has(v)||typeof P!="string"||!P||/^[A-Z0-9]{2,10}$/.test(v)&&O.push({symbol:v,currency:v,address:P,show:y,type:"CHAIN",meta:{address:P,show:y}}));return [A,...O]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function Gn(e,t){return queryOptions({queryKey:c.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>await g("bridge.get_relationship_between_accounts",[e,t])??{follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false}})}function Ig(e){return queryOptions({queryKey:c.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Qg(e,t){return queryOptions({queryKey:c.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Hg(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Lg(e,t){return queryOptions({queryKey:c.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function $g(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Jg(e,t,r){return queryOptions({queryKey:c.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let o=await h()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function ey(e,t){return queryOptions({enabled:!!e&&!!t,queryKey:c.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await h()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function iy(e){return queryOptions({enabled:!!e,queryKey:c.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function py(e,t=50){return queryOptions({queryKey:c.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>e?g("condenser_api.get_account_reputations",[e,t]):[]})}var K=te.operations,zn={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer,K.fill_recurrent_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay]},Zs=[...Object.values(zn)].reduce((e,t)=>e.concat(t),[]);function ea(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function ta(e){return e.replace(/_operation$/,"")}function ra(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function na(e){if(!ra(e))return e;let t=k(e),r=vt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function oa(e){let t={};for(let[r,n]of Object.entries(e))t[r]=na(n);return t}function hy(e,t=20,r=""){let n=r?zn[r]:Zs;return infiniteQueryOptions({queryKey:c.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{if(!e)return {entries:[],currentPage:0};let s={"account-name":e,"operation-types":n.join(","),"page-size":t};o!==null&&(s.page=o);let a=await X("hafah","/accounts/{account-name}/operations",s,void 0,void 0,i);return {entries:a.operations_result.map(p=>{let l=ta(p.op.type);return {...oa(p.op.value),num:ea(p),type:l,timestamp:p.timestamp,trx_id:p.trx_id}}),currentPage:o??a.total_pages}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function vy(){return queryOptions({queryKey:c.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function xy(e){return infiniteQueryOptions({queryKey:c.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=N.getValidatedBaseUrl(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Cy(e){return queryOptions({queryKey:c.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function Ky(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return infiniteQueryOptions({queryKey:c.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var pa=30;function Ny(e,t,r){return queryOptions({queryKey:c.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(u=>t==="following"?u.following:u.follower).filter(u=>u.toLowerCase().includes(r.toLowerCase())).slice(0,pa);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(u=>({name:u.name,full_name:u.metadata.profile?.name||"",reputation:u.reputation,active:u.active}))??[]}})}function jy(e=20){return infiniteQueryOptions({queryKey:c.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function Jy(e=250){return infiniteQueryOptions({queryKey:c.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Hn(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function Qe(e,t){return queryOptions({queryKey:c.posts.fragments(e),queryFn:async()=>t?(await h()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function eh(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function oh(e="feed"){return queryOptions({queryKey:c.posts.promoted(e),queryFn:async()=>{let t=N.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await h()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function uh(e){return queryOptions({queryKey:c.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function mh(e,t,r){return queryOptions({queryKey:c.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function _h(e,t){return queryOptions({queryKey:c.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function Oh(e,t){return queryOptions({queryKey:c.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function Ch(e,t){return queryOptions({queryKey:c.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function Z(e){return Array.isArray(e)?e.map(t=>Jn(t)):Jn(e)}function Jn(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function Yn(e,t,r){try{let n=await wt("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function Xn(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return queryOptions({queryKey:c.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let u=await Yn(e,o,r);if(!u)return null;let p=n!==void 0?{...u,num:n}:u;return Z(p)}let a=n!==void 0?{...s,num:n}:s;return Z(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ie(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function Zn(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await Pa(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function eo(e,t,r){let n=e.map(Ze),o=await Promise.all(n.map(i=>Zn(i,t,void 0,r)));return Z(o)}async function to(e,t="",r="",n=20,o="",i="",s){let a=await ie("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return a&&eo(a,i,s)}async function sr(e,t,r="",n="",o=20,i="",s){if(d.dmcaAccounts.includes(t))return [];let a=await ie("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:o,observer:i},s);return a&&eo(a,i,s)}function Ze(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function Pa(e="",t="",r="",n,o){let i=await ie("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=Ze(i),a=await Zn(s,r,n,o);return Z(a)}}async function jh(e="",t=""){let r=await ie("get_post_header",{author:e,permlink:t});return r&&Ze(r)}async function ro(e,t,r){let n=await ie("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=Ze(s);return o}return n}async function no(e,t=""){return ie("get_community",{name:e,observer:t})}async function Lh(e="",t=100,r,n="rank",o=""){return ie("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function oo(e){let t=await ie("normalize_post",{post:e});return t&&Ze(t)}async function $h(e){return ie("list_all_subscriptions",{account:e})}async function Wh(e){return ie("list_subscribers",{community:e})}async function Gh(e,t){return ie("get_relationship_between_accounts",[e,t])}async function Ot(e,t){return ie("get_profiles",{accounts:e,observer:t})}var so=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(so||{});function ar(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Aa(e,t,r){let n=l=>ar(l.pending_payout_value).amount+ar(l.author_payout_value).amount+ar(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(o(l))return 1;if(o(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m<y?1:0},votes:(l,f)=>{let m=l.children,y=f.children;return m>y?-1:m<y?1:0},created:(l,f)=>{if(o(l))return 1;if(o(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:m<y?1:0}},a=t.sort(s[r]),u=a.findIndex(l=>i(l)),p=a[u];return u>=0&&(a.splice(u,1),a.unshift(p)),a}function ao(e,t="created",r=true,n){return queryOptions({queryKey:c.posts.discussions(e?.author,e?.permlink,t,n||e?.author),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:n||e.author}),i=o?Array.from(Object.values(o)):[];return Z(i)},enabled:r&&!!e,select:o=>Aa(e,o,t),structuralSharing:(o,i)=>{if(!o||!i)return i;let s=o.filter(p=>p.is_optimistic===true),a=new Set(i.map(p=>`${p.author}/${p.permlink}`)),u=s.filter(p=>!a.has(`${p.author}/${p.permlink}`));return u.length>0?[...i,...u]:i}})}function tw(e,t,r,n=true){return queryOptions({queryKey:c.posts.discussion(e,t,r||e),enabled:n&&!!e&&!!t,queryFn:async()=>ro(e,t,r)})}function aw(e,t="posts",r=20,n="",o=true){return infiniteQueryOptions({queryKey:c.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await sr(t,e,i.author??"",i.permlink??"",r,n,s);return Z(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function cw(e,t="posts",r="",n="",o=20,i="",s=true){return queryOptions({queryKey:c.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let u=await sr(t,e,r,n,o,i,a);return Z(u??[])}})}function gw(e,t,r=20,n="",o=true,i={}){return infiniteQueryOptions({queryKey:c.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{if(!s.hasNextPage)return [];let u=t;d.dmcaTagRegexes.some(O=>O.test(t))&&(u="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:u,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);let l=p,f=l.filter(O=>O.stats?.is_pinned),y=(e==="hot"?l:l.sort((O,v)=>new Date(v.created).getTime()-new Date(O.created).getTime())).filter(O=>!O.stats?.is_pinned),A=[...f,...y];return Z(A)},enabled:o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},getNextPageParam:s=>{let a=s?.[s.length-1];return {author:a?.author,permlink:a?.permlink,hasNextPage:(s?.length??0)>0}}})}function yw(e,t="",r="",n=20,o="",i="",s=true){return queryOptions({queryKey:c.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let u=o;d.dmcaTagRegexes.some(l=>l.test(o))&&(u="");let p=await to(e,t,r,n,u,i,a);return Z(p??[])}})}function vw(e,t,r=200){return queryOptions({queryKey:c.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function Ew(e,t){return queryOptions({queryKey:c.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function Tw(e,t){return queryOptions({queryKey:c.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Rw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Dw(e,t){return queryOptions({queryKey:c.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Iw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function uo(e){let r=await h()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function Qw(e,t){return queryOptions({queryKey:c.posts.images(e),queryFn:async()=>!e||!t?[]:uo(t),enabled:!!e&&!!t})}function Hw(e,t){return queryOptions({queryKey:c.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:uo(t),enabled:!!e&&!!t})}function Uw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function $w(e,t,r=false){return queryOptions({queryKey:c.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function Ba(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function Jw(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?Ba(n,r):"";return queryOptions({queryKey:c.posts.deletedEntry(i),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:u,tags:p}=s.list[0];return {body:a,title:u,tags:p}},enabled:o})}function e_(e,t,r=true){return queryOptions({queryKey:c.posts.tips(e,t),queryFn:async()=>{let n=await fetch(d.privateApiHost+"/private-api/post-tips",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t})});if(!n.ok)throw new Error(`Failed to fetch post tips: ${n.status}`);return n.json()},enabled:!!e&&!!t&&r})}function Na(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function Qa(e){return {...e,id:e.id??e.post_id}}function fe(e,t){if(!e)return null;let r=e.container??e,n=Na(r,t),o=e.parent?Qa(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:o}}function Ha(e){return Array.isArray(e)?e:[]}async function po(e){let t=ao(e,"created",true),r=await d.queryClient.fetchQuery(t),n=Ha(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function lo(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var ja=20;function fo(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??ja}}async function mo({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let u=N.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",u);p.searchParams.set("limit",String(i)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),o&&p.searchParams.set("observer",o);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=fe(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function c_(e={}){let t=fo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:c.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:u,signal:p})=>mo(t,u,p),getNextPageParam:u=>{if(!(u.length<a))return u[u.length-1]?._cursor}})}function u_(e={}){let t=fo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return queryOptions({queryKey:[...c.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),"latest"],staleTime:0,queryFn:({signal:u})=>mo(t,void 0,u)})}var $a=20;function Wa(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??$a}}async function Ga({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=N.getValidatedBaseUrl(),u=new URL("/private-api/waves/shorts",a);u.searchParams.set("limit",String(o)),i&&u.searchParams.set("cursor",i),e.forEach(f=>u.searchParams.append("container",f)),t&&u.searchParams.set("tag",t),r&&u.searchParams.set("author",r),n&&u.searchParams.set("observer",n);let p=await fetch(u.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=fe(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function m_(e={}){let t=Wa(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return infiniteQueryOptions({queryKey:c.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:u})=>Ga(t,a,u),getNextPageParam:a=>{if(!(a.length<s))return a[a.length-1]?._cursor}})}var Ja=5,Ya=50;async function Xa(e,t){let r=t?.author,n=t?.permlink,o=0,i=t?.post_id;for(;o<Ya;){let s={sort:"posts",account:e,limit:Ja,...r?{start_author:r}:{},...n?{start_permlink:n}:{}},a;try{a=await g("bridge.get_account_posts",s);}catch(l){return console.error("[SDK] getThreads get_account_posts error:",l),null}if(!a||a.length===0)return null;let u=a.map(l=>(l.id=l.post_id,l.host=e,l));for(let l of u){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await po(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:lo(f,l,e)}}let p=u[u.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function b_(e){return infiniteQueryOptions({queryKey:c.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await Xa(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var ec=40;function x_(e,t,r=ec){return infiniteQueryOptions({queryKey:c.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>fe(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function T_(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>fe(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function K_(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:c.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:u,posts:p})=>({tag:u,posts:p}))}catch(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function N_(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>fe(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function V_(e){return queryOptions({queryKey:c.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=N.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function G_(e,t=true){return queryOptions({queryKey:c.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>oo(e)})}function ac(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function go(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function tb(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return infiniteQueryOptions({queryKey:c.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&go(m.timestamp)<=o),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(Xn(m.author,m.permlink));ac(y)&&l.push(y);}let[f]=a;return {lastDate:f?go(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function sb(e,t,r=true){return queryOptions({queryKey:c.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Ot(e,t)})}function lb(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:c.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await X("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function yb(e,t="HIVE",r="yearly"){return queryOptions({queryKey:c.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await X("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function bb(){return queryOptions({queryKey:c.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function vb(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function Sb(e,t,r){let n=useQueryClient(),{data:o}=useQuery(M(e));return b(["accounts","update"],e,i=>{let s=$n(n.getQueryData(M(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:Wn({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(M(e).queryKey,a=>{if(!a)return a;let u=JSON.parse(JSON.stringify(a));return u.profile=ir({existingProfile:Ln(a),profile:s.profile,tokens:s.tokens}),u}),await E(t?.adapter,r,[c.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...M(e),staleTime:0});}catch{}}})}function Fb(e,t,r,n,o){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=Gn(e,t);await _().prefetchQuery(s);let a=_().getQueryData(s.queryKey);return await Nn(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),_().setQueryData(c.accounts.relations(e,t),i),t&&_().invalidateQueries(M(t));}})}function cr(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function Te(e,t,r,n,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function Re(e,t,r,n,o,i,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:o,allow_curation_rewards:i,extensions:s}]}function ur(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function pr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function Fe(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function gc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>Fe(e,i.trim(),r,n))}function yc(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:o,executions:i,extensions:[]}]}function He(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function qe(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function yo(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function et(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [qe(e,t,r,n,o),yo(e,o)]}function tt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function rt(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function nt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function ot(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function it(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function lr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function Ke(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function dr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function fr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function mr(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function xt(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function hc(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function wc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return xt(e,t)}function gr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}function yr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function hr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function wr(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function _r(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function _c(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function bc(e,t,r,n,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function br(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function vr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Pr(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function Ar(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Or(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function xr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function vc(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function Pc(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}var ho=(r=>(r.Buy="buy",r.Sell="sell",r))(ho||{}),wo=(r=>(r.EMPTY="",r.SWAP="9",r))(wo||{});function St(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function Et(e,t=3){return e.toFixed(t)}function Ac(e,t,r,n,o=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,u=n==="buy"?`${Et(t,3)} HBD`:`${Et(t,3)} HIVE`,p=n==="buy"?`${Et(r,3)} HIVE`:`${Et(r,3)} HBD`;return St(e,u,p,false,s,a)}function Er(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Sr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function Oc(e,t,r,n,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}function xc(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function kr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Cr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Tr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Rr(e,t,r,n,o,i){if(!e||!t||!r||!o)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let u={...t,account_auths:a};return u.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:u,memo_key:o,json_metadata:i}]}function Ec(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}function Sc(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function kc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function Cc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function Fr(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function qr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function Kr(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function Ue(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Tc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>Ue(e,i.trim(),r,n))}function Dr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function Rc(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function Fc(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function Zb(e,t,r){return b(["accounts","follow"],e,({following:n})=>[mr(e,n)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.relations(e,o.following),c.accounts.full(o.following),c.accounts.followCount(o.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function nv(e,t,r){return b(["accounts","unfollow"],e,({following:n})=>[xt(e,n)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.relations(e,o.following),c.accounts.full(o.following),c.accounts.followCount(o.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function av(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,code:t})})).json()},onSuccess:()=>{r(),_().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function lv(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),_().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function gv(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{r();let s=_();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,i)});},onError:n})}function bv(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await h()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=_(),s=c.accounts.favorites(e),a=c.accounts.favoritesInfinite(e),u=c.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:u})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(y=>y.account!==o));let l=i.getQueryData(u);i.setQueryData(u,false);let f=i.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,A]of f)A&&i.setQueryData(y,{...A,pages:A.pages.map(O=>({...O,data:O.data.filter(v=>v.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{r();let s=_();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,i)});},onError:(o,i,s)=>{let a=_();if(s?.previousList&&a.setQueryData(c.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);s?.previousCheck!==void 0&&a.setQueryData(c.accounts.checkFavorite(e,i),s.previousCheck),n(o);}})}function Nc(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function _o(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let u=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=o?l.key_auths.filter(([A])=>!m.includes(A.toString())):[];return l.key_auths=Nc(y,n.map((A,O)=>[A[p].createPublic().toString(),O+1])),l};return Y([["account_update",{account:e,json_metadata:r.json_metadata,owner:u("owner"),active:u("active"),posting:u("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],i)},...t})}function Tv(e,t){let{data:r}=useQuery(M(e)),{mutateAsync:n}=_o(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=H.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:H.fromLogin(e,o,"owner"),active:H.fromLogin(e,o,"active"),posting:H.fromLogin(e,o,"posting"),memo_key:H.fromLogin(e,o,"memo")}]})},...t})}function Iv(e,t,r){let n=useQueryClient(),{data:o}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let u=JSON.parse(JSON.stringify(o.posting));u.account_auths=u.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:u,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return Y([["account_update",p]],a);if(s==="keychain"){if(!r?.broadcast)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.broadcast([["account_update",p]],"active")}else return !t.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing."),Mn.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(M(e).queryKey,u=>({...u,posting:{...u?.posting,account_auths:u?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function Vv(e,t,r,n){let{data:o}=useQuery(M(e));return useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:u})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await h()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:u,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return Y([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.broadcast)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.broadcast([["change_recovery_account",p]],"owner")}else return !r.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing."),Mn.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function Lv(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function bo(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([u])=>!r.has(u.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function Yv(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=bo(r,i);return Y([["account_update",s]],n)},...t})}function tP(e,t,r){return b(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[Tr(n,o)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function iP(e,t,r){return b(["accounts","grant-posting-permission"],e,n=>[Rr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await E(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}function uP(e,t,r){return b(["accounts","create"],e,n=>[n.useClaimed?Cr(e,n.newAccountName,n.keys):kr(e,n.newAccountName,n.keys,n.fee)],async()=>{await E(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}var Ir=300*60*24,Yc=1e4,Xc=5e7;function vo(e){let t=k(e.vesting_shares).amount,r=k(e.received_vesting_shares).amount,n=k(e.delegated_vesting_shares).amount,o=k(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function Zc(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function eu(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function tu(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let o=vo(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/Yc/(n*Ir)),a=rr(e),u=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(u)||s>u?0:Math.max(s-Xc,0)}function ru(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(eu(t))return tu(e,t,n);let o=0;try{if(o=vo(e),!Number.isFinite(o))return 0}catch{return 0}return Zc(o,r,n)}function fP(e){return rr(e).percentage/100}function mP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*Ir/1e4}function gP(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/Ir;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function yP(e){return bt(e).percentage/100}function hP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let u=ru(e,t,r,n);return Number.isFinite(u)?u/o*i*(s/a):0}var nu={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function ou(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function iu(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function su(e){let t=e[0];return t==="custom_json"?ou(e):t==="create_proposal"||t==="update_proposal"?iu(e):nu[t]??"posting"}function _P(e){let t="posting";for(let r of e){let n=su(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function OP(e){return useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=H.fromLogin(e,r,"active"):Kn(r)?n=H.fromString(r):n=H.from(r),Y([t],n)}})}function SP(e,t,r="active"){return useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.broadcast)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.broadcast([n],r)}})}function RP(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>Mn.sendOperation(t,{callback:e},()=>{})})}function DP(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Po(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Ao(e,t){return {...e??{},title:t.title,body:t.body}}function VP(e,t){return useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await h()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=_(),i=Ao(r,n);o.setQueryData(Qe(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,u)=>u===0?{...a,data:[i,...a.data]}:a)});}})}function JP(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await h()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let o=_(),i=s=>Po(s,r,n);o.setQueryData(Qe(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(u=>u.id===n.fragmentId?i(u):u)}))});}})}function rA(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await h()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=_();o.setQueryData(Qe(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function $(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function iA(e,t,r,n){let i=await h()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await $(i);return {status:i.status,data:s}}async function sA(e){let r=await h()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await $(r);return {status:r.status,data:n}}async function aA(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await h()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await $(s);}async function cA(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await h()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return $(s)}async function uA(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},u=await h()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return $(u)}async function pA(e,t,r){let n={code:e,username:t,token:r},i=await h()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return $(i)}async function Oo(e,t){let r={code:e};t&&(r.id=t);let o=await h()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function xo(e,t){let r={code:e,url:t},o=await h()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}var gu="https://i.ecency.com";async function Eo(e,t,r){let n=h(),o=new FormData;o.append("file",e);let i=await n(`${gu}/hs/${t}`,{method:"POST",body:o,signal:r});return $(i)}async function lA(e,t,r,n){let o=h(),i=new FormData;i.append("file",e);let s=await o(`${d.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return $(s)}async function So(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function ko(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await h()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return $(a)}async function Co(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},u=await h()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return $(u)}async function To(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function Ro(e,t,r,n,o,i,s,a){let u={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(u.options=i);let l=await h()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return $(l)}async function Fo(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function qo(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function dA(e,t,r){let n={code:e,author:t,permlink:r},i=await h()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return $(i)}async function fA(e,t,r){let n={username:e,email:t,friend:r},i=await h()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return $(i)}function wA(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return ko(t,o,i,s,a)},onSuccess:o=>{r?.();let i=_();o?.drafts?i.setQueryData(c.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function AA(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:u})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Co(t,o,i,s,a,u)},onSuccess:()=>{r?.();let o=_();o.invalidateQueries({queryKey:c.posts.drafts(e)}),o.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function CA(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return To(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=_(),s=c.posts.drafts(e),a=c.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let u=i.getQueryData(s);u&&i.setQueryData(s,u.filter(f=>f._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&i.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(A=>A._id!==o)}))});return {previousList:u,previousInfinite:l}},onSuccess:()=>{r?.();let o=_();o.invalidateQueries({queryKey:c.posts.drafts(e)}),o.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:(o,i,s)=>{let a=_();if(s?.previousList&&a.setQueryData(c.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);n?.(o);}})}function KA(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:u,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Ro(t,o,i,s,a,u,p,l)},onSuccess:()=>{r?.(),_().invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function NA(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return Fo(t,o)},onSuccess:o=>{r?.();let i=_();o?i.setQueryData(c.posts.schedules(e),o):i.invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function jA(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return qo(t,o)},onSuccess:o=>{r?.();let i=_();o?i.setQueryData(c.posts.schedules(e),o):i.invalidateQueries({queryKey:c.posts.schedules(e)}),i.invalidateQueries({queryKey:c.posts.drafts(e)});},onError:n})}function zA(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return xo(s,o)},onSuccess:()=>{r?.(),_().invalidateQueries({queryKey:c.posts.images(e)});},onError:n})}function e0(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return So(t,o)},onSuccess:(o,i)=>{r?.();let s=_(),{imageId:a}=i;s.setQueryData(["posts","images",e],u=>u?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},u=>u&&{...u,pages:u.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function o0(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>Eo(r,n,o),onSuccess:e,onError:t})}function Ct(e,t){return `/@${e}/${t}`}function xu(e,t,r){return (r??_()).getQueryData(c.posts.entry(Ct(e,t)))}function Eu(e,t){(t??_()).setQueryData(c.posts.entry(Ct(e.author,e.permlink)),e);}function kt(e,t,r,n){let o=n??_(),i=Ct(e,t),s=o.getQueryData(c.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(c.posts.entry(i),a),s}var De;(a=>{function e(u,p,l,f,m){kt(u,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(u,p,l,f){kt(u,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(u,p,l,f){kt(u,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(u,p,l,f){kt(p,l,m=>({...m,children:m.children+1,replies:[u,...m.replies]}),f);}a.addReply=n;function o(u,p){u.forEach(l=>Eu(l,p));}a.updateEntries=o;function i(u,p,l){(l??_()).invalidateQueries({queryKey:c.posts.entry(Ct(u,p))});}a.invalidateEntry=i;function s(u,p,l){return xu(u,p,l)}a.getEntry=s;})(De||={});function Su(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function ku(e,t,r){let n=De.getEntry(t.author,t.permlink,r);if(!n?.active_votes||Su(n.active_votes,e,t.weight))return;let o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);De.updateVotes(t.author,t.permlink,o,i,r);}function l0(e,t,r){return b(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[cr(e,n,o,i)],async(n,o)=>{ku(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([c.posts.entry(`/@${o.author}/${o.permlink}`),c.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function y0(e,t,r){return b(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[pr(e,n,o,i??false)],async(n,o)=>{let i=De.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));De.updateReblogsCount(o.author,o.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{_().invalidateQueries({queryKey:c.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([c.posts.entry(`/@${o.author}/${o.permlink}`),c.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function b0(e,t,r){return b(["posts","comment"],e,n=>{let o=[];if(o.push(Te(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Re(n.author,n.permlink,i,s,a,u,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=i?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let u=[c.accounts.full(e),c.resourceCredits.account(e)];if(!i){u.push(c.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.parentPermlink;u.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(u);}},t,"posting",{broadcastMode:r})}function A0(e,t,r,n){let o=n??_(),i=o.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of i)a&&o.setQueryData(s,[e,...a]);}function Ko(e,t,r,n,o){let i=o??_(),s=new Map,a=i.getQueriesData({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[u,p]of a)p&&(s.set(u,p),i.setQueryData(u,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Do(e,t){let r=t??_();for(let[n,o]of e)r.setQueryData(n,o);}function O0(e,t,r,n){let o=n??_(),i=`/@${e}/${t}`,s=o.getQueryData(c.posts.entry(i));return s&&o.setQueryData(c.posts.entry(i),{...s,...r}),s}function x0(e,t,r,n){let o=n??_(),i=`/@${e}/${t}`;o.setQueryData(c.posts.entry(i),r);}function T0(e,t,r){return b(["posts","deleteComment"],e,({author:n,permlink:o})=>[ur(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[c.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(c.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.push({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:Ko(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&Do(s);}})}function K0(e,t,r){return b(["posts","cross-post"],e,n=>{let o=[];if(o.push(Te(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true}=n.options;o.push(Re(n.author,n.permlink,i,s,a,u,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[c.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function M0(e,t,r){return b(["posts","update-reply"],e,n=>{let o=[];if(o.push(Te(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Re(n.author,n.permlink,i,s,a,u,l));}return o},async(n,o)=>{let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(110,i,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:i,error:s});}),t?.adapter?.invalidateQueries){let s=[c.resourceCredits.account(e)];s.push(c.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let a=o.rootAuthor||o.parentAuthor,u=o.rootPermlink||o.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===u}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function U0(e,t,r){return b(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[Kr(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.posts._promotedPrefix],[...c.points._prefix(e)],c.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Cu=[3e3,3e3,3e3],Tu=e=>new Promise(t=>setTimeout(t,e));async function Ru(e,t){return g("condenser_api.get_content",[e,t])}async function Fu(e,t,r=0,n){let o=n?.delays??Cu,i;try{i=await Ru(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await Tu(s),Fu(e,t,r+1,n)}var Ve={};ut(Ve,{useRecordActivity:()=>Br});function Ku(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function Br(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=h(),o=Ku(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function X0(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function nO(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),o=n.map(s=>s.account),i=await g("condenser_api.get_accounts",[o]);for(let s=0;s<i.length;s++){let a=i[s],u=n[s],p=typeof a.vesting_shares=="string"?a.vesting_shares:a.vesting_shares.toString(),l=typeof a.received_vesting_shares=="string"?a.received_vesting_shares:a.received_vesting_shares.toString(),f=typeof a.delegated_vesting_shares=="string"?a.delegated_vesting_shares:a.delegated_vesting_shares.toString(),m=typeof a.vesting_withdraw_rate=="string"?a.vesting_withdraw_rate:a.vesting_withdraw_rate.toString(),y=parseFloat(p)+parseFloat(l)-parseFloat(f)-parseFloat(m);u.efficiency=u.vests/y;}return n.sort((s,a)=>a.efficiency-s.efficiency),n}})}function aO(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,o,i,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Qr={};ut(Qr,{getAccountTokenQueryOptions:()=>Nr,getAccountVideosQueryOptions:()=>Vu});var Mr={};ut(Mr,{getDecodeMemoQueryOptions:()=>Qu});function Qu(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new Mn.Client({accessToken:r}).decode(t)}})}var Io={queries:Mr};function Nr(e,t){return queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await h()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),o=Io.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await _().prefetchQuery(o);let{memoDecoded:i}=_().getQueryData(o.queryKey);return i.replace("#","")}})}function Vu(e,t){return queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=Nr(e,t);await _().prefetchQuery(r);let n=_().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await h()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var kO={queries:Qr};function qO(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await h()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function BO({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await h()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function HO(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function LO(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}var Bo={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function GO({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return Bo;let{current_mana:o,max_mana:i}=bt(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...Bo,ready:true,currentMana:o,maxMana:i};let a=Number.isFinite(n)&&n>0?n:1.2,u=s*a,p=o<u;return {ready:true,currentMana:o,maxMana:i,avgCost:s,estimatedCost:u,willLikelyFail:p,deficit:p?Math.ceil(u-o):0,remaining:Math.floor(o/s)}}function XO(e,t,r){return queryOptions({queryKey:["games","status-check",r,e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function nx(e,t,r,n){let{mutateAsync:o}=Br(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){o();}})}function ax(e){let t=e?.replace("@","");return queryOptions({queryKey:c.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await h()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var Yu=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function ux(e,t){return Yu.find(r=>r.tier===e&&r.id===t)}var px=300,lx=2;function ep(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function tp(e){let r=await h()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:ep()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function gx(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return tp(t)},onSuccess(){n&&r.invalidateQueries({queryKey:c.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:c.quests.status(n)});}})}function _x(e,t,r){return b(["communities","subscribe"],e,({community:n})=>[br(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(o.community)],c.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function Ax(e,t,r){return b(["communities","unsubscribe"],e,({community:n})=>[vr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(o.community)],c.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function Sx(e,t,r){return b(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[xr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[c.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function Rx(e,t,r,n){return b(["communities","set-role",e],t,({account:o,role:i})=>[Pr(t,e,o,i)],async(o,i)=>{_().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>{if(!a)return a;let u=[...a.team??[]],p=u.findIndex(([l])=>l===i.account);return p>=0?u[p]=[u[p][0],i.role,u[p][2]??""]:u.push([i.account,i.role,""]),{...a,team:u}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)],c.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function Dx(e,t,r,n){return b(["communities","update",e],t,o=>[Ar(t,e,o)],async(o,i)=>{_().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function Nx(e,t,r){return b(["communities","registerRewards"],e,({name:n})=>[Dr(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.communities.singlePrefix(o.name)],[...c.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function Vx(e,t,r){return b(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[Or(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.posts.entry(`/@${o.account}/${o.permlink}`),[...c.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function Gx(e,t,r=100,n=void 0,o=true){return queryOptions({queryKey:c.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function Zx(e,t){return queryOptions({queryKey:c.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function oE(e,t="",r=true){return queryOptions({queryKey:c.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>no(e??"",t)})}function uE(e){return queryOptions({queryKey:c.communities.subscribers(e),queryFn:async()=>await g("bridge.list_subscribers",{community:e})??[],staleTime:6e4})}function mE(e,t){return infiniteQueryOptions({queryKey:c.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>{try{return await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[]}catch{return []}},getNextPageParam:r=>r?.length>0?r[r.length-1].id:null})}function wE(){return queryOptions({queryKey:c.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var cp=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(cp||{}),bE={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function PE(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function AE({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function SE(e,t){return queryOptions({queryKey:c.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function RE(e,t,r=void 0){return infiniteQueryOptions({queryKey:c.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialData:{pages:[],pageParams:[]},initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var lp=(f=>(f.VOTES="rvotes",f.MENTIONS="mentions",f.FAVORITES="nfavorites",f.BOOKMARKS="nbookmarks",f.FOLLOWS="follows",f.REPLIES="replies",f.REBLOGS="reblogs",f.TRANSFERS="transfers",f.DELEGATIONS="delegations",f.PAYOUTS="payouts",f.SCHEDULED_PUBLISHED="scheduled_published",f))(lp||{});var dp=(l=>(l[l.VOTE=1]="VOTE",l[l.MENTION=2]="MENTION",l[l.FOLLOW=3]="FOLLOW",l[l.COMMENT=4]="COMMENT",l[l.RE_BLOG=5]="RE_BLOG",l[l.TRANSFERS=6]="TRANSFERS",l[l.FAVORITES=13]="FAVORITES",l[l.BOOKMARKS=15]="BOOKMARKS",l[l.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",l.ALLOW_NOTIFY="ALLOW_NOTIFY",l))(dp||{}),Mo=[1,2,3,4,5,6,13,15,22],fp=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(fp||{});function ME(e,t,r){return queryOptions({queryKey:c.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let o=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Mo]})})}function UE(){return queryOptions({queryKey:c.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function $E(e){return queryOptions({queryKey:c.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function wp(e,t){return {...e,read:!t||t===e.id?1:e.read}}function No(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function ZE(e,t,r,n){let o=_();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Oo(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:c.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:c.notifications._prefix,predicate:l=>{let f=l.state.data;return No(f)}});a.forEach(([l,f])=>{if(f&&No(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(A=>wp(A,i)))};o.setQueryData(l,m);}});let u=c.notifications.unreadCount(e),p=o.getQueryData(u);return typeof p=="number"&&p>0&&(s.push([u,p]),i?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===i&&y.read===0)))&&o.setQueryData(u,p-1):o.setQueryData(u,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(c.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([u,p])=>{o.setQueryData(u,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:c.notifications._prefix});}})}function nS(e,t,r){return b(["notifications","set-last-read"],e,({date:n})=>gr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function aS(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)<new Date&&new Date(r.end_date)>=new Date?r.status="active":new Date(r.end_date)<new Date?r.status="expired":r.status="inactive",r}})}function lS(){return queryOptions({queryKey:["proposals","list"],queryFn:async()=>{let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function yS(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),u=At(a);return s.map(l=>({...l,voterAccount:u.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function bS(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function OS(e,t,r){return b(["proposals","vote"],e,({proposalIds:n,approve:o})=>[_r(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.proposals.list(),c.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function kS(e,t,r){return b(["proposals","create"],e,n=>[wr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.proposals.list()]);},t,"active",{broadcastMode:r})}function FS(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.length<t?void 0:r[r.length-1]?.delegatee,enabled:!!e})}function IS(e){return queryOptions({queryKey:["assets","account-delegations",e],enabled:!!e,queryFn:({signal:t})=>X("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function QS(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function jS(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function GS(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function XS(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function rk(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function sk(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function pk(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function mk(e){return queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await h()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function wk(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function Pk(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function pe(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function se(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function Ip(e){if(!e||typeof e!="object")return;let t=e;return {name:pe(t.name)??"",symbol:pe(t.symbol)??"",layer:pe(t.layer)??"hive",balance:se(t.balance)??0,fiatRate:se(t.fiatRate)??0,currency:pe(t.currency)??"usd",precision:se(t.precision)??3,address:pe(t.address),error:pe(t.error),pendingRewards:se(t.pendingRewards),pendingRewardsFiat:se(t.pendingRewardsFiat),liquid:se(t.liquid),liquidFiat:se(t.liquidFiat),savings:se(t.savings),savingsFiat:se(t.savingsFiat),staked:se(t.staked),stakedFiat:se(t.stakedFiat),iconUrl:pe(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:se(t.apr)}}function Bp(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function Mp(e){if(!e||typeof e!="object")return;let t=e;return pe(t.username)??pe(t.name)??pe(t.account)}function Qo(e,t="usd",r=true){return queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${N.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=Bp(i).map(a=>Ip(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:Mp(i)??e,currency:pe(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Tt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await _().prefetchQuery(_e()),await _().prefetchQuery(M(e));let t=_().getQueryData(_e().queryKey),r=_().getQueryData(M(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=k(r.balance).amount,s=k(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function Ho(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await _().prefetchQuery(_e()),await _().prefetchQuery(M(e));let t=_().getQueryData(M(e).queryKey),r=_().getQueryData(_e().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:k(t.hbd_balance).amount+k(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:k(t.hbd_balance).amount},{name:"savings",balance:k(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function Up(e){let u=9.5-(e.headBlock-7e6)/25e4*.01;u<.95&&(u=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*u*p/f).toFixed(3)}function Uo(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await _().prefetchQuery(_e()),await _().prefetchQuery(M(e));let t=_().getQueryData(_e().queryKey),r=_().getQueryData(M(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o:t.base/t.quote,s=k(r.vesting_shares).amount,a=k(r.delegated_vesting_shares).amount,u=k(r.received_vesting_shares).amount,p=k(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=Un(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Ne(s,t.hivePerMVests).toFixed(3),y=+Ne(a,t.hivePerMVests).toFixed(3),A=+Ne(u,t.hivePerMVests).toFixed(3),O=+Ne(l,t.hivePerMVests).toFixed(3),v=+Ne(f,t.hivePerMVests).toFixed(3),P=Math.max(m-O,0),I=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+P.toFixed(3),apr:Up(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+I.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:A},...O>0?[{name:"pending_power_down",balance:+O.toFixed(3)}]:[],...v>0&&v!==O?[{name:"next_power_down",balance:+v.toFixed(3)}]:[]]}}})}var D=te.operations,Hr={transfers:[D.transfer,D.transfer_to_savings,D.transfer_from_savings,D.cancel_transfer_from_savings,D.recurrent_transfer,D.fill_recurrent_transfer,D.escrow_transfer,D.fill_recurrent_transfer],"market-orders":[D.fill_convert_request,D.fill_order,D.fill_collateralized_convert_request,D.limit_order_create2,D.limit_order_create,D.limit_order_cancel],interests:[D.interest],"stake-operations":[D.return_vesting_delegation,D.withdraw_vesting,D.transfer_to_vesting,D.set_withdraw_vesting_route,D.update_proposal_votes,D.fill_vesting_withdraw,D.account_witness_proxy,D.delegate_vesting_shares],rewards:[D.author_reward,D.curation_reward,D.producer_reward,D.claim_reward_balance,D.comment_benefactor_reward,D.liquidity_reward,D.proposal_pay],"":[]};var Wk=Object.keys(te.operations);var Vo=te.operations,Jk=Vo,Yk=Object.entries(Vo).reduce((e,[t,r])=>(e[r]=t,e),{});var jo=te.operations;function jp(e){return Object.prototype.hasOwnProperty.call(jo,e)}function st(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in Hr){Hr[a].forEach(u=>i.add(u));return}jp(a)&&i.add(jo[a]);});let s=Lp(Array.from(i));return {filterKey:o,filterArgs:s}}function Lp(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<<BigInt(n):r|=1n<<BigInt(n-64);}),[t!==0n?t.toString():null,r!==0n?r.toString():null]}function Rt(e,t=20,r=[]){let{filterArgs:n,filterKey:o}=st(r);return infiniteQueryOptions({queryKey:["assets","hive","transactions",e,t,o],initialData:{pages:[],pageParams:[]},initialPageParam:-1,getNextPageParam:(i,s)=>i?+(i[i.length-1]?.num??0)-1:-1,queryFn:async({pageParam:i})=>(await g("condenser_api.get_account_history",[e,i,t,...n])).map(a=>({num:a[0],type:a[1].op[0],timestamp:a[1].timestamp,trx_id:a[1].trx_id,...a[1].op[1]})),select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.map(a=>a.filter(u=>{switch(u.type){case "author_reward":case "comment_benefactor_reward":return k(u.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(u.amount).symbol==="HIVE";case "transfer_from_savings":return k(u.amount).symbol==="HIVE";case "fill_recurrent_transfer":let l=k(u.amount);return ["HIVE"].includes(l.symbol);case "claim_reward_balance":return k(u.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return false}}))})})}function cC(e,t=20,r=[]){let{filterKey:n}=st(r);return infiniteQueryOptions({...Rt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:i})=>({pageParams:i,pages:o.map(s=>s.filter(a=>{switch(a.type){case "author_reward":case "comment_benefactor_reward":return k(a.hbd_payout).amount>0;case "claim_reward_balance":return k(a.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(a.amount).symbol==="HBD";case "transfer_from_savings":return k(a.amount).symbol==="HBD";case "fill_recurrent_transfer":let l=k(a.amount);return ["HBD"].includes(l.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return false}}))})})}function fC(e,t=20,r=[]){let{filterKey:n}=st(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return infiniteQueryOptions({...Rt(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return k(p.vesting_payout).amount>0;case "claim_reward_balance":return k(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(k(p.amount).symbol);case "fill_recurrent_transfer":let m=k(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return i||o.has(p.type)}}))})})}function Lo(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function Ur(e,t){return new Date(e.getTime()-t*1e3)}function hC(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,Lo(t),Lo(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[Ur(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[Ur(n,Math.max(100*e,28800)),Ur(n,e)]})}function vC(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function xC(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function TC(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>k(n.vesting_shares).amount-k(r.vesting_shares).amount)})}function KC(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function MC(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function UC(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function $C(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function JC(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=h(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function $o(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function eT(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[$o(o),$o(n),e])})}function oT(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function cT(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function dT(e,t,r){return b(["market","limit-order-create"],e,n=>[St(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function yT(e,t,r){return b(["market","limit-order-cancel"],e,({orderId:n})=>[Er(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function at(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function _T(e,t,r,n){let o=h(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return at(s)}async function Wo(e){if(e==="hbd")return 1;let t=h(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await at(n)).hive_dollar[e]}async function bT(e,t){let n=await h()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return at(n)}async function vT(){let t=await h()(d.privateApiHost+"/private-api/market-data/latest");return at(t)}async function PT(){let t=await h()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return at(t)}var sl={"Content-type":"application/json"};async function al(e){let t=h(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:sl});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Ae(e,t){try{return await al(e)}catch{return t}}async function xT(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([Ae({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Ae({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=a=>a.sort((u,p)=>{let l=Number(u.price??0);return Number(p.price??0)-l}),s=a=>a.sort((u,p)=>{let l=Number(u.price??0),f=Number(p.price??0);return l-f});return {buy:i(n),sell:s(o)}}async function ET(e,t=50){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function ST(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[o,i]=await Promise.all([Ae({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Ae({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),u=i.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...u].sort((p,l)=>l.timestamp-p.timestamp)}async function cl(e,t){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...e?{symbol:e}:{},...t?{account:t}:{}}},id:1},[])}async function Ft(e,t){return cl(t,e)}async function qt(e){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Kt(e){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Go(e,t,r,n){let o=h(),i=N.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await o(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function zo(e,t="daily"){let r=h(),n=N.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function Jo(e){let t=h(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function Dt(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>qt(e)})}function Yo(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ft()})}function Xo(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Kt(e)})}function QT(e,t,r=20){return infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return Go(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function jT(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>zo(e,t)})}function GT(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await Jo(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function XT(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Ft(e,t)})}function je(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,u=typeof a=="string"?parseFloat(a):a;return s+=u.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),i&&(s+=" "+i),s}var It=class{symbol;name;icon;precision;stakingEnabled;delegationEnabled;balance;stake;stakedBalance;delegationsIn;delegationsOut;usdValue;constructor(t){this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}hasDelegations=()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false;delegations=()=>this.hasDelegations()?`(${je(this.stake,{fractionDigits:this.precision})} + ${je(this.delegationsIn,{fractionDigits:this.precision})} - ${je(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():je(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():je(this.balance,{fractionDigits:this.precision})};function sR(e,t,r){return queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await qt(e),o=await Kt(n.map(a=>a.symbol)),i=t?t.base/t.quote:0,s=Array.isArray(r)?r:[];return n.map(a=>{let u=o.find(A=>A.symbol===a.symbol),p;if(u?.metadata)try{p=JSON.parse(u.metadata);}catch{p=void 0;}let l=s.find(A=>A.symbol===a.symbol),f=Number(l?.lastPrice??"0"),m=Number(a.balance),y=a.symbol==="SWAP.HIVE"?i*m:f===0?0:Number((f*i*m).toFixed(10));return new It({symbol:a.symbol,name:u?.name??a.symbol,icon:p?.icon??"",precision:u?.precision??0,stakingEnabled:u?.stakingEnabled??false,delegationEnabled:u?.delegationEnabled??false,balance:a.balance,stake:a.stake,delegationsIn:a.delegationsIn,delegationsOut:a.delegationsOut,usdValue:y})})},enabled:!!e})}function Zo(e,t){return queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=_(),n=Tt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Xo([t])),s=await r.ensureQueryData(Dt(e)),a=await r.ensureQueryData(Yo()),u=i?.find(v=>v.symbol===t),p=s?.find(v=>v.symbol===t),f=+(a?.find(v=>v.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),A=parseFloat(p?.pendingUnstake??"0"),O=[{name:"liquid",balance:m},{name:"staked",balance:y}];return A>0&&O.push({name:"unstaking",balance:A}),{name:t,title:u?.name??"",price:f===0?0:Number(f*(o?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:O}}})}function ct(e,t=0){return queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let o=await n.json(),i=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function ei(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await _().prefetchQuery(ct(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(_().getQueryData(ct(e).queryKey)?.points??0)})})}function OR(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:o,type:i,amount:s,id:a,sender:u,receiver:p,memo:l})=>({created:new Date(o),type:i,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:u??void 0,to:p??void 0,memo:l??void 0}))})}function IR(e,t,r={refetch:false}){let n=_(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await Wo(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=Qo(e,o,true),u=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,A=m.value;if(typeof A=="string"){let v=A.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(v){let P=Math.abs(Number.parseFloat(v[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:P}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:P}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:P});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,o],queryFn:async()=>{let p=await u();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Tt(e));else if(t==="HP")l=await i(Uo(e));else if(t==="HBD")l=await i(Ho(e));else if(t==="POINTS")l=await i(ei(e));else if((await n.ensureQueryData(Dt(e))).some(m=>m.symbol===t))l=await i(Zo(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var Pl=(P=>(P.Transfer="transfer",P.TransferToSavings="transfer-saving",P.WithdrawFromSavings="withdraw-saving",P.Delegate="delegate",P.PowerUp="power-up",P.PowerDown="power-down",P.WithdrawRoutes="withdraw-routes",P.ClaimInterest="claim-interest",P.Swap="swap",P.Convert="convert",P.Gift="gift",P.Promote="promote",P.Claim="claim",P.Buy="buy",P.Stake="stake",P.Unstake="unstake",P.Undelegate="undelegate",P))(Pl||{});function UR(e,t,r){return b(["wallet","transfer"],e,n=>[Fe(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function WR(e,t,r){return b(["wallet","transfer-point"],e,n=>[Ue(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function XR(e,t,r){return b(["wallet","delegate-vesting-shares"],e,n=>[nt(e,n.delegatee,n.vestingShares)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nF(e,t,r){return b(["wallet","set-withdraw-vesting-route"],e,n=>[ot(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await E(t?.adapter,r,[c.wallet.withdrawRoutes(e),c.accounts.full(e),c.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function aF(e,t,r){return b(["wallet","transfer-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:o}]]},async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function dF(e,t,r){return b(["wallet","transfer-to-savings"],e,n=>[He(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function hF(e,t,r){return b(["wallet","transfer-from-savings"],e,n=>[qe(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function PF(e,t,r){return b(["wallet","transfer-to-vesting"],e,n=>[tt(e,n.to,n.amount)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function SF(e,t,r){return b(["wallet","withdraw-vesting"],e,n=>[rt(e,n.vestingShares)],async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function FF(e,t,r){return b(["wallet","convert"],e,n=>[n.collateralized?lr(e,n.amount,n.requestId):it(e,n.amount,n.requestId)],async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function BF(e,t,r){return b(["wallet","claim-interest"],e,n=>et(e,n.to,n.amount,n.memo,n.requestId),async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var Al=5e3,Bt=new Map;function UF(e,t,r){return b(["wallet","claim-rewards"],e,n=>[Sr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],c.assets.hiveGeneralInfo(e),c.assets.hbdGeneralInfo(e),c.assets.hivePowerGeneralInfo(e)],i=Bt.get(n);i&&(clearTimeout(i),Bt.delete(n));let s=setTimeout(async()=>{try{let a=_(),p=(await Promise.allSettled(o.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{Bt.delete(n);}},Al);Bt.set(n,s);},t,"posting",{broadcastMode:r})}function $F(e,t,r){return b(["wallet","delegate-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function JF(e,t,r){return b(["wallet","undelegate-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function eq(e,t,r){return b(["wallet","stake-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function oq(e,t,r){return b(["wallet","unstake-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function cq(e,t,r){return b(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function dq(e,t,r){return b(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Ol(e,t,r){let{from:n,to:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Fe(n,o,i,s)];case "transfer-saving":return [He(n,o,i,s)];case "withdraw-saving":return [qe(n,o,i,s,a)];case "power-up":return [tt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [Fe(n,o,i,s)];case "transfer-saving":return [He(n,o,i,s)];case "withdraw-saving":return [qe(n,o,i,s,a)];case "claim-interest":return et(n,o,i,s,a);case "convert":return [it(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [rt(n,i)];case "delegate":return [nt(n,o,i)];case "withdraw-routes":return [ot(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ue(n,o,i,s)];break}return null}function xl(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [Ke(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [Ke(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [Ke(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [Ke(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [Ke(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [dr(n,[e])]}return null}function El(e){return e==="claim"?"posting":"active"}function wq(e,t,r,n,o){let{mutateAsync:i}=Ve.useRecordActivity(e,r);return b(["ecency-wallets",t,r],e,s=>{let a=Ol(t,r,s);if(a)return a;let u=xl(t,r,s);if(u)return u;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{_().invalidateQueries({queryKey:a});});},5e3);},n,El(r),{broadcastMode:o})}function Pq(e,t,r){return b(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[fr(e,n,o)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),c.resourceCredits.account(e),c.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function Eq(e,t,r){return b(["witnesses","vote"],e,({witness:n,approve:o})=>[yr(e,n,o)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function Tq(e,t,r){return b(["witnesses","proxy"],e,({proxy:n})=>[hr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function kl(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function Dq(e){return infiniteQueryOptions({queryKey:c.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await X("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(kl),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function Iq(e,t,r,n="vests",o="desc"){return queryOptions({queryKey:c.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await X("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function Bq(e){return queryOptions({queryKey:c.witnesses.voterCount(e),queryFn:async()=>await X("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Cl=(y=>(y[y.CHECKIN=10]="CHECKIN",y[y.LOGIN=20]="LOGIN",y[y.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",y[y.POST=100]="POST",y[y.COMMENT=110]="COMMENT",y[y.VOTE=120]="VOTE",y[y.REBLOG=130]="REBLOG",y[y.DELEGATION=150]="DELEGATION",y[y.REFERRAL=160]="REFERRAL",y[y.COMMUNITY=170]="COMMUNITY",y[y.TRANSFER_SENT=998]="TRANSFER_SENT",y[y.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",y[y.MINTED=991]="MINTED",y))(Cl||{});async function Rl(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await h()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function jq(e,t,r,n){let{mutateAsync:o}=Ve.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>Rl(e,t),onError:n,onSuccess:()=>{o(),_().setQueryData(ct(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}function Gq(e,t,r,n,o,i){return queryOptions({queryKey:c.search.results(e,t,r,n,o,i),queryFn:async({signal:s})=>{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let u=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:he(we,s)});if(!u.ok)throw new Error(`Search failed: ${u.status}`);return u.json()}})}function zq(e,t,r=true){return infiniteQueryOptions({queryKey:c.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",u=e==="rising"?"children":e,p=i?i.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:u,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:he(we,o)});if(!y.ok)throw new Error(`Search failed: ${y.status}`);return y.json()},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r})}async function Vr(e){let r=await(async()=>{try{return await e.json()}catch{try{return await e.text()}catch{return}}})();if(!e.ok){let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}if(r===void 0)throw new Error("Response body was empty or invalid JSON");return r}async function Xq(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await h()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:he(we,s)});return Vr(p)}async function ri(e,t,r=we){let o=await h()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:he(r,t)});return Vr(o)}async function Zq(e,t){let n=await h()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:he(we,t)}),o=await Vr(n);return o?.length>0?o:[e]}var Dl=4368*60*60*1e3,Il=4,Bl=3e3,Ml=2e3,Nl=4e3,oK=2;function Ql(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Hl(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return (t>>>0).toString(36)}function iK(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=Ql(e.body??"",Bl),i=Hl(`${t}|${n.join(",")}|${o}`);return queryOptions({queryKey:c.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-Dl).toISOString().slice(0,19),u=await ri({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?Ml:Nl),p=[],l=new Set;for(let f of u.results){if(p.length>=Il)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function lK(e,t=5){let r=e.trim();return queryOptions({queryKey:c.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Ot(n)},enabled:!!r})}function yK(e,t=10){let r=e.trim();return queryOptions({queryKey:c.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function bK(e,t,r,n,o,i){return infiniteQueryOptions({queryKey:c.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let u={q:e,sort:t,hide_low:r};n&&(u.since=n),s&&(u.scroll_id=s),o!==void 0&&(u.votes=o),i&&(u.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(u),signal:he(we,a)});if(!p.ok)throw new Error(`Search failed: ${p.status}`);return p.json()},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e})}function OK(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function Wl(e){let r=await h()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function kK(e,t){let r=e?.replace("@","");return queryOptions({queryKey:c.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return Wl(t)},enabled:!!r&&!!t})}async function Jl(e,t){let n=await h()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function Yl(e,t,r){return e.setQueryData(c.support.settings(t),r),e.invalidateQueries({queryKey:c.support.settings(t)})}function qK(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Jl(t,o)},onSuccess(o){n&&Yl(r,n,o);}})}function BK(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function HK(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function LK(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function zK(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function ZK(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function nD(e,t,r){return b(["promotions","boost-plus"],e,({account:n,duration:o})=>[Fr(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function aD(e,t,r){return b(["promotions","rc-delegation"],e,({duration:n})=>[qr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function pD(e){let r=await h()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var od="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function mD(){return queryOptions({queryKey:c.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(od,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(`
|
|
1
|
+
import {QueryClient,useQuery,useInfiniteQuery,useMutation,queryOptions,infiniteQueryOptions,useQueryClient}from'@tanstack/react-query';import {hexToBytes,bytesToHex}from'@noble/hashes/utils.js';import {ripemd160}from'@noble/hashes/legacy.js';import Jr from'bs58';import {secp256k1}from'@noble/curves/secp256k1.js';import {sha256,sha512}from'@noble/hashes/sha2.js';import {cbc}from'@noble/ciphers/aes.js';import Mn from'hivesigner';var oi=Object.defineProperty;var ut=(e,t)=>{for(var r in t)oi(e,r,{get:t[r],enumerable:true});};var pt=new ArrayBuffer(0),lt=null,dt=null;function ii(){return lt||(typeof TextEncoder<"u"?lt=new TextEncoder:lt={encode(e){let t=[];for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n<128)t.push(n);else if(n<2048)t.push(192|n>>6,128|n&63);else if(n>=55296&&n<=56319&&r+1<e.length){let o=e.charCodeAt(++r);n=65536+((n&1023)<<10)+(o&1023),t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63);}else t.push(224|n>>12,128|n>>6&63,128|n&63);}return new Uint8Array(t)}}),lt}function jr(){return dt||(typeof TextDecoder<"u"?dt=new TextDecoder:dt={decode(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r="";for(let n=0;n<t.length;){let o=t[n],i;o<128?(i=o,n+=1):(o&224)===192?(i=(o&31)<<6|t[n+1]&63,n+=2):(o&240)===224?(i=(o&15)<<12|(t[n+1]&63)<<6|t[n+2]&63,n+=3):(i=(o&7)<<18|(t[n+1]&63)<<12|(t[n+2]&63)<<6|t[n+3]&63,n+=4),i<=65535?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296+(i>>10),56320+(i&1023)));}return r}}),dt}var q=class e{static LITTLE_ENDIAN=true;static BIG_ENDIAN=false;static DEFAULT_CAPACITY=16;static DEFAULT_ENDIAN=e.BIG_ENDIAN;buffer;view;offset;markedOffset;limit;littleEndian;constructor(t=e.DEFAULT_CAPACITY,r=e.DEFAULT_ENDIAN){this.buffer=t===0?pt:new ArrayBuffer(t),this.view=t===0?new DataView(pt):new DataView(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=t,this.littleEndian=r;}static allocate(t,r){return new e(t,r)}static concat(t,r){let n=0;for(let a=0;a<t.length;++a){let u=t[a];if(u instanceof e)n+=u.limit-u.offset;else if(u instanceof Uint8Array)n+=u.length;else if(u instanceof ArrayBuffer)n+=u.byteLength;else if(Array.isArray(u))n+=u.length;else throw TypeError("Illegal buffer")}if(n===0)return new e(0,r);let o=new e(n,r),i=new Uint8Array(o.buffer),s=0;for(let a=0;a<t.length;++a){let u=t[a];u instanceof e?(i.set(new Uint8Array(u.buffer,u.offset,u.limit-u.offset),s),s+=u.limit-u.offset):u instanceof Uint8Array?(i.set(u,s),s+=u.length):u instanceof ArrayBuffer?(i.set(new Uint8Array(u),s),s+=u.byteLength):(i.set(u,s),s+=u.length);}return o.limit=o.offset=s,o.offset=0,o}static wrap(t,r){if(t instanceof e){let o=t.clone();return o.markedOffset=-1,o}let n;if(t instanceof Uint8Array)n=new e(0,r),t.length>0&&(n.buffer=t.buffer,n.offset=t.byteOffset,n.limit=t.byteOffset+t.byteLength,n.view=new DataView(t.buffer));else if(t instanceof ArrayBuffer)n=new e(0,r),t.byteLength>0&&(n.buffer=t,n.offset=0,n.limit=t.byteLength,n.view=t.byteLength>0?new DataView(t):new DataView(pt));else if(Array.isArray(t))n=new e(t.length,r),n.limit=t.length,new Uint8Array(n.buffer).set(t);else throw TypeError("Illegal buffer");return n}writeBytes(t,r){return this.append(t,r)}writeInt8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setInt8(r,t),n&&(this.offset+=1),this}writeByte(t,r){return this.writeInt8(t,r)}writeUint8(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+1>this.buffer.byteLength&&this.resize(r+1),this.view.setUint8(r,t),n&&(this.offset+=1),this}writeUInt8(t,r){return this.writeUint8(t,r)}readUint8(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint8(t);return r&&(this.offset+=1),n}readUInt8(t){return this.readUint8(t)}writeInt16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setInt16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeShort(t,r){return this.writeInt16(t,r)}writeUint16(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+2>this.buffer.byteLength&&this.resize(r+2),this.view.setUint16(r,t,this.littleEndian),n&&(this.offset+=2),this}writeUInt16(t,r){return this.writeUint16(t,r)}writeInt32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setInt32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeInt(t,r){return this.writeInt32(t,r)}writeUint32(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,r+4>this.buffer.byteLength&&this.resize(r+4),this.view.setUint32(r,t,this.littleEndian),n&&(this.offset+=4),this}writeUInt32(t,r){return this.writeUint32(t,r)}readUint32(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getUint32(t,this.littleEndian);return r&&(this.offset+=4),n}readUInt32=this.readUint32;append(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let o;return t instanceof e?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.length),this)}clone(t){let r=new e(0,this.littleEndian);return t?(r.buffer=new ArrayBuffer(this.buffer.byteLength),new Uint8Array(r.buffer).set(new Uint8Array(this.buffer)),r.view=new DataView(r.buffer)):(r.buffer=this.buffer,r.view=this.view),r.offset=this.offset,r.markedOffset=this.markedOffset,r.limit=this.limit,r}copy(t,r){if(t===void 0&&(t=this.offset),r===void 0&&(r=this.limit),t===r)return new e(0,this.littleEndian);let n=r-t,o=new e(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(t.offset+=a),this)}ensureCapacity(t){let r=this.buffer.byteLength;return r<t?this.resize((r*=2)>t?r:t):this}flip(){return this.limit=this.offset,this.offset=0,this}resize(t){if(this.buffer.byteLength<t){let r=new ArrayBuffer(t);new Uint8Array(r).set(new Uint8Array(this.buffer)),this.buffer=r,this.view=new DataView(r);}return this}skip(t){return this.offset+=t,this}writeInt64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigInt64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeLong(t,r){return this.writeInt64(t,r)}readInt64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigInt64(t,this.littleEndian);return r&&(this.offset+=8),n}readLong(t){return this.readInt64(t)}writeUint64(t,r){let n=typeof r>"u";return n?r=this.offset:r=r,typeof t=="number"&&(t=BigInt(t)),r+8>this.buffer.byteLength&&this.resize(r+8),this.view.setBigUint64(r,t,this.littleEndian),n&&(this.offset+=8),this}writeUInt64(t,r){return this.writeUint64(t,r)}readUint64(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=this.view.getBigUint64(t,this.littleEndian);return r&&(this.offset+=8),n}readUInt64(t){return this.readUint64(t)}toBuffer(t){let r=this.offset,n=this.limit;return !t&&r===0&&n===this.buffer.byteLength?this.buffer:r===n?pt:this.buffer.slice(r,n)}toArrayBuffer(t){return this.toBuffer(t)}writeVarint32(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,length:n}}calculateVarint32(t){return t=t>>>0,t<128?1:t<16384?2:t<1<<21?3:t<1<<28?4:5}writeVString(t,r){let n=typeof r>"u",o=n?this.offset:r,i=ii().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=jr().decode(new Uint8Array(this.buffer,t,i));return t+=i,r?(this.offset=t,a):{string:a,length:t-n}}readUTF8String(t,r){let n=typeof r>"u";n?r=this.offset:r=r;let o=jr().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,length:t}}};var x={nodes:["https://api.hive.blog","https://api.deathwing.me","https://api.openhive.network","https://techcoderx.com","https://api.syncad.com","https://rpc.mahdiyari.info"],restNodes:["https://api.hive.blog","https://rpc.mahdiyari.info","https://api.syncad.com","https://hiveapi.actifit.io","https://api.c0ff33a.uk"],restNodesByApi:{hivesense:["https://api.hive.blog","https://api.syncad.com"]},userAgent:"ecency-sdk",chain_id:"beeab0de00000000000000000000000000000000000000000000000000000000",address_prefix:"STM",timeout:5e3,broadcastTimeout:15e3,retry:5,resilience:{adaptiveTimeout:true,adaptiveTimeoutFloorMs:2e3,adaptiveTimeoutFactor:4,hedge:false,hedgeDelayFloorMs:750,hedgeDelayFactor:2,hedgeBucketCapacity:10,hedgeRefillPerSuccess:.1,totalBudgetFactor:2}},Qt=e=>Array.isArray(e)?[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim().replace(/\/+$/,"")).filter(t=>t.length>0&&/^https?:\/\/.+/.test(t)))]:[],Ht=e=>{let t=Qt(e);t.length&&(x.nodes=t);},Ut=e=>{let t=Qt(e);t.length&&(x.restNodes=t);},Vt=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=Qt(n);o.length?t[r]=o:delete t[r];}x.restNodesByApi=t;},jt=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},Lt=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>0;r(e.adaptiveTimeout)&&(t.adaptiveTimeout=e.adaptiveTimeout),n(e.adaptiveTimeoutFloorMs)&&(t.adaptiveTimeoutFloorMs=Math.max(e.adaptiveTimeoutFloorMs,2e3)),n(e.adaptiveTimeoutFactor)&&(t.adaptiveTimeoutFactor=e.adaptiveTimeoutFactor),r(e.hedge)&&(t.hedge=e.hedge),n(e.hedgeDelayFloorMs)&&(t.hedgeDelayFloorMs=e.hedgeDelayFloorMs),n(e.hedgeDelayFactor)&&(t.hedgeDelayFactor=e.hedgeDelayFactor),n(e.hedgeBucketCapacity)&&(t.hedgeBucketCapacity=e.hedgeBucketCapacity),n(e.hedgeRefillPerSuccess)&&(t.hedgeRefillPerSuccess=Math.min(e.hedgeRefillPerSuccess,1)),n(e.totalBudgetFactor)&&(t.totalBudgetFactor=Math.max(e.totalBudgetFactor,1));};var be=class e{data;recovery;compressed;constructor(t,r,n){this.data=t,this.recovery=r,this.compressed=n??true;}static from(t){if(typeof t=="string"){let r=hexToBytes(t),n=parseInt(bytesToHex(r.subarray(0,1)),16)-31,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}else throw new Error("Expected string for data")}toBuffer(){let t=new Uint8Array(65).fill(0);return this.compressed?t[0]=this.recovery+31&255:t[0]=this.recovery+27&255,t.set(this.data,1),t}customToString(){return bytesToHex(this.toBuffer())}toString(){return this.customToString()}getPublicKey(t){if(t instanceof Uint8Array&&t.length!==32||typeof t=="string"&&t.length!==64)throw new Error("Expected a valid sha256 hash as message");typeof t=="string"&&(t=hexToBytes(t));let r=secp256k1.Signature.fromBytes(this.data,"compact"),n=new secp256k1.Signature(r.r,r.s,this.recovery);return new G(n.recoverPublicKey(t).toBytes())}};var G=class e{key;prefix;constructor(t,r){this.key=t,this.prefix=r??x.address_prefix;}static fromString(t){let r=x.address_prefix;if(typeof t!="string"||t.length<=r.length)throw new Error("Invalid public key");let n=t.slice(0,r.length);if(n!==r)throw new Error(`Public key must start with ${r}`);let o;try{o=Jr.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=ripemd160(i).subarray(0,4);if(!ai(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=be.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return si(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},si=(e,t)=>{let r=ripemd160(e);return t+Jr.encode(new Uint8Array([...e,...r.subarray(0,4)]))},ai=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return false;return true};var ft=class e{amount;symbol;constructor(t,r){this.amount=t,this.symbol=r==="HIVE"?"STEEM":r==="HBD"?"SBD":r;}static fromString(t,r=null){let[n,o]=t.split(" ");if(["STEEM","VESTS","SBD","TESTS","TBD","HIVE","HBD"].indexOf(o)===-1)throw new Error(`Invalid asset symbol: ${o}`);if(r&&o!==r)throw new Error(`Invalid asset, expected symbol: ${r} got: ${o}`);let i=Number.parseFloat(n);if(!Number.isFinite(i))throw new Error(`Invalid asset amount: ${n}`);return new e(i,o)}static from(t,r){if(t instanceof e){if(r&&t.symbol!==r)throw new Error(`Invalid asset, expected symbol: ${r} got: ${t.symbol}`);return t}else {if(typeof t=="number"&&Number.isFinite(t))return new e(t,r||"STEEM");if(typeof t=="string")return e.fromString(t,r);throw new Error(`Invalid asset '${String(t)}'`)}}getPrecision(){switch(this.symbol){case "TESTS":case "TBD":case "STEEM":case "SBD":case "HBD":case "HIVE":return 3;case "VESTS":return 6;default:return 3}}toString(){return `${this.amount.toFixed(this.getPrecision())} ${this.symbol}`}toJSON(){return this.toString()}};var mt=class e{buffer;static from(t){return t instanceof e?t:t instanceof Uint8Array?new e(t):typeof t=="string"?new e(hexToBytes(t)):new e(new Uint8Array(t))}constructor(t){this.buffer=t;}toString(){return bytesToHex(this.buffer)}toJSON(){return this.toString()}};var C={vote:0,comment:1,transfer:2,transfer_to_vesting:3,withdraw_vesting:4,limit_order_create:5,limit_order_cancel:6,feed_publish:7,convert:8,account_create:9,account_update:10,witness_update:11,account_witness_vote:12,account_witness_proxy:13,custom:15,delete_comment:17,custom_json:18,comment_options:19,set_withdraw_vesting_route:20,limit_order_create2:21,claim_account:22,create_claimed_account:23,request_account_recovery:24,recover_account:25,change_recovery_account:26,escrow_transfer:27,escrow_dispute:28,escrow_release:29,escrow_approve:31,transfer_to_savings:32,transfer_from_savings:33,cancel_transfer_from_savings:34,decline_voting_rights:36,reset_account:37,set_reset_account:38,claim_reward_balance:39,delegate_vesting_shares:40,account_create_with_delegation:41,witness_set_properties:42,account_update2:43,create_proposal:44,update_proposal_votes:45,remove_proposal:46,update_proposal:47,collateralized_convert:48,recurrent_transfer:49},ne=()=>{throw new Error("Void can not be serialized")},w=(e,t)=>{e.writeVString(t);},pi=(e,t)=>{e.writeInt16(t);},Xr=(e,t)=>{e.writeInt64(t);},Yr=(e,t)=>{e.writeUint8(t);},ae=(e,t)=>{e.writeUint16(t);},z=(e,t)=>{e.writeUint32(t);},Zr=(e,t)=>{e.writeUint64(t);},me=(e,t)=>{e.writeByte(t?1:0);},en=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},F=(e,t)=>{let r=ft.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||0);},ve=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},de=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(G.from(t).key);},tn=(e=null)=>(t,r)=>{r=mt.from(r);let n=r.buffer.length;if(e){if(n!==e)throw new Error(`Unable to serialize binary. Expected ${e} bytes, got ${n}`)}else t.writeVarint32(n);t.append(r.buffer);},rn=tn(),$t=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},U=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},ce=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Oe=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},L=ce([["weight_threshold",z],["account_auths",$t(w,ae)],["key_auths",$t(de,ae)]]),li=ce([["account",w],["weight",ae]]),Wt=ce([["base",F],["quote",F]]),di=ce([["account_creation_fee",F],["maximum_block_size",z],["hbd_interest_rate",ae]]),T=(e,t)=>{let r=ce(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},S={};S.account_create=T(C.account_create,[["fee",F],["creator",w],["new_account_name",w],["owner",L],["active",L],["posting",L],["memo_key",de],["json_metadata",w]]);S.account_create_with_delegation=T(C.account_create_with_delegation,[["fee",F],["delegation",F],["creator",w],["new_account_name",w],["owner",L],["active",L],["posting",L],["memo_key",de],["json_metadata",w],["extensions",U(ne)]]);S.account_update=T(C.account_update,[["account",w],["owner",Oe(L)],["active",Oe(L)],["posting",Oe(L)],["memo_key",de],["json_metadata",w]]);S.account_witness_proxy=T(C.account_witness_proxy,[["account",w],["proxy",w]]);S.account_witness_vote=T(C.account_witness_vote,[["account",w],["witness",w],["approve",me]]);S.cancel_transfer_from_savings=T(C.cancel_transfer_from_savings,[["from",w],["request_id",z]]);S.change_recovery_account=T(C.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",U(ne)]]);S.claim_account=T(C.claim_account,[["creator",w],["fee",F],["extensions",U(ne)]]);S.claim_reward_balance=T(C.claim_reward_balance,[["account",w],["reward_hive",F],["reward_hbd",F],["reward_vests",F]]);S.comment=T(C.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);S.comment_options=T(C.comment_options,[["author",w],["permlink",w],["max_accepted_payout",F],["percent_hbd",ae],["allow_votes",me],["allow_curation_rewards",me],["extensions",U(en([ce([["beneficiaries",U(li)]])]))]]);S.convert=T(C.convert,[["owner",w],["requestid",z],["amount",F]]);S.create_claimed_account=T(C.create_claimed_account,[["creator",w],["new_account_name",w],["owner",L],["active",L],["posting",L],["memo_key",de],["json_metadata",w],["extensions",U(ne)]]);S.custom=T(C.custom,[["required_auths",U(w)],["id",ae],["data",rn]]);S.custom_json=T(C.custom_json,[["required_auths",U(w)],["required_posting_auths",U(w)],["id",w],["json",w]]);S.decline_voting_rights=T(C.decline_voting_rights,[["account",w],["decline",me]]);S.delegate_vesting_shares=T(C.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",F]]);S.delete_comment=T(C.delete_comment,[["author",w],["permlink",w]]);S.escrow_approve=T(C.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",z],["approve",me]]);S.escrow_dispute=T(C.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",z]]);S.escrow_release=T(C.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",z],["hbd_amount",F],["hive_amount",F]]);S.escrow_transfer=T(C.escrow_transfer,[["from",w],["to",w],["hbd_amount",F],["hive_amount",F],["escrow_id",z],["agent",w],["fee",F],["json_meta",w],["ratification_deadline",ve],["escrow_expiration",ve]]);S.feed_publish=T(C.feed_publish,[["publisher",w],["exchange_rate",Wt]]);S.limit_order_cancel=T(C.limit_order_cancel,[["owner",w],["orderid",z]]);S.limit_order_create=T(C.limit_order_create,[["owner",w],["orderid",z],["amount_to_sell",F],["min_to_receive",F],["fill_or_kill",me],["expiration",ve]]);S.limit_order_create2=T(C.limit_order_create2,[["owner",w],["orderid",z],["amount_to_sell",F],["exchange_rate",Wt],["fill_or_kill",me],["expiration",ve]]);S.recover_account=T(C.recover_account,[["account_to_recover",w],["new_owner_authority",L],["recent_owner_authority",L],["extensions",U(ne)]]);S.request_account_recovery=T(C.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",L],["extensions",U(ne)]]);S.reset_account=T(C.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",L]]);S.set_reset_account=T(C.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);S.set_withdraw_vesting_route=T(C.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",ae],["auto_vest",me]]);S.transfer=T(C.transfer,[["from",w],["to",w],["amount",F],["memo",w]]);S.transfer_from_savings=T(C.transfer_from_savings,[["from",w],["request_id",z],["to",w],["amount",F],["memo",w]]);S.transfer_to_savings=T(C.transfer_to_savings,[["from",w],["to",w],["amount",F],["memo",w]]);S.transfer_to_vesting=T(C.transfer_to_vesting,[["from",w],["to",w],["amount",F]]);S.vote=T(C.vote,[["voter",w],["author",w],["permlink",w],["weight",pi]]);S.withdraw_vesting=T(C.withdraw_vesting,[["account",w],["vesting_shares",F]]);S.witness_update=T(C.witness_update,[["owner",w],["url",w],["block_signing_key",de],["props",di],["fee",F]]);S.witness_set_properties=T(C.witness_set_properties,[["owner",w],["props",$t(w,rn)],["extensions",U(ne)]]);S.account_update2=T(C.account_update2,[["account",w],["owner",Oe(L)],["active",Oe(L)],["posting",Oe(L)],["memo_key",Oe(de)],["json_metadata",w],["posting_json_metadata",w],["extensions",U(ne)]]);S.create_proposal=T(C.create_proposal,[["creator",w],["receiver",w],["start_date",ve],["end_date",ve],["daily_pay",F],["subject",w],["permlink",w],["extensions",U(ne)]]);S.update_proposal_votes=T(C.update_proposal_votes,[["voter",w],["proposal_ids",U(Xr)],["approve",me],["extensions",U(ne)]]);S.remove_proposal=T(C.remove_proposal,[["proposal_owner",w],["proposal_ids",U(Xr)],["extensions",U(ne)]]);var fi=ce([["end_date",ve]]);S.update_proposal=T(C.update_proposal,[["proposal_id",Zr],["creator",w],["daily_pay",F],["subject",w],["permlink",w],["extensions",U(en([ne,fi]))]]);S.collateralized_convert=T(C.collateralized_convert,[["owner",w],["requestid",z],["amount",F]]);S.recurrent_transfer=T(C.recurrent_transfer,[["from",w],["to",w],["amount",F],["memo",w],["recurrence",ae],["executions",ae],["extensions",U(ce([["type",Yr],["value",ce([["pair_id",Yr]])]]))]]);var mi=(e,t)=>{let r=S[t[0]];if(!r)throw new Error(`No serializer for operation: ${t[0]}`);try{r(e,t[1]);}catch(n){throw n.message=`${t[0]}: ${n.message}`,n}},gi=ce([["ref_block_num",ae],["ref_block_prefix",z],["expiration",ve],["operations",U(mi)],["extensions",U(w)]]),yi=ce([["from",de],["to",de],["nonce",Zr],["check",z],["encrypted",tn()]]),ue={Asset:F,Memo:yi,Price:Wt,PublicKey:de,String:w,Transaction:gi,UInt16:ae,UInt32:z};var Ge=e=>new Promise(t=>setTimeout(t,e));var hi=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function an(){return hi?{"User-Agent":x.userAgent}:{}}var J=class extends Error{name="RPCError";data;code;stack=void 0;constructor(t){super(t.message),this.code=t.code,"data"in t&&(this.data=t.data);}},xe=class extends Error{node;rateLimitMs;isRateLimit;constructor(t,r,n={}){super(r),this.node=t,this.rateLimitMs=n.rateLimitMs??0,this.isRateLimit=n.isRateLimit??false;}};function cn(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t))return t>0?t*1e3:0;let r=Date.parse(e);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return 0}var wi=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],_i=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function bi(e){if(!e)return "";let t=[String(e.name||""),String(e.message||""),String(e.code||"")],r=e.cause;for(let n=0;r&&n<5;n++)t.push(String(r.code||""),String(r.message||"")),r=r.cause;return t.join(" ")}function vi(e){if(!e)return false;if(e instanceof xe)return true;if(e instanceof J)return false;let t=bi(e);return !!(wi.some(r=>t.includes(r))||_i.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function Gt(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function un(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var Pi=1e4,Ai=6e4,Oi=12e4,nn=2,on=6e4,sn=12e4,xi=30,ze=.3,zt=3,Je=5*6e4,pn=6e4,ln=1e3,dn=2e3,yt=class{health=new Map;getOrCreate(t){let r=this.health.get(t);return r||(r={consecutiveFailures:0,lastFailureTime:0,rateLimitedUntil:0,rateLimitStreak:0,lastRateLimitAt:0,apiFailures:new Map,headBlock:0,headBlockUpdatedAt:0,ewmaLatencyMs:void 0,latencySampleCount:0,latencyUpdatedAt:0,lastProbeAt:Date.now(),apiLatency:new Map},this.health.set(t,r)),r}recordSuccess(t,r,n,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r<dn||this.recordLatency(this.getOrCreate(t),r,n);}getUsableLatencyMs(t,r){let n=this.health.get(t);if(!n)return;let o=Date.now();if(r!==void 0){let i=n.apiLatency.get(r);return i&&i.sampleCount>=zt&&o-i.updatedAt<=Je?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?n.ewmaLatencyMs:void 0}recordCensoredLatency(t,r,n){!Number.isFinite(r)||r<50||this.recordLatency(this.getOrCreate(t),r,n);}recordLatency(t,r,n){let o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>Je&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:ze*r+(1-ze)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>Je?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=ze*r+(1-ze)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=nn&&(i.cooldownUntil=o+on),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,nn),i.lastFailureTime=o,i.cooldownUntil=o+on,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>Oi&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(Pi*2**n.rateLimitStreak,Ai);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}recordHeadBlock(t,r){if(!r||!Number.isFinite(r))return;let n=this.getOrCreate(t);n.headBlock=r,n.headBlockUpdatedAt=Date.now();}consensusHeadBlock(){let t=Date.now(),r=[];for(let n of this.health.values())n.headBlock>0&&t-n.headBlockUpdatedAt<=sn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=sn&&i-n.headBlock>xi)}getOrderedNodes(t,r){let n=[],o=[];for(let u of t)this.isNodeHealthy(u,r)?n.push(u):o.push(u);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((u,p)=>({node:u,i:p,score:this.scoreNode(u,i)})).sort((u,p)=>u.score-p.score||u.i-p.i).map(u=>u.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(u=>u!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=zt&&r-t.latencyUpdatedAt<=Je}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:ln}pickReprobeCandidate(t,r){let n=r-pn,o,i=1/0;for(let s of t){let a=this.getOrCreate(s),u=Math.max(a.latencyUpdatedAt,a.lastProbeAt);u<=n&&u<i&&(o=s,i=u);}return o&&(this.getOrCreate(o).lastProbeAt=r),o}},V=new yt,Pe=new yt,Jt=class{tokens=x.resilience.hedgeBucketCapacity;trySpend(){return this.clamp(),this.tokens>=1-1e-9?(this.tokens-=1,true):false}refill(){this.clamp(),this.tokens=Math.min(x.resilience.hedgeBucketCapacity,this.tokens+x.resilience.hedgeRefillPerSuccess);}clamp(){this.tokens>x.resilience.hedgeBucketCapacity&&(this.tokens=x.resilience.hedgeBucketCapacity);}get available(){return this.tokens}reset(t=x.resilience.hedgeBucketCapacity){this.tokens=t;}},Yt=new Jt;function ht(e,t,r,n,o){let i=x.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function Xt(e,t,r,n){r instanceof xe?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof J?e.recordFailure(t,n):e.recordFailure(t);}function fn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function Ei(){if(typeof DOMException<"u")return new DOMException("The operation was aborted due to timeout","TimeoutError");let e=new Error("The operation was aborted due to timeout");return e.name="TimeoutError",e}function mn(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(Ei()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function Zt(e,t){if(!t)return {signal:e,cleanup:()=>{}};if(typeof AbortSignal.any=="function")return {signal:AbortSignal.any([e,t]),cleanup:()=>{}};let r=new AbortController;if(e.aborted)return r.abort(e.reason),{signal:r.signal,cleanup:()=>{}};if(t.aborted)return r.abort(t.reason),{signal:r.signal,cleanup:()=>{}};let n=()=>r.abort(e.reason),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var Ye=async(e,t,r,n=x.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:u,cleanup:p}=mn(n),{signal:l,cleanup:f}=Zt(u,i),m=()=>{p(),f();};try{let y=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...an()},signal:l});if(y.status===429)throw new xe(e,"HTTP 429 Rate Limited",{rateLimitMs:cn(y.headers.get("Retry-After")),isRateLimit:!0});if(y.status>=500&&y.status<600)throw new xe(e,`HTTP ${y.status} from ${e}`);let A=await y.json();if(!A||typeof A.id>"u"||A.id!==s||A.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in A)return A.result;if("error"in A){let O=A.error;throw "message"in O&&"code"in O?new J(O):A.error}throw A}catch(y){if(y instanceof J||y instanceof xe||i?.aborted)throw y;if(o)return Ye(e,t,r,n,false,i);throw y}finally{m();}};function gt(){return Ge(50+Math.random()*50)}function Si(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:u,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,y)=>{let A=false,O=0,v=false,P=false,I,B,j=0,Q=[],ee=W=>{if(!A){A=true,B!==void 0&&(clearTimeout(B),B=void 0);for(let R of Q)R.signal.aborted||R.abort();W();}},Ie=(W,R)=>{O++;let le=new AbortController;Q.push(le);let We=Zt(le.signal,p),ni=ht(V,W,t,s,a),Nt=Date.now();R||(j=Nt),Ye(W,t,r,ni,false,We.signal).then(re=>{if(We.cleanup(),O--,R||(P=true),!A){if(f&&!f(re)){if(V.recordDefectiveResponse(W,n),I=new Error(`[hive-tx] response validation failed for ${t} from ${W}`),!R&&!v){ee(()=>y(I));return}O===0&&ee(()=>y(I));return}V.recordSuccess(W,n,Date.now()-Nt,t),fn(V,W,t,re),R?P||V.recordCensoredLatency(o,Date.now()-j,t):v||Yt.refill(),ee(()=>m(re));}}).catch(re=>{if(We.cleanup(),O--,R||(P=true),!A){if(p?.aborted){ee(()=>y(re));return}if(re instanceof J&&!Gt(re.code,re.message)){ee(()=>y(re));return}if(Xt(V,W,re,n),V.recordSlowFailure(W,Date.now()-Nt,t),I=re,!R&&!v){ee(()=>y(re));return}O===0&&ee(()=>y(I));}});};Ie(o,false);let Le=V.getUsableLatencyMs(o,t)??0,$e=ht(V,o,t,s,a),Mt=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*Le),.8*$e);B=setTimeout(()=>{if(B=void 0,A||p?.aborted||Date.now()>=u)return;let W=i.filter(le=>V.isNodeHealthy(le,n));if(W.length===0)return;let R=W[Math.floor(Math.random()*W.length)];Yt.trySpend()&&(v=true,l(R),Ie(R,true));},Mt);})}var g=async(e,t=[],r,n=x.retry,o,i)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let s=r!==void 0,a=r??x.timeout,u=un(e),p=Date.now()+x.resilience.totalBudgetFactor*a,l=new Set,f;for(let m=0;m<=n&&!(m>0&&Date.now()>=p);m++){let y=V.getOrderedNodes(x.nodes,u),A=y.find(P=>!l.has(P));A||(l.clear(),A=y[0]),l.add(A);let O=[];if(x.resilience.hedge&&V.getUsableLatencyMs(A,e)!==void 0&&(O=y.filter(P=>!l.has(P)&&V.isNodeHealthy(P,u)).slice(0,3)),O.length>0)try{return await Si({method:e,params:t,api:u,primary:A,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:p,externalSignal:o,onHedgeFired:P=>l.add(P),validate:i})}catch(P){if(P instanceof J&&!Gt(P.code,P.message)||o?.aborted)throw P;f=P,m<n&&await gt();continue}let v=Date.now();try{let P=await Ye(A,e,t,ht(V,A,e,a,s),!1,o);if(i&&!i(P)){V.recordDefectiveResponse(A,u),f=new Error(`[hive-tx] response validation failed for ${e} from ${A}`),m<n&&await gt();continue}return V.recordSuccess(A,u,Date.now()-v,e),Yt.refill(),fn(V,A,e,P),P}catch(P){if(P instanceof J&&!Gt(P.code,P.message)||o?.aborted)throw P;Xt(V,A,P,u),V.recordSlowFailure(A,Date.now()-v,e),f=P,m<n&&await gt();}}throw f},Be=async(e,t=[],r=x.broadcastTimeout,n)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an array");if(x.nodes.length===0)throw new Error("config.nodes is empty");let o=un(e),i=new Set,s;for(let a=0;a<x.nodes.length;a++){let p=V.getOrderedNodes(x.nodes,o).find(l=>!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await Ye(p,e,t,r,!1,n);return V.recordSuccess(p,o),l}catch(l){if(l instanceof J||n?.aborted||(Xt(V,p,l,o),s=l,!vi(l)))throw l}}throw s},ki={balance:"/balance-api",hafah:"/hafah-api",hafbe:"/hafbe-api",hivemind:"/hivemind-api",hivesense:"/hivesense-api",reputation:"/reputation-api","nft-tracker":"/nft-tracker-api",hafsql:"/hafsql",status:"/status-api"};async function X(e,t,r,n,o=x.retry,i){if(!Array.isArray(x.restNodes))throw new Error("config.restNodes is not an array");if(x.restNodes.length===0)throw new Error("config.restNodes is empty");let s=n!==void 0,a=n??x.timeout,u=Date.now()+x.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=x.restNodesByApi?.[e]?.length?x.restNodesByApi[e]:x.restNodes,f=new Set,m,y=false;for(let A=0;A<=o&&!(A>0&&Date.now()>=u);A++){let O=Pe.getOrderedNodes(l,e),v=O.find(R=>!f.has(R));v||(f.clear(),v=O[0]),f.add(v);let P=v+ki[e],I=t,B=r||{},j=new Set;Object.entries(B).forEach(([R,le])=>{I.includes(`{${R}}`)&&(I=I.replace(`{${R}}`,encodeURIComponent(String(le))),j.add(R));});let Q=new URL(P+I);if(Object.entries(B).forEach(([R,le])=>{j.has(R)||(Array.isArray(le)?le.forEach(We=>Q.searchParams.append(R,String(We))):Q.searchParams.set(R,String(le)));}),i?.aborted)throw new Error("Aborted");y=false;let{signal:ee,cleanup:Ie}=mn(ht(Pe,v,p,a,s)),{signal:Le,cleanup:$e}=Zt(ee,i),Mt=()=>{Ie(),$e();},W=Date.now();try{let R=await fetch(Q.toString(),{signal:Le,headers:an()});if(R.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(R.status===429)throw Pe.recordRateLimit(v,cn(R.headers.get("Retry-After"))||void 0),y=!0,new Error(`HTTP 429 Rate Limited by ${v}`);if(R.status===503)throw Pe.recordFailure(v,e),y=!0,new Error(`HTTP 503 Service Unavailable from ${v}`);if(!R.ok)throw Pe.recordFailure(v,e),y=!0,new Error(`HTTP ${R.status} from ${v}`);return Pe.recordSuccess(v,e,Date.now()-W,p),R.json()}catch(R){if(R?.message?.includes("HTTP 404")||i?.aborted)throw R;y||Pe.recordFailure(v,e),Pe.recordSlowFailure(v,Date.now()-W,p),m=R,A<o&&await gt();}finally{Mt();}}throw m}var wt=async(e,t=[],r=2,n)=>{if(!Array.isArray(x.nodes))throw new Error("config.nodes is not an Array");if(r>x.nodes.length)throw new Error("quorum > config.nodes.length");let i=(u=>{let p=[...u];for(let l=p.length-1;l>0;l--){let f=Math.floor(Math.random()*(l+1));[p[l],p[f]]=[p[f],p[l]];}return p})(x.nodes),s=Math.min(r,i.length),a=[];for(;s>0&&i.length>0;){let u=i.splice(0,s),p=[],l=[];for(let m=0;m<u.length;m++)p.push(Ye(u[m],e,t,void 0,true,n).then(y=>l.push(y)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Ci(a,r);if(f)return f;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Ci(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var Ri=hexToBytes(x.chain_id),Ee=class e{transaction;expiration=6e4;txId;constructor(t){t?.transaction&&(t.transaction instanceof e?(this.transaction=t.transaction.transaction,this.expiration=t.transaction.expiration):this.transaction=t.transaction,this.transaction&&!Array.isArray(this.transaction.signatures)&&(this.transaction.signatures=[]),this.txId=this.digest().txId),t?.expiration&&(this.expiration=t.expiration);}async addOperation(t,r){this.transaction||await this.createTransaction(this.expiration),this.transaction.operations.push([t,r]);}sign(t){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");if(this.transaction){let{digest:r,txId:n}=this.digest();Array.isArray(t)||(t=[t]);for(let o of t){let i=o.sign(r);this.transaction.signatures.push(i.customToString());}return this.txId=n,this.transaction}else throw new Error("No transaction to sign")}async broadcast(t=false){if(!this.transaction)throw new Error("Attempted to broadcast an empty transaction. Add operations by .addOperation()");if(this.transaction.signatures.length===0)throw new Error("Attempted to broadcast a transaction with no signatures. Sign using .sign(keys)");try{await Be("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof J&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await Ge(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o<r;)await Ge(1e3+o*300),n=await this.checkStatus(),o++;return {tx_id:this.txId,status:n?.status??"unknown"}}digest(){if(!this.transaction)throw new Error("First create a transaction by .addOperation()");let t=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN),r={...this.transaction};try{ue.Transaction(t,r);}catch(s){throw new Error("Unable to serialize transaction: "+s)}t.flip();let n=new Uint8Array(t.toBuffer()),o=bytesToHex(sha256(n)).slice(0,40);return {digest:sha256(new Uint8Array([...Ri,...n])),txId:o}}addSignature(t){if(!this.transaction)throw new Error("First create a transaction by .create(operations)");if(typeof t!="string")throw new Error("Signature must be string");if(t.length!==130)throw new Error("Signature must be 130 characters long");return this.transaction.signatures.push(t),this.transaction}async checkStatus(){return this.txId||(this.txId=this.digest().txId),g("transaction_status_api.find_transaction",{transaction_id:this.txId,expiration:this.transaction?.expiration})}createTransaction=async t=>{let r=await g("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,signatures:[]};}};var bn=new Uint8Array([128]),H=class e{key;constructor(t){this.key=t;try{secp256k1.getPublicKey(t);}catch{throw new Error("invalid private key")}}static from(t){return typeof t=="string"?e.fromString(t):new e(t)}static fromString(t){return new e(Di(t).subarray(1))}static fromSeed(t){if(typeof t=="string")if(/^[0-9a-fA-F]+$/.test(t))t=hexToBytes(t);else {let n=[];for(let o=0;o<t.length;o++){let i=t.charCodeAt(o);if(i<128)n.push(i);else if(i<2048)n.push(192|i>>6,128|i&63);else if(i>=55296&&i<=56319&&o+1<t.length){let s=t.charCodeAt(++o);i=65536+((i&1023)<<10)+(s&1023),n.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return be.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new G(secp256k1.getPublicKey(this.key),t)}toString(){return Ki(new Uint8Array([...bn,...this.key]))}inspect(){let t=this.toString();return `PrivateKey: ${t.slice(0,6)}...${t.slice(-6)}`}getSharedSecret(t){let r=secp256k1.getSharedSecret(this.key,t.key);return sha512(r.subarray(1))}static randomKey(){return new e(secp256k1.keygen().secretKey)}},vn=e=>sha256(sha256(e)),Ki=e=>{let t=vn(e);return Jr.encode(new Uint8Array([...e,...t.slice(0,4)]))},Di=e=>{let t=Jr.decode(e);if(!wn(t.slice(0,1),bn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=vn(n).slice(0,4);if(!wn(r,o))throw new Error("Private key checksum mismatch");return n},wn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;n<r&&e[n]===t[n];)n++;return n===r};var An=(e,t,r,n=Hi())=>xn(e,t,n,r),On=(e,t,r,n,o)=>xn(e,t,r,n,o).message,xn=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);a.writeUint64(i),a.append(s),a.flip();let u=sha512(new Uint8Array(a.toBuffer())),p=u.subarray(32,48),l=u.subarray(0,32),f=sha256(u).subarray(0,4),m=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);m.append(f),m.flip();let y=m.readUint32();if(o!==void 0){if(y!==o)throw new Error("Invalid key");n=Ni(n,l,p);}else n=Qi(n,l,p);return {nonce:i,message:n,checksum:y}},Ni=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},Qi=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},tr=null,Hi=()=>{if(tr===null){let r=secp256k1.utils.randomSecretKey();tr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++tr%65536;return e=e<<BigInt(16)|BigInt(t),e};var En=e=>{let t=Wi(e,33);return new G(t)},Vi=e=>e.readUint64(),ji=e=>e.readUint32(),Li=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},$i=e=>t=>{let r={},n=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function Wi(e,t){if(e){let r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())}else throw Error("No buffer found on first parameter")}var Gi=$i([["from",En],["to",En],["nonce",Vi],["check",ji],["encrypted",Li]]),Sn={Memo:Gi};var Cn=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),Rn(),e=Fn(e),t=zi(t);let o=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:u}=An(e,t,i,n),p=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);ue.Memo(p,{check:u,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+Jr.encode(l)},Tn=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),Rn(),e=Fn(e);let r=Sn.Memo(Jr.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new G(n.key).toString()?new G(o.key):new G(n.key);r=On(e,p,i,a,s);let l=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},_t,Rn=()=>{if(_t===void 0){let e;_t=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=Cn(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=Tn(t,n);}finally{_t=e==="#memo\u7231";}}if(_t===false)throw new Error("This environment does not support encryption.")},Fn=e=>typeof e=="string"?H.fromString(e):e,zi=e=>typeof e=="string"?G.fromString(e):e,qn={decode:Tn,encode:Cn};var te={};ut(te,{buildWitnessSetProperties:()=>ts,makeBitMaskFilter:()=>Zi,operations:()=>Xi,validateUsername:()=>Yi});var Yi=e=>{let t="Account name should ";if(!e)return t+"not be empty.";let r=e.length;if(r<3)return t+"be longer.";if(r>16)return t+"be shorter.";/\./.test(e)&&(t="Each account segment should ");let n=e.split("."),o=n.length;for(let i=0;i<o;i++){let s=n[i];if(!/^[a-z]/.test(s))return t+"start with a lowercase letter.";if(!/^[a-z0-9-]*$/.test(s))return t+"have only lowercase letters, digits, or dashes.";if(!/[a-z0-9]$/.test(s))return t+"end with a lowercase letter or digit.";if(s.length<3)return t+"be longer."}return null},Xi={vote:0,comment:1,transfer:2,transfer_to_vesting:3,withdraw_vesting:4,limit_order_create:5,limit_order_cancel:6,feed_publish:7,convert:8,account_create:9,account_update:10,witness_update:11,account_witness_vote:12,account_witness_proxy:13,pow:14,custom:15,report_over_production:16,delete_comment:17,custom_json:18,comment_options:19,set_withdraw_vesting_route:20,limit_order_create2:21,claim_account:22,create_claimed_account:23,request_account_recovery:24,recover_account:25,change_recovery_account:26,escrow_transfer:27,escrow_dispute:28,escrow_release:29,pow2:30,escrow_approve:31,transfer_to_savings:32,transfer_from_savings:33,cancel_transfer_from_savings:34,custom_binary:35,decline_voting_rights:36,reset_account:37,set_reset_account:38,claim_reward_balance:39,delegate_vesting_shares:40,account_create_with_delegation:41,witness_set_properties:42,account_update2:43,create_proposal:44,update_proposal_votes:45,remove_proposal:46,update_proposal:47,collateralized_convert:48,recurrent_transfer:49,fill_convert_request:50,author_reward:51,curation_reward:52,comment_reward:53,liquidity_reward:54,interest:55,fill_vesting_withdraw:56,fill_order:57,shutdown_witness:58,fill_transfer_from_savings:59,hardfork:60,comment_payout_update:61,return_vesting_delegation:62,comment_benefactor_reward:63,producer_reward:64,clear_null_account_balance:65,proposal_pay:66,sps_fund:67,hardfork_hive:68,hardfork_hive_restore:69,delayed_voting:70,consolidate_treasury_balance:71,effective_comment_vote:72,ineffective_delete_comment:73,sps_convert:74,expired_account_notification:75,changed_recovery_account:76,transfer_to_vesting_completed:77,pow_reward:78,vesting_shares_split:79,account_created:80,fill_collateralized_convert_request:81,system_warning:82,fill_recurrent_transfer:83,failed_recurrent_transfer:84,limit_order_cancelled:85,producer_missed:86,proposal_fee:87,collateralized_convert_immediate_conversion:88,escrow_approved:89,escrow_rejected:90,proxy_cleared:91,declined_voting_rights:92},Zi=e=>e.reduce(es,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),es=([e,t],r)=>r<64?[e|BigInt(1)<<BigInt(r),t]:[e,t|BigInt(1)<<BigInt(r-64)],ts=(e,t)=>{let r={extensions:[],owner:e,props:[]};for(let n of Object.keys(t)){if(t[n]===void 0)continue;let o;switch(n){case "key":case "new_signing_key":o=ue.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=ue.UInt32;break;case "hbd_interest_rate":o=ue.UInt16;break;case "url":o=ue.String;break;case "hbd_exchange_rate":o=ue.Price;break;case "account_creation_fee":o=ue.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,rs(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},rs=(e,t)=>{let r=new q(q.DEFAULT_CAPACITY,q.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function Af(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o<128)r.push(o);else if(o<2048)r.push(192|o>>6,128|o&63);else if(o>=55296&&o<=56319&&n+1<e.length){let i=e.charCodeAt(++n);o=65536+((o&1023)<<10)+(i&1023),r.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function Kn(e){try{return H.fromString(e),!0}catch{return false}}async function Y(e,t){let r=new Ee;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Be("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function Dn(e,t){let r=new Ee;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var os=432e3;function In(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/os,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function is(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function rr(e){let t=is(e)*1e6;return In(t,e.voting_manabar)}function bt(e){return In(Number(e.max_rc),e.rc_manabar)}var Bn=(u=>(u.COMMON="common",u.INFO="info",u.INSUFFICIENT_RESOURCE_CREDITS="insufficient_resource_credits",u.MISSING_AUTHORITY="missing_authority",u.TOKEN_EXPIRED="token_expired",u.NETWORK="network",u.TIMEOUT="timeout",u.VALIDATION="validation",u))(Bn||{});function Me(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/you may only post once every/i))return {message:"Please wait before posting again (minimum 3 second interval between comments).",type:"common",originalError:e};if(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/votes evaluating for comment that is paid out is forbidden/i))return {message:"Cannot vote on posts that have already been paid out.",type:"common",originalError:e};if(i(/no (active|owner|posting|memo) key available/i))return {message:"Key not available. Please provide your key to sign this operation.",type:"missing_authority",originalError:e};if(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/missing (required )?posting authority/i))return {message:"Missing posting authority. Please check your login method.",type:"missing_authority",originalError:e};if(n==="invalid_grant"||n==="unauthorized_access"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\bnetwork[-\s]?(request|error|timeout|unreachable|down|failed)\b/i))return {message:"Network error. Please check your connection and try again.",type:"network",originalError:e};if(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).substring(0,150)||"Validation error occurred",type:"validation",originalError:e};if(e?.error_description&&typeof e.error_description=="string")return {message:e.error_description.substring(0,150),type:"common",originalError:e};if(e?.message&&typeof e.message=="string")return {message:e.message.substring(0,150),type:"common",originalError:e};let s;return typeof e=="object"&&e!==null?e.error_description?s=String(e.error_description):e.code?s=`Error code: ${e.code}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function ss(e){let t=Me(e);return [t.message,t.type]}function ge(e){let{type:t}=Me(e);return t==="missing_authority"||t==="token_expired"}function as(e){let{type:t}=Me(e);return t==="insufficient_resource_credits"}function cs(e){let{type:t}=Me(e);return t==="info"}function us(e){let{type:t}=Me(e);return t==="network"||t==="timeout"}async function ye(e,t,r,n,o="posting",i,s,a="async"){let u=n?.adapter;switch(e){case "key":{if(!u)throw new Error("No adapter provided for key-based auth");let p=i;if(p===void 0)switch(o){case "owner":if(u.getOwnerKey)p=await u.getOwnerKey(t);else throw new Error("Owner key not supported by adapter. Owner operations (like account recovery) require master password login or manual key entry.");break;case "active":u.getActiveKey&&(p=await u.getActiveKey(t));break;case "memo":if(u.getMemoKey)p=await u.getMemoKey(t);else throw new Error("Memo key not supported by adapter. Use memo encryption methods instead.");break;default:p=await u.getPostingKey(t);break}if(!p)throw new Error(`No ${o} key available for ${t}`);let l=H.fromString(p);return a==="async"?await Dn(r,l):await Y(r,l)}case "hiveauth":{if(!u?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await u.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!u)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await u.getAccessToken(t);if(p)try{return (await new Mn.Client({accessToken:p}).broadcast(r)).result}catch(l){if(u.broadcastWithHiveSigner&&ge(l))return await u.broadcastWithHiveSigner(t,r,o);throw l}if(u.broadcastWithHiveSigner)return await u.broadcastWithHiveSigner(t,r,o);throw new Error(`No access token available for ${t}`)}case "keychain":{if(!u?.broadcastWithKeychain)throw new Error("Keychain not supported by adapter");return await u.broadcastWithKeychain(t,r,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function ls(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let f=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!ge(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!ge(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&f&&l==="hiveauth")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!ge(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await ye(l,e,t,r,n,void 0,void 0,o)}catch(m){if(ge(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let y=t.length>0?t[0][0]:"unknown",A=await i.showAuthUpgradeUI(n,y);if(!A)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ye(A,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await ye("hivesigner",e,t,r,n,void 0,void 0,o)}catch(f){if(ge(f)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",y=await i.showAuthUpgradeUI(n,m);if(!y)throw new Error(`No login type available for ${e}. Please log in again.`);return await ye(y,e,t,r,n,void 0,void 0,o)}throw f}else if(n==="active"&&i.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ye(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",y,A;switch(l){case "key":if(!i)f=!0,m="No adapter provided";else {let O;switch(n){case "owner":i.getOwnerKey&&(O=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(O=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(O=await i.getMemoKey(e));break;default:O=await i.getPostingKey(e);break}O?y=O:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)f=!0,m="No adapter provided";else {let O=await i.getAccessToken(e);O&&(A=O);}break;case "keychain":i?.broadcastWithKeychain||(f=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(f=!0,m="No custom broadcast function provided");break}if(f){a.set(l,new Error(`Skipped: ${m}`));continue}return await ye(l,e,t,r,n,y,A,o)}catch(f){if(a.set(l,f),!ge(f))throw f}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([f,m])=>`${f}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,f])=>`${l}: ${f.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function b(e=[],t,r,n=()=>{},o,i="posting",s){let a=s?.broadcastMode??"async";return useMutation({onSuccess:n,onMutate:s?.onMutate,onError:s?.onError,onSettled:s?.onSettled,mutationKey:[...e,t],mutationFn:async u=>{if(!t)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let p=r(u);try{if(o?.enableFallback!==!1&&o?.adapter)return await ls(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=H.fromString(l);return await Y(p,m)}let f=o?.accessToken;if(f)return (await new Mn.Client({accessToken:f}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof J?new Error(l.message):l}}})}async function Nn(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let a=H.fromString(i);return Y([["custom_json",o]],a)}let s=n?.accessToken;if(s)return (await new Mn.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}var Nf=4e3;function E(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function he(e,t){let r=AbortSignal.timeout(e);if(!t)return r;if(typeof AbortSignal.any=="function")return AbortSignal.any([t,r]);let n=new AbortController,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Se=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),ms=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},we=1e4,d={privateApiHost:"https://ecency.com",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return x.nodes},heliusApiKey:ms(),queryClient:new QueryClient,pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},N;(O=>{function e(v){d.queryClient=v;}O.setQueryClient=e;function t(v){d.privateApiHost=v;}O.setPrivateApiHost=t;function r(v){d.clientId=v;}O.setClientId=r;function n(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}O.getValidatedBaseUrl=n;function o(v){d.pollsApiHost=v;}O.setPollsApiHost=o;function i(v){d.imageHost=v;}O.setImageHost=i;function s(v){Ht(v);}O.setHiveNodes=s;function a(v){Ut(v);}O.setRestNodes=a;function u(v){Vt(v);}O.setRestNodesByApi=u;function p(v){jt(v);}O.setUserAgent=p;function l(v){Lt(v);}O.setResilience=l;function f(v){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(v))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(v))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(v))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(v)||/\.\+\.\+/.test(v))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let P=/\.?\{(\d+),(\d+)\}/g,I;for(;(I=P.exec(v))!==null;){let[,B,j]=I;if(parseInt(j,10)-parseInt(B,10)>1e3)return {safe:false,reason:`excessive range: {${B},${j}}`}}return {safe:true}}function m(v){let P=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],I=5;for(let B of P){let j=Date.now();try{v.test(B);let Q=Date.now()-j;if(Q>I)return {safe:!1,reason:`runtime test exceeded ${I}ms (took ${Q}ms on input length ${B.length})`}}catch(Q){return {safe:false,reason:`runtime test threw error: ${Q}`}}}return {safe:true}}function y(v,P=200){try{if(!v)return Se&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(v.length>P)return Se&&console.warn(`[SDK] DMCA pattern rejected: length ${v.length} exceeds max ${P} - pattern: ${v.substring(0,50)}...`),null;let I=f(v);if(!I.safe)return Se&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${I.reason}) - pattern: ${v.substring(0,50)}...`),null;let B;try{B=new RegExp(v);}catch(Q){return Se&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${v.substring(0,50)}...`,Q),null}let j=m(B);return j.safe?B:(Se&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${j.reason}) - pattern: ${v.substring(0,50)}...`),null)}catch(I){return Se&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${v.substring(0,50)}...`,I),null}}function A(v={}){let P=Q=>Array.isArray(Q)?Q.filter(ee=>typeof ee=="string"):[],I=v||{},B={accounts:P(I.accounts),tags:P(I.tags),patterns:P(I.posts)};d.dmcaAccounts=B.accounts,d.dmcaTags=B.tags,d.dmcaPatterns=B.patterns,d.dmcaTagRegexes=B.tags.map(Q=>y(Q)).filter(Q=>Q!==null),d.dmcaPatternRegexes=[];let j=B.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Se&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${B.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${B.tags.length} compiled (${j} rejected)`),console.log(` - Post patterns: ${B.patterns.length} (using exact string matching)`),j>0&&console.warn(`[SDK] ${j} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}O.setDmcaLists=A;})(N||={});function Yf(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var _=()=>d.queryClient,ws;(s=>{function e(a){return _().getQueryData(a)}s.getQueryData=e;function t(a){return _().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await _().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await _().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>_().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>_().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(ws||={});function Zf(e){return btoa(JSON.stringify(e))}function em(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var Qn=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(Qn||{}),vt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(vt||{});function k(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:Qn[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:vt[e.nai]}}var nr;function h(){if(!nr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");nr=globalThis.fetch.bind(globalThis);}return nr}function Hn(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function _s(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function oe(e,t){return _s(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Ne(e,t){return e/1e6*t}function Un(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var Vn=60*1e3;function _e(){return queryOptions({queryKey:c.core.dynamicProps(),refetchInterval:Vn,staleTime:Vn,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([g("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),g("condenser_api.get_feed_history",[],void 0,void 0,e),g("condenser_api.get_chain_properties",[],void 0,void 0,e),g("condenser_api.get_reward_fund",["post"],void 0,void 0,e),g("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=k(t.total_vesting_shares).amount,a=k(t.total_vesting_fund_hive).amount,u=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(u=a/s*1e6);let p=k(r.current_median_history.base).amount,l=k(r.current_median_history.quote).amount,f=parseFloat(o.recent_claims),m=k(o.reward_balance).amount,y=Number(t.vote_power_reserve_rate??0),A=o.author_reward_curve??"linear",O=Number(o.content_constant??0),v=String(i.current_hardfork_version??"0.0.0"),P=Number(i.last_hardfork??0),I=t.hbd_print_rate,B=t.hbd_interest_rate,j=t.head_block_number,Q=a,ee=s,Ie=k(t.virtual_supply).amount,Le=t.vesting_reward_percent||0,$e=n.account_creation_fee;return {hivePerMVests:u,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:y,authorRewardCurve:A,contentConstant:O,currentHardforkVersion:v,lastHardfork:P,hbdPrintRate:I,hbdInterestRate:B,headBlock:j,totalVestingFund:Q,totalVestingShares:ee,virtualSupply:Ie,vestingRewardPercent:Le,accountCreationFee:$e,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function ym(e="post"){return queryOptions({queryKey:c.core.rewardFund(e),queryFn:()=>g("condenser_api.get_reward_fund",[e])})}function ke(...e){let t=e.length;for(;t>0&&e[t-1]===void 0;)t--;return e.slice(0,t)}var c={posts:{entry:e=>["posts","entry",e],postHeader:(e,t)=>["posts","post-header",e,t],content:(e,t)=>["posts","content",e,t],contentReplies:(e,t)=>["posts","content-replies",e,t],accountPosts:(e,t,r,n)=>["posts","account-posts",e,t,r,n],accountPostsPage:(e,t,r,n,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],userPostVote:(e,t,r)=>["posts","user-vote",e,t,r],reblogs:(e,t)=>["posts","reblogs",e,t],entryActiveVotes:(e,t)=>["posts","entry-active-votes",e,t],rebloggedBy:(e,t)=>["posts","reblogged-by",e,t],tips:(e,t)=>["posts","tips",e,t],normalize:(e,t)=>["posts","normalize",e,t],drafts:e=>["posts","drafts",e],draftsInfinite:(e,t)=>ke("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>ke("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>ke("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>ke("posts","images","infinite",e,t),promoted:e=>["posts","promoted",e],_promotedPrefix:["posts","promoted"],accountPostsBlogPrefix:e=>["posts","account-posts",e,"blog"],postsRanked:(e,t,r,n)=>["posts","posts-ranked",e,t,r,n],postsRankedPage:(e,t,r,n,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],discussions:(e,t,r,n)=>["posts","discussions",e,t,r,n],discussion:(e,t,r)=>["posts","discussion",e,t,r],deletedEntry:e=>["posts","deleted-entry",e],commentHistory:(e,t,r)=>["posts","comment-history",e,t,r],trendingTags:()=>["posts","trending-tags"],trendingTagsWithStats:e=>["posts","trending-tags","stats",e],wavesFeed:(e={})=>["posts","waves","feed",e.tag??"",e.following??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],shortsFeed:(e={})=>["posts","waves","shorts",e.tag??"",e.author??"",e.observer??"",e.limit??0,[...e.containers??[]].sort().join(",")],wavesByHost:e=>["posts","waves","by-host",e],wavesByTag:(e,t)=>["posts","waves","by-tag",e,t],wavesFollowing:(e,t)=>["posts","waves","following",e,t],wavesTrendingTags:(e,t)=>["posts","waves","trending-tags",e,t],wavesByAccount:(e,t)=>["posts","waves","by-account",e,t],wavesTrendingAuthors:e=>["posts","waves","trending-authors",e],_prefix:["posts"]},accounts:{full:e=>["get-account-full",e],list:(...e)=>["accounts","list",...e],friends:(e,t,r,n)=>["accounts","friends",e,t,r,n],searchFriends:(e,t,r)=>["accounts","friends","search",e,t,r],subscriptions:e=>["accounts","subscriptions",e],followCount:e=>["accounts","follow-count",e],recoveries:e=>["accounts","recoveries",e],pendingRecovery:e=>["accounts","recoveries",e,"pending-request"],checkWalletPending:(e,t)=>["accounts","check-wallet-pending",e,t],mutedUsers:e=>["accounts","muted-users",e],following:(e,t,r,n)=>["accounts","following",e,t,r,n],followers:(e,t,r,n)=>["accounts","followers",e,t,r,n],search:(e,t)=>["accounts","search",e,t],profiles:(e,t)=>["accounts","profiles",e,t],lookup:(e,t)=>["accounts","lookup",e,t],transactions:(e,t,r)=>["accounts","transactions",e,t,r],favorites:e=>["accounts","favorites",e],favoritesInfinite:(e,t)=>ke("accounts","favorites","infinite",e,t),checkFavorite:(e,t)=>["accounts","favorites","check",e,t],relations:(e,t)=>["accounts","relations",e,t],bots:()=>["accounts","bots"],voteHistory:(e,t)=>["accounts","vote-history",e,t],reputations:(e,t)=>["accounts","reputations",e,t],bookmarks:e=>["accounts","bookmarks",e],bookmarksInfinite:(e,t)=>ke("accounts","bookmarks","infinite",e,t),referrals:e=>["accounts","referrals",e],referralsStats:e=>["accounts","referrals-stats",e],proMembers:()=>["accounts","pro-members"],_prefix:["accounts"]},notifications:{announcements:()=>["notifications","announcements"],spotlights:()=>["notifications","spotlights"],list:(e,t)=>["notifications",e,t],unreadCount:e=>["notifications","unread",e],settings:e=>["notifications","settings",e],_prefix:["notifications"]},core:{rewardFund:e=>["core","reward-fund",e],dynamicProps:()=>["core","dynamic-props"],chainProperties:()=>["core","chain-properties"],_prefix:["core"]},communities:{single:(e,t)=>["community","single",e,t],singlePrefix:e=>["community","single",e],context:(e,t)=>["community","context",e,t],rewarded:()=>["communities","rewarded"],list:(e,t,r)=>["communities","list",e,t,r],subscribers:e=>["communities","subscribers",e],accountNotifications:(e,t)=>["communities","account-notifications",e,t]},proposals:{list:()=>["proposals","list"],proposal:e=>["proposals","proposal",e],votes:(e,t,r)=>["proposals","votes",e,t,r],votesPrefix:e=>["proposals","votes",e],votesByUser:e=>["proposals","votes","by-user",e]},search:{topics:(e,t)=>["search","topics",e,t],path:e=>["search","path",e],account:(e,t)=>["search","account",e,t],results:(e,t,r,n,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],controversialRising:(e,t)=>["search","controversial-rising",e,t],similarEntries:(e,t,r)=>r?["search","similar-entries",e,t,r]:["search","similar-entries",e,t],api:(e,t,r,n,o,i)=>ke("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],voterCount:e=>["witnesses","voter-count",e]},wallet:{outgoingRcDelegations:(e,t)=>["wallet","outgoing-rc-delegations",e,t],vestingDelegations:(e,t)=>["wallet","vesting-delegations",e,t],withdrawRoutes:e=>["wallet","withdraw-routes",e],incomingRc:e=>["wallet","incoming-rc",e],conversionRequests:e=>["wallet","conversion-requests",e],receivedVestingShares:e=>["wallet","received-vesting-shares",e],savingsWithdraw:e=>["wallet","savings-withdraw",e],openOrders:e=>["wallet","open-orders",e],collateralizedConversionRequests:e=>["wallet","collateralized-conversion-requests",e],recurrentTransfers:e=>["wallet","recurrent-transfers",e],balanceHistory:(e,t,r)=>["wallet","balance-history",e,t,r],aggregatedHistory:(e,t,r)=>r===void 0?["wallet","aggregated-history",e,t]:["wallet","aggregated-history",e,t,r],portfolio:(e,t,r)=>["wallet","portfolio","v2",e,t,r]},assets:{hiveGeneralInfo:e=>["assets","hive","general-info",e],hiveTransactions:(e,t,r)=>["assets","hive","transactions",e,t,r],hiveWithdrawalRoutes:e=>["assets","hive","withdrawal-routes",e],hiveMetrics:e=>["assets","hive","metrics",e],hbdGeneralInfo:e=>["assets","hbd","general-info",e],hbdTransactions:(e,t,r)=>["assets","hbd","transactions",e,t,r],hivePowerGeneralInfo:e=>["assets","hive-power","general-info",e],hivePowerDelegates:e=>["assets","hive-power","delegates",e],hivePowerDelegatings:e=>["assets","hive-power","delegatings",e],hivePowerTransactions:(e,t,r)=>["assets","hive-power","transactions",e,t,r],pointsGeneralInfo:e=>["assets","points","general-info",e],pointsTransactions:(e,t)=>["assets","points","transactions",e,t],ecencyAssetInfo:(e,t,r)=>["ecency-wallets","asset-info",e,t,r]},market:{statistics:()=>["market","statistics"],orderBook:e=>["market","order-book",e],history:(e,t,r)=>["market","history",e,t,r],feedHistory:()=>["market","feed-history"],hiveHbdStats:()=>["market","hive-hbd-stats"],data:(e,t,r,n)=>["market","data",e,t,r,n],tradeHistory:(e,t,r)=>["market","trade-history",e,t,r],currentMedianHistoryPrice:()=>["market","current-median-history-price"]},analytics:{discoverCuration:e=>["analytics","discover-curation",e],pageStats:(e,t,r,n)=>["analytics","page-stats",e,t,r,n],discoverLeaderboard:e=>["analytics","discover-leaderboard",e]},promotions:{promotePrice:()=>["promotions","promote-price"],boostPlusPrices:()=>["promotions","boost-plus-prices"],boostPlusAccounts:e=>["promotions","boost-plus-accounts",e]},resourceCredits:{account:e=>["resource-credits","account",e],stats:()=>["resource-credits","stats"]},points:{points:(e,t)=>["points",e,t],_prefix:e=>["points",e]},polls:{details:(e,t)=>["polls","details",e,t],vote:(e,t)=>e&&t?["polls","vote",e,t]:["polls","vote"],_prefix:["polls"]},operations:{chainProperties:()=>["operations","chain-properties"]},games:{statusCheck:(e,t)=>["games","status-check",e,t]},quests:{status:e=>["quests","status",e]},support:{settings:e=>["support","settings",e],_prefix:["support"]},badActors:{list:()=>["bad-actors","list"],_prefix:["bad-actors"]},ai:{prices:()=>["ai","prices"],assistPrices:e=>["ai","assist-prices",e],_prefix:["ai"]}};function vm(e){return queryOptions({queryKey:c.ai.prices(),queryFn:async()=>{let r=await h()(d.privateApiHost+"/private-api/ai-generate-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch AI generation prices: ${r.status}`);return await r.json()},staleTime:3e5,enabled:!!e})}function xm(e,t){return queryOptions({queryKey:c.ai.assistPrices(e),queryFn:async()=>{let n=await h()(d.privateApiHost+"/private-api/ai-assist-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch AI assist prices: ${n.status}`);return await n.json()},staleTime:6e4,enabled:!!t})}function xs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Cm(e,t){return useMutation({mutationKey:["ai","generate-image"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][GenerateImage] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][GenerateImage] \u2013 access token wasn't found");let o=await h()(d.privateApiHost+"/private-api/ai-generate-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,us:e,prompt:r.prompt,aspect_ratio:r.aspect_ratio??"1:1",power:r.power??1,idempotency_key:r.idempotency_key??xs()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let u=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw u.status=o.status,u.data=a,u}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&_().invalidateQueries({queryKey:c.points._prefix(e)});}})}function Ss(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function qm(e,t){return useMutation({mutationKey:["ai","assist"],mutationFn:async r=>{if(!e)throw new Error("[SDK][AI][Assist] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][AI][Assist] \u2013 access token wasn't found");let o=await h()(d.privateApiHost+"/private-api/ai-assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r.code??t,us:e,action:r.action,text:r.text,idempotency_key:Ss()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&_().invalidateQueries({queryKey:c.points._prefix(e)}),_().invalidateQueries({queryKey:c.ai.assistPrices(e)}));}})}function or(e){return !e.posting_json_metadata&&!e.json_metadata}function Cs(e){return e?Object.values(e).some(t=>typeof t=="string"?t.length>0:t!=null):false}function M(e){return queryOptions({queryKey:c.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([g("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),g("bridge.get_profile",{account:e},void 0,void 0,t).catch(p=>{if(t?.aborted)throw p;return null})]);if(!r?.[0])return null;let o=r[0];if(or(o)&&Cs(n?.metadata?.profile)){let p=await g("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!or(l[0])));if(p[0]&&!or(p[0]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=Ce(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,u=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:u,profile:i}},enabled:!!e,staleTime:6e4})}var Ts=new Set(["__proto__","constructor","prototype"]);function Pt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function jn(e,t){let r={...e};for(let n of Object.keys(t)){if(Ts.has(n))continue;let o=t[n],i=r[n];Pt(o)&&Pt(i)?r[n]=jn(i,o):r[n]=o;}return r}function Rs(e){if(!(!e||!Array.isArray(e)))return e.map(({meta:t,...r})=>{if(!t||typeof t!="object")return {...r,meta:t};let{privateKey:n,username:o,...i}=t;return {...r,meta:i}})}function Ce(e){if(!e)return {};try{let t=JSON.parse(e);if(t&&typeof t=="object"&&t.profile&&typeof t.profile=="object")return t.profile}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata:",t,{length:e?.length??0});}return {}}function Ln(e){return Ce(e?.posting_json_metadata)}function $n(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Ce(e.posting_json_metadata)).length;return Object.keys(Ce(t.posting_json_metadata)).length>r?t:e}function Fs(e){if(!e)return {};try{let t=JSON.parse(e);if(Pt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function Wn({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=Fs(e),o=Pt(n.profile)?n.profile:{},i=ir({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function ir({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=jn(e??{},i);return s.tokens&&!Array.isArray(s.tokens)&&(s.tokens=void 0),r!==void 0?s.tokens=r&&r.length>0?r:[]:n!==void 0&&(s.tokens=n),s.tokens=Rs(s.tokens),s.version=2,s}function At(e){return e.map(t=>{let r={name:t.name,owner:t.owner,active:t.active,posting:t.posting,memo_key:t.memo_key,post_count:t.post_count,created:t.created,reputation:t.reputation,posting_json_metadata:t.posting_json_metadata,last_vote_time:t.last_vote_time,last_post:t.last_post,json_metadata:t.json_metadata,reward_hive_balance:t.reward_hive_balance,reward_hbd_balance:t.reward_hbd_balance,reward_vesting_hive:t.reward_vesting_hive,reward_vesting_balance:t.reward_vesting_balance,balance:t.balance,hbd_balance:t.hbd_balance,savings_balance:t.savings_balance,savings_hbd_balance:t.savings_hbd_balance,savings_hbd_last_interest_payment:t.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:t.savings_hbd_seconds_last_update,savings_hbd_seconds:t.savings_hbd_seconds,next_vesting_withdrawal:t.next_vesting_withdrawal,pending_claimed_accounts:t.pending_claimed_accounts,vesting_shares:t.vesting_shares,delegated_vesting_shares:t.delegated_vesting_shares,received_vesting_shares:t.received_vesting_shares,vesting_withdraw_rate:t.vesting_withdraw_rate,to_withdraw:t.to_withdraw,withdrawn:t.withdrawn,witness_votes:t.witness_votes,proxy:t.proxy,recovery_account:t.recovery_account,proxied_vsf_votes:t.proxied_vsf_votes,voting_manabar:t.voting_manabar,voting_power:t.voting_power,downvote_manabar:t.downvote_manabar},n=Ce(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function Wm(e){return queryOptions({queryKey:c.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=await g("condenser_api.get_accounts",[e],void 0,void 0,void 0,r=>Array.isArray(r));return At(t??[])}})}function Xm(e){return queryOptions({queryKey:c.accounts.followCount(e),queryFn:()=>g("condenser_api.get_follow_count",[e])})}function ng(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.followers(e,t,r,n),queryFn:()=>g("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function cg(e,t,r="blog",n=100){return queryOptions({queryKey:c.accounts.following(e,t,r,n),queryFn:()=>g("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}function fg(e,t=100){return queryOptions({queryKey:c.accounts.mutedUsers(e),queryFn:async()=>(await g("condenser_api.get_following",[e,"","ignore",t])).map(n=>n.following),enabled:!!e})}function wg(e,t=50){return queryOptions({queryKey:c.accounts.lookup(e,t),queryFn:()=>g("condenser_api.lookup_accounts",[e,t]),enabled:!!e,staleTime:1/0})}function Ag(e,t=5,r=[]){return queryOptions({queryKey:c.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await g("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var Hs=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Sg(e,t){return queryOptions({queryKey:c.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await h()(d.privateApiHost+"/private-api/wallets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,code:t})});if(!n.ok)return {exist:false};let o=await n.json(),i=Array.isArray(o)?o.flatMap(s=>{if(!s||typeof s!="object")return [];let a=s,u=typeof a.token=="string"?a.token:void 0;if(!u)return [];let p=a.meta&&typeof a.meta=="object"?{...a.meta}:{},l={},f=typeof a.address=="string"&&a.address?a.address:void 0,y=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=y;let A={symbol:u,currency:u,address:f,show:y,type:"CHAIN",meta:l},O=[];for(let[v,P]of Object.entries(p))typeof v=="string"&&(Hs.has(v)||typeof P!="string"||!P||/^[A-Z0-9]{2,10}$/.test(v)&&O.push({symbol:v,currency:v,address:P,show:y,type:"CHAIN",meta:{address:P,show:y}}));return [A,...O]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function Gn(e,t){return queryOptions({queryKey:c.accounts.relations(e,t),enabled:!!e&&!!t,refetchOnMount:false,refetchInterval:36e5,queryFn:async()=>await g("bridge.get_relationship_between_accounts",[e,t])??{follows:false,ignores:false,blacklists:false,follows_muted:false,follows_blacklists:false}})}function Ig(e){return queryOptions({queryKey:c.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await g("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Qg(e,t){return queryOptions({queryKey:c.accounts.bookmarks(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Bookmarks] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Hg(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.bookmarksInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Lg(e,t){return queryOptions({queryKey:c.accounts.favorites(e),enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function $g(e,t,r=10){return infiniteQueryOptions({queryKey:c.accounts.favoritesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Jg(e,t,r){return queryOptions({queryKey:c.accounts.checkFavorite(e,r),enabled:!!e&&!!t&&!!r,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts][Favorites] \u2013 missing auth");if(!r)throw new Error("[SDK][Accounts][Favorites] \u2013 no target username");let o=await h()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function ey(e,t){return queryOptions({enabled:!!e&&!!t,queryKey:c.accounts.recoveries(e),queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Accounts] Missing username or access token");return (await h()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function iy(e){return queryOptions({enabled:!!e,queryKey:c.accounts.pendingRecovery(e),queryFn:()=>g("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function py(e,t=50){return queryOptions({queryKey:c.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>e?g("condenser_api.get_account_reputations",[e,t]):[]})}var K=te.operations,zn={transfers:[K.transfer,K.transfer_to_savings,K.transfer_from_savings,K.cancel_transfer_from_savings,K.recurrent_transfer,K.fill_recurrent_transfer,K.escrow_transfer,K.fill_recurrent_transfer],"market-orders":[K.fill_convert_request,K.fill_order,K.fill_collateralized_convert_request,K.limit_order_create2,K.limit_order_create,K.limit_order_cancel],interests:[K.interest],"stake-operations":[K.return_vesting_delegation,K.withdraw_vesting,K.transfer_to_vesting,K.set_withdraw_vesting_route,K.update_proposal_votes,K.fill_vesting_withdraw,K.account_witness_proxy,K.delegate_vesting_shares],rewards:[K.author_reward,K.curation_reward,K.producer_reward,K.claim_reward_balance,K.comment_benefactor_reward,K.liquidity_reward,K.proposal_pay]},Zs=[...Object.values(zn)].reduce((e,t)=>e.concat(t),[]);function ea(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function ta(e){return e.replace(/_operation$/,"")}function ra(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function na(e){if(!ra(e))return e;let t=k(e),r=vt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function oa(e){let t={};for(let[r,n]of Object.entries(e))t[r]=na(n);return t}function hy(e,t=20,r=""){let n=r?zn[r]:Zs;return infiniteQueryOptions({queryKey:c.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{if(!e)return {entries:[],currentPage:0};let s={"account-name":e,"operation-types":n.join(","),"page-size":t};o!==null&&(s.page=o);let a=await X("hafah","/accounts/{account-name}/operations",s,void 0,void 0,i);return {entries:a.operations_result.map(p=>{let l=ta(p.op.type);return {...oa(p.op.value),num:ea(p),type:l,timestamp:p.timestamp,trx_id:p.trx_id}}),currentPage:o??a.total_pages}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function vy(){return queryOptions({queryKey:c.accounts.bots(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/public/bots",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch bots: ${e.status}`);return e.json()},refetchOnMount:true,staleTime:1/0})}function xy(e){return infiniteQueryOptions({queryKey:c.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=N.getValidatedBaseUrl(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Cy(e){return queryOptions({queryKey:c.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/referrals/${e}/stats`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch referral stats: ${t.status}`);let r=await t.json();if(!r)throw new Error("No Referrals for this user!");return {total:r.total??0,rewarded:r.rewarded??0}}})}function Ky(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return infiniteQueryOptions({queryKey:c.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(y=>t==="following"?y.following:y.follower);return (await g("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(y=>({name:y.name,reputation:y.reputation,active:y.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var pa=30;function Ny(e,t,r){return queryOptions({queryKey:c.accounts.searchFriends(e,t,r),refetchOnMount:false,enabled:false,queryFn:async()=>{if(!r)return [];let n=r.slice(0,-1),s=(await g(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,n,"blog",1e3])).map(u=>t==="following"?u.following:u.follower).filter(u=>u.toLowerCase().includes(r.toLowerCase())).slice(0,pa);return (await g("bridge.get_profiles",{accounts:s,observer:void 0}))?.map(u=>({name:u.name,full_name:u.metadata.profile?.name||"",reputation:u.reputation,active:u.active}))??[]}})}function jy(e=20){return infiniteQueryOptions({queryKey:c.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!n.name.startsWith("hive-")).map(n=>n.name)),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length>0?{afterTag:t[t.length-1]}:void 0,staleTime:3600*1e3})}function Jy(e=250){return infiniteQueryOptions({queryKey:c.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>g("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Hn(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function Qe(e,t){return queryOptions({queryKey:c.posts.fragments(e),queryFn:async()=>t?(await h()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function eh(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.fragmentsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function oh(e="feed"){return queryOptions({queryKey:c.posts.promoted(e),queryFn:async()=>{let t=N.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await h()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function uh(e){return queryOptions({queryKey:c.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>g("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function mh(e,t,r){return queryOptions({queryKey:c.posts.userPostVote(e,t,r),queryFn:async()=>(await g("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function _h(e,t){return queryOptions({queryKey:c.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content",[e,t])})}function Oh(e,t){return queryOptions({queryKey:c.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>g("condenser_api.get_content_replies",{author:e,permlink:t})})}function Ch(e,t){return queryOptions({queryKey:c.posts.postHeader(e,t),queryFn:async()=>g("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function Z(e){return Array.isArray(e)?e.map(t=>Jn(t)):Jn(e)}function Jn(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return d.dmcaPatterns.includes(t)||d.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function Yn(e,t,r){try{let n=await wt("bridge.get_post",{author:e,permlink:t,observer:r},1);if(n&&typeof n=="object"&&n.author===e&&n.permlink===t)return n}catch{}return null}function Xn(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return queryOptions({queryKey:c.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await g("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let u=await Yn(e,o,r);if(!u)return null;let p=n!==void 0?{...u,num:n}:u;return Z(p)}let a=n!==void 0?{...s,num:n}:s;return Z(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ie(e,t,r){return g(`bridge.${e}`,t,void 0,void 0,r)}async function Zn(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await Pa(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function eo(e,t,r){let n=e.map(Ze),o=await Promise.all(n.map(i=>Zn(i,t,void 0,r)));return Z(o)}async function to(e,t="",r="",n=20,o="",i="",s){let a=await ie("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return a&&eo(a,i,s)}async function sr(e,t,r="",n="",o=20,i="",s){if(d.dmcaAccounts.includes(t))return [];let a=await ie("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:o,observer:i},s);return a&&eo(a,i,s)}function Ze(e){let t={...e,active_votes:Array.isArray(e.active_votes)?[...e.active_votes]:[],beneficiaries:Array.isArray(e.beneficiaries)?[...e.beneficiaries]:[],blacklists:Array.isArray(e.blacklists)?[...e.blacklists]:[],replies:Array.isArray(e.replies)?[...e.replies]:[],stats:e.stats?{...e.stats}:null},r=["author","title","body","created","category","permlink","url","updated"];for(let n of r)t[n]==null&&(t[n]="");return t.author_reputation==null&&(t.author_reputation=0),t.children==null&&(t.children=0),t.depth==null&&(t.depth=0),t.net_rshares==null&&(t.net_rshares=0),t.payout==null&&(t.payout=0),t.percent_hbd==null&&(t.percent_hbd=0),t.stats||(t.stats={flag_weight:0,gray:false,hide:false,total_votes:0}),t.author_payout_value==null&&(t.author_payout_value="0.000 HBD"),t.curator_payout_value==null&&(t.curator_payout_value="0.000 HBD"),t.max_accepted_payout==null&&(t.max_accepted_payout="1000000.000 HBD"),t.payout_at==null&&(t.payout_at=""),t.pending_payout_value==null&&(t.pending_payout_value="0.000 HBD"),t.promoted==null&&(t.promoted="0.000 HBD"),t.is_paidout==null&&(t.is_paidout=false),t}async function Pa(e="",t="",r="",n,o){let i=await ie("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=Ze(i),a=await Zn(s,r,n,o);return Z(a)}}async function jh(e="",t=""){let r=await ie("get_post_header",{author:e,permlink:t});return r&&Ze(r)}async function ro(e,t,r){let n=await ie("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=Ze(s);return o}return n}async function no(e,t=""){return ie("get_community",{name:e,observer:t})}async function Lh(e="",t=100,r,n="rank",o=""){return ie("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function oo(e){let t=await ie("normalize_post",{post:e});return t&&Ze(t)}async function $h(e){return ie("list_all_subscriptions",{account:e})}async function Wh(e){return ie("list_subscribers",{community:e})}async function Gh(e,t){return ie("get_relationship_between_accounts",[e,t])}async function Ot(e,t){return ie("get_profiles",{accounts:e,observer:t})}var so=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(so||{});function ar(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Aa(e,t,r){let n=l=>ar(l.pending_payout_value).amount+ar(l.author_payout_value).amount+ar(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(o(l))return 1;if(o(f))return -1;let m=n(l),y=n(f);return m!==y?y-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,y=f.author_reputation;return m>y?-1:m<y?1:0},votes:(l,f)=>{let m=l.children,y=f.children;return m>y?-1:m<y?1:0},created:(l,f)=>{if(o(l))return 1;if(o(f))return -1;let m=Date.parse(l.created),y=Date.parse(f.created);return m>y?-1:m<y?1:0}},a=t.sort(s[r]),u=a.findIndex(l=>i(l)),p=a[u];return u>=0&&(a.splice(u,1),a.unshift(p)),a}function ao(e,t="created",r=true,n){return queryOptions({queryKey:c.posts.discussions(e?.author,e?.permlink,t,n||e?.author),queryFn:async()=>{if(!e)return [];let o=await g("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:n||e.author}),i=o?Array.from(Object.values(o)):[];return Z(i)},enabled:r&&!!e,select:o=>Aa(e,o,t),structuralSharing:(o,i)=>{if(!o||!i)return i;let s=o.filter(p=>p.is_optimistic===true),a=new Set(i.map(p=>`${p.author}/${p.permlink}`)),u=s.filter(p=>!a.has(`${p.author}/${p.permlink}`));return u.length>0?[...i,...u]:i}})}function tw(e,t,r,n=true){return queryOptions({queryKey:c.posts.discussion(e,t,r||e),enabled:n&&!!e&&!!t,queryFn:async()=>ro(e,t,r)})}function aw(e,t="posts",r=20,n="",o=true){return infiniteQueryOptions({queryKey:c.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await sr(t,e,i.author??"",i.permlink??"",r,n,s);return Z(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function cw(e,t="posts",r="",n="",o=20,i="",s=true){return queryOptions({queryKey:c.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let u=await sr(t,e,r,n,o,i,a);return Z(u??[])}})}function gw(e,t,r=20,n="",o=true,i={}){return infiniteQueryOptions({queryKey:c.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{if(!s.hasNextPage)return [];let u=t;d.dmcaTagRegexes.some(O=>O.test(t))&&(u="");let p=await g("bridge.get_ranked_posts",{sort:e,start_author:s.author,start_permlink:s.permlink,limit:r,tag:u,observer:n},void 0,void 0,a);if(p==null)return [];if(!Array.isArray(p))throw new Error(`[SDK] get_ranked_posts returned ${typeof p} for sort=${e}`);let l=p,f=l.filter(O=>O.stats?.is_pinned),y=(e==="hot"?l:l.sort((O,v)=>new Date(v.created).getTime()-new Date(O.created).getTime())).filter(O=>!O.stats?.is_pinned),A=[...f,...y];return Z(A)},enabled:o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},getNextPageParam:s=>{let a=s?.[s.length-1];return {author:a?.author,permlink:a?.permlink,hasNextPage:(s?.length??0)>0}}})}function yw(e,t="",r="",n=20,o="",i="",s=true){return queryOptions({queryKey:c.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let u=o;d.dmcaTagRegexes.some(l=>l.test(o))&&(u="");let p=await to(e,t,r,n,u,i,a);return Z(p??[])}})}function vw(e,t,r=200){return queryOptions({queryKey:c.posts.reblogs(e??"",r),queryFn:async()=>(await g("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function Ew(e,t){return queryOptions({queryKey:c.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await g("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function Tw(e,t){return queryOptions({queryKey:c.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(d.privateApiHost+"/private-api/schedules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch schedules: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Rw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.schedulesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Dw(e,t){return queryOptions({queryKey:c.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(d.privateApiHost+"/private-api/drafts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!n.ok)throw new Error(`Failed to fetch drafts: ${n.status}`);return n.json()},enabled:!!e&&!!t})}function Iw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.draftsInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function uo(e){let r=await h()(d.privateApiHost+"/private-api/images",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok)throw new Error(`Failed to fetch images: ${r.status}`);return r.json()}function Qw(e,t){return queryOptions({queryKey:c.posts.images(e),queryFn:async()=>!e||!t?[]:uo(t),enabled:!!e&&!!t})}function Hw(e,t){return queryOptions({queryKey:c.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:uo(t),enabled:!!e&&!!t})}function Uw(e,t,r=10){return infiniteQueryOptions({queryKey:c.posts.imagesInfinite(e,r),queryFn:async({pageParam:n=0})=>{if(!e||!t)return {data:[],pagination:{total:0,limit:r,offset:0,has_next:false}};let i=await h()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return oe(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function $w(e,t,r=false){return queryOptions({queryKey:c.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t,onlyMeta:r?"1":""}),signal:n});if(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function Ba(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function Jw(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?Ba(n,r):"";return queryOptions({queryKey:c.posts.deletedEntry(i),queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/private-api/comment-history",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:r||""}),signal:s});if(!a.ok)throw new Error(`Failed to fetch comment history: ${a.status}`);return a.json()},select:s=>{if(!s?.list?.[0])return null;let{body:a,title:u,tags:p}=s.list[0];return {body:a,title:u,tags:p}},enabled:o})}function e_(e,t,r=true){return queryOptions({queryKey:c.posts.tips(e,t),queryFn:async()=>{let n=await fetch(d.privateApiHost+"/private-api/post-tips",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:e,permlink:t})});if(!n.ok)throw new Error(`Failed to fetch post tips: ${n.status}`);return n.json()},enabled:!!e&&!!t&&r})}function Na(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function Qa(e){return {...e,id:e.id??e.post_id}}function fe(e,t){if(!e)return null;let r=e.container??e,n=Na(r,t),o=e.parent?Qa(e.parent):void 0;return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,max_accepted_payout:e.max_accepted_payout||"1000000.000 HBD",pending_payout_value:e.pending_payout_value||"0.000 HBD",author_payout_value:e.author_payout_value||"0.000 HBD",curator_payout_value:e.curator_payout_value||"0.000 HBD",host:t,container:n,parent:o}}function Ha(e){return Array.isArray(e)?e:[]}async function po(e){let t=ao(e,"created",true),r=await d.queryClient.fetchQuery(t),n=Ha(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function lo(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var ja=20;function fo(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,following:e.following?.trim().toLowerCase()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??ja}}async function mo({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let u=N.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",u);p.searchParams.set("limit",String(i)),s&&p.searchParams.set("cursor",s),e.forEach(m=>p.searchParams.append("container",m)),t&&p.searchParams.set("tag",t),r&&p.searchParams.set("following",r),n&&p.searchParams.set("author",n),o&&p.searchParams.set("observer",o);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let f=await l.json();return !Array.isArray(f)||f.length===0?[]:f.map(m=>{let y=fe(m,m.host??"");return y?{...y,_cursor:m._cursor}:null}).filter(m=>!!m)}function c_(e={}){let t=fo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:c.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:u,signal:p})=>mo(t,u,p),getNextPageParam:u=>{if(!(u.length<a))return u[u.length-1]?._cursor}})}function u_(e={}){let t=fo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return queryOptions({queryKey:[...c.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),"latest"],staleTime:0,queryFn:({signal:u})=>mo(t,void 0,u)})}var $a=20;function Wa(e){return {containers:e.containers??[],tag:e.tag?.trim()||void 0,author:e.author?.trim().toLowerCase()||void 0,observer:e.observer?.trim().toLowerCase()||void 0,limit:e.limit??$a}}async function Ga({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=N.getValidatedBaseUrl(),u=new URL("/private-api/waves/shorts",a);u.searchParams.set("limit",String(o)),i&&u.searchParams.set("cursor",i),e.forEach(f=>u.searchParams.append("container",f)),t&&u.searchParams.set("tag",t),r&&u.searchParams.set("author",r),n&&u.searchParams.set("observer",n);let p=await fetch(u.toString(),{method:"GET",signal:s});if(!p.ok)throw new Error(`Failed to fetch shorts feed: ${p.status}`);let l=await p.json();return !Array.isArray(l)||l.length===0?[]:l.map(f=>{let m=fe(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function m_(e={}){let t=Wa(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return infiniteQueryOptions({queryKey:c.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:u})=>Ga(t,a,u),getNextPageParam:a=>{if(!(a.length<s))return a[a.length-1]?._cursor}})}var Ja=5,Ya=50;async function Xa(e,t){let r=t?.author,n=t?.permlink,o=0,i=t?.post_id;for(;o<Ya;){let s={sort:"posts",account:e,limit:Ja,...r?{start_author:r}:{},...n?{start_permlink:n}:{}},a;try{a=await g("bridge.get_account_posts",s);}catch(l){return console.error("[SDK] getThreads get_account_posts error:",l),null}if(!a||a.length===0)return null;let u=a.map(l=>(l.id=l.post_id,l.host=e,l));for(let l of u){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await po(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(f.length===0){r=l.author,n=l.permlink;continue}return {entries:lo(f,l,e)}}let p=u[u.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function b_(e){return infiniteQueryOptions({queryKey:c.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await Xa(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var ec=40;function x_(e,t,r=ec){return infiniteQueryOptions({queryKey:c.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves by tag: ${s.status}`);return (await s.json()).slice(0,r).map(p=>fe(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function T_(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesFollowing(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:n});if(!s.ok)throw new Error(`Failed to fetch waves following feed: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>fe(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function K_(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:c.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves trending tags: ${s.status}`);return (await s.json()).map(({tag:u,posts:p})=>({tag:u,posts:p}))}catch(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function N_(e,t){let r=t?.trim().toLowerCase();return infiniteQueryOptions({queryKey:c.posts.wavesByAccount(e,r??""),enabled:!!r,initialPageParam:void 0,queryFn:async({signal:n})=>{if(!r)return [];try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.toString(),{method:"GET",signal:n});if(!s.ok)throw new Error(`Failed to fetch waves for account: ${s.status}`);let a=await s.json();if(!Array.isArray(a)||a.length===0)return [];let u=a.map(p=>fe(p,e)).filter(p=>!!p);return u.length===0?[]:u.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function V_(e){return queryOptions({queryKey:c.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=N.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.json()).map(({author:s,posts:a})=>({author:s,posts:a}))}catch(r){throw console.error("[SDK] Failed to fetch waves trending authors",r),r}}})}function G_(e,t=true){return queryOptions({queryKey:c.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>oo(e)})}function ac(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function go(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function tb(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return infiniteQueryOptions({queryKey:c.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await g("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,y])=>({...y.op[1],num:m,timestamp:y.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&go(m.timestamp)<=o),l=[];for(let m of p){let y=await d.queryClient.fetchQuery(Xn(m.author,m.permlink));ac(y)&&l.push(y);}let[f]=a;return {lastDate:f?go(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function sb(e,t,r=true){return queryOptions({queryKey:c.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Ot(e,t)})}function lb(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:c.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await X("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function yb(e,t="HIVE",r="yearly"){return queryOptions({queryKey:c.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await X("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function bb(){return queryOptions({queryKey:c.accounts.proMembers(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/pro-members",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch pro members: ${e.status}`);return e.json()},staleTime:300*1e3})}function vb(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function Sb(e,t,r){let n=useQueryClient(),{data:o}=useQuery(M(e));return b(["accounts","update"],e,i=>{let s=$n(n.getQueryData(M(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:Wn({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(M(e).queryKey,a=>{if(!a)return a;let u=JSON.parse(JSON.stringify(a));return u.profile=ir({existingProfile:Ln(a),profile:s.profile,tokens:s.tokens}),u}),await E(t?.adapter,r,[c.accounts.full(e)]);},t,void 0,{broadcastMode:r,onMutate:async()=>{if(e)try{await n.fetchQuery({...M(e),staleTime:0});}catch{}}})}function Fb(e,t,r,n,o){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=Gn(e,t);await _().prefetchQuery(s);let a=_().getQueryData(s.queryKey);return await Nn(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),_().setQueryData(c.accounts.relations(e,t),i),t&&_().invalidateQueries(M(t));}})}function cr(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildVoteOp] Missing required parameters");if(n<-1e4||n>1e4)throw new Error("[SDK][buildVoteOp] Weight must be between -10000 and 10000");return ["vote",{voter:e,author:t,permlink:r,weight:n}]}function Te(e,t,r,n,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function Re(e,t,r,n,o,i,s){if(!e||!t)throw new Error("[SDK][buildCommentOptionsOp] Missing required parameters");return ["comment_options",{author:e,permlink:t,max_accepted_payout:r,percent_hbd:n,allow_votes:o,allow_curation_rewards:i,extensions:s}]}function ur(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function pr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function Fe(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferOp] Missing required parameters");return ["transfer",{from:e,to:t,amount:r,memo:n||""}]}function gc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>Fe(e,i.trim(),r,n))}function yc(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<24)throw new Error("[SDK][buildRecurrentTransferOp] Recurrence must be at least 24 hours");return ["recurrent_transfer",{from:e,to:t,amount:r,memo:n||"",recurrence:o,executions:i,extensions:[]}]}function He(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildTransferToSavingsOp] Missing required parameters");return ["transfer_to_savings",{from:e,to:t,amount:r,memo:n||""}]}function qe(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function yo(e,t){if(!e||t===void 0)throw new Error("[SDK][buildCancelTransferFromSavingsOp] Missing required parameters");return ["cancel_transfer_from_savings",{from:e,request_id:t}]}function et(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [qe(e,t,r,n,o),yo(e,o)]}function tt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildTransferToVestingOp] Missing required parameters");return ["transfer_to_vesting",{from:e,to:t,amount:r}]}function rt(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function nt(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildDelegateVestingSharesOp] Missing required parameters");return ["delegate_vesting_shares",{delegator:e,delegatee:t,vesting_shares:r}]}function ot(e,t,r,n){if(!e||!t||r===void 0)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Missing required parameters");if(r<0||r>1e4)throw new Error("[SDK][buildSetWithdrawVestingRouteOp] Percent must be between 0 and 10000");return ["set_withdraw_vesting_route",{from_account:e,to_account:t,percent:r,auto_vest:n}]}function it(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildConvertOp] Missing required parameters");return ["convert",{owner:e,amount:t,requestid:r}]}function lr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildCollateralizedConvertOp] Missing required parameters");return ["collateralized_convert",{owner:e,amount:t,requestid:r}]}function Ke(e,t,r,n="tokens"){return ["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:JSON.stringify({contractName:n,contractAction:t,contractPayload:r})}]}function dr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function fr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.trim()):[t];return ["custom_json",{id:"rc",json:JSON.stringify(["delegate_rc",{from:e,delegatees:n,max_rc:r}]),required_auths:[],required_posting_auths:[e]}]}function mr(e,t){if(!e||!t)throw new Error("[SDK][buildFollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["blog"]}]),required_auths:[],required_posting_auths:[e]}]}function xt(e,t){if(!e||!t)throw new Error("[SDK][buildUnfollowOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:[]}]),required_auths:[],required_posting_auths:[e]}]}function hc(e,t){if(!e||!t)throw new Error("[SDK][buildIgnoreOp] Missing required parameters");return ["custom_json",{id:"follow",json:JSON.stringify(["follow",{follower:e,following:t,what:["ignore"]}]),required_auths:[],required_posting_auths:[e]}]}function wc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return xt(e,t)}function gr(e,t){if(!e)throw new Error("[SDK][buildSetLastReadOps] Missing required parameters");let r=t||new Date().toISOString().split(".")[0],n=["custom_json",{id:"notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}function yr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildWitnessVoteOp] Missing required parameters");return ["account_witness_vote",{account:e,witness:t,approve:r}]}function hr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function wr(e,t){if(!e||!t.receiver||!t.subject||!t.permlink||!t.start||!t.end||!t.dailyPay)throw new Error("[SDK][buildProposalCreateOp] Missing required parameters");let r=new Date(t.start),n=new Date(t.end);if(r.toString()==="Invalid Date"||n.toString()==="Invalid Date")throw new Error("[SDK][buildProposalCreateOp] Invalid date format: start and end must be valid ISO date strings");return ["create_proposal",{creator:e,receiver:t.receiver,start_date:t.start,end_date:t.end,daily_pay:t.dailyPay,subject:t.subject,permlink:t.permlink,extensions:[]}]}function _r(e,t,r){if(!e||!t||t.length===0||r===void 0)throw new Error("[SDK][buildProposalVoteOp] Missing required parameters");return ["update_proposal_votes",{voter:e,proposal_ids:t,approve:r,extensions:[]}]}function _c(e,t){if(!e||!t||t.length===0)throw new Error("[SDK][buildRemoveProposalOp] Missing required parameters");return ["remove_proposal",{proposal_owner:e,proposal_ids:t,extensions:[]}]}function bc(e,t,r,n,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function br(e,t){if(!e||!t)throw new Error("[SDK][buildSubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["subscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function vr(e,t){if(!e||!t)throw new Error("[SDK][buildUnsubscribeOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["unsubscribe",{community:t}]),required_auths:[],required_posting_auths:[e]}]}function Pr(e,t,r,n){if(!e||!t||!r||!n)throw new Error(`[SDK][buildSetRoleOp] Missing required parameters: username=${e}, community=${t}, account=${r}, role=${n}`);return ["custom_json",{id:"community",json:JSON.stringify(["setRole",{community:t,account:r,role:n}]),required_auths:[],required_posting_auths:[e]}]}function Ar(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildUpdateCommunityOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["updateProps",{community:t,props:r}]),required_auths:[],required_posting_auths:[e]}]}function Or(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function xr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function vc(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function Pc(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildFlagPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify(["flagPost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}var ho=(r=>(r.Buy="buy",r.Sell="sell",r))(ho||{}),wo=(r=>(r.EMPTY="",r.SWAP="9",r))(wo||{});function St(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function Et(e,t=3){return e.toFixed(t)}function Ac(e,t,r,n,o=""){if(!e||n===void 0||!Number.isFinite(t)||t<=0||!Number.isFinite(r)||r<=0)throw new Error("[SDK][buildLimitOrderCreateOpWithType] Missing or invalid parameters");let i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,u=n==="buy"?`${Et(t,3)} HBD`:`${Et(t,3)} HIVE`,p=n==="buy"?`${Et(r,3)} HIVE`:`${Et(r,3)} HBD`;return St(e,u,p,false,s,a)}function Er(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Sr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildClaimRewardBalanceOp] Missing required parameters");return ["claim_reward_balance",{account:e,reward_hive:t,reward_hbd:r,reward_vests:n}]}function Oc(e,t,r,n,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}function xc(e,t,r,n){if(!e||r===void 0)throw new Error("[SDK][buildAccountUpdate2Op] Missing required parameters");return ["account_update2",{account:e,json_metadata:t||"",posting_json_metadata:r,extensions:n||[]}]}function kr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},s={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["account_create",{creator:e,new_account_name:t,owner:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Cr(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildCreateClaimedAccountOp] Missing required parameters");let n={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={weight_threshold:1,account_auths:[["ecency.app",1]],key_auths:[[r.postingPublicKey,1]]};return ["create_claimed_account",{creator:e,new_account_name:t,owner:n,active:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Tr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Rr(e,t,r,n,o,i){if(!e||!t||!r||!o)throw new Error("[SDK][buildGrantPostingPermissionOp] Missing required parameters");let s=t.account_auths.findIndex(([p])=>p===r),a=[...t.account_auths];s>=0?a[s]=[r,n]:a.push([r,n]);let u={...t,account_auths:a};return u.account_auths.sort((p,l)=>p[0]>l[0]?1:-1),["account_update",{account:e,posting:u,memo_key:o,json_metadata:i}]}function Ec(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}function Sc(e,t,r=[]){if(!e||!t)throw new Error("[SDK][buildChangeRecoveryAccountOp] Missing required parameters");return ["change_recovery_account",{account_to_recover:e,new_recovery_account:t,extensions:r}]}function kc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRequestAccountRecoveryOp] Missing required parameters");return ["request_account_recovery",{recovery_account:e,account_to_recover:t,new_owner_authority:r,extensions:n}]}function Cc(e,t,r,n=[]){if(!e||!t||!r)throw new Error("[SDK][buildRecoverAccountOp] Missing required parameters");return ["recover_account",{account_to_recover:e,new_owner_authority:t,recent_owner_authority:r,extensions:n}]}function Fr(e,t,r){if(!e||!t||!Number.isFinite(r))throw new Error("[SDK][buildBoostPlusOp] Missing required parameters");return ["custom_json",{id:"ecency_boost_plus",json:JSON.stringify({user:e,account:t,duration:r}),required_auths:[e],required_posting_auths:[]}]}function qr(e,t){if(!e||!Number.isInteger(t)||t<=0)throw new Error("[SDK][buildRcDelegationOp] Missing or invalid parameters");return ["custom_json",{id:"ecency_rc_delegation",json:JSON.stringify({user:e,duration:t}),required_auths:[e],required_posting_auths:[]}]}function Kr(e,t,r,n){if(!e||!t||!r||!Number.isFinite(n))throw new Error("[SDK][buildPromoteOp] Missing required parameters");return ["custom_json",{id:"ecency_promote",json:JSON.stringify({user:e,author:t,permlink:r,duration:n}),required_auths:[e],required_posting_auths:[]}]}function Ue(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Tc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>Ue(e,i.trim(),r,n))}function Dr(e){if(!e)throw new Error("[SDK][buildCommunityRegistrationOp] Missing required parameters");return ["custom_json",{id:"ecency_registration",json:JSON.stringify({name:e}),required_auths:[e],required_posting_auths:[]}]}function Rc(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildActiveCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[e],required_posting_auths:[]}]}function Fc(e,t,r){if(!e||!t||!r)throw new Error("[SDK][buildPostingCustomJsonOp] Missing required parameters");return ["custom_json",{id:t,json:JSON.stringify(r),required_auths:[],required_posting_auths:[e]}]}function Zb(e,t,r){return b(["accounts","follow"],e,({following:n})=>[mr(e,n)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.relations(e,o.following),c.accounts.full(o.following),c.accounts.followCount(o.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function nv(e,t,r){return b(["accounts","unfollow"],e,({following:n})=>[xt(e,n)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.relations(e,o.following),c.accounts.full(o.following),c.accounts.followCount(o.following),c.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function av(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,code:t})})).json()},onSuccess:()=>{r(),_().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function lv(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),_().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function gv(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{r();let s=_();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,i)});},onError:n})}function bv(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await h()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=_(),s=c.accounts.favorites(e),a=c.accounts.favoritesInfinite(e),u=c.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:u})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(y=>y.account!==o));let l=i.getQueryData(u);i.setQueryData(u,false);let f=i.getQueriesData({queryKey:a}),m=new Map(f);for(let[y,A]of f)A&&i.setQueryData(y,{...A,pages:A.pages.map(O=>({...O,data:O.data.filter(v=>v.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{r();let s=_();s.invalidateQueries({queryKey:c.accounts.favorites(e)}),s.invalidateQueries({queryKey:c.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:c.accounts.checkFavorite(e,i)});},onError:(o,i,s)=>{let a=_();if(s?.previousList&&a.setQueryData(c.accounts.favorites(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);s?.previousCheck!==void 0&&a.setQueryData(c.accounts.checkFavorite(e,i),s.previousCheck),n(o);}})}function Nc(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function _o(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,keysToRevoke:s=[],keysToRevokeByAuthority:a={}})=>{if(n.length===0)throw new Error("[SDK][Update password] \u2013 no new keys provided");if(!r)throw new Error("[SDK][Update password] \u2013 cannot update keys for anon user");let u=p=>{let l=JSON.parse(JSON.stringify(r[p])),m=[...a[p]||[],...a[p]===void 0?s:[]],y=o?l.key_auths.filter(([A])=>!m.includes(A.toString())):[];return l.key_auths=Nc(y,n.map((A,O)=>[A[p].createPublic().toString(),O+1])),l};return Y([["account_update",{account:e,json_metadata:r.json_metadata,owner:u("owner"),active:u("active"),posting:u("posting"),memo_key:n[0].memo_key.createPublic().toString()}]],i)},...t})}function Tv(e,t){let{data:r}=useQuery(M(e)),{mutateAsync:n}=_o(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=H.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:H.fromLogin(e,o,"owner"),active:H.fromLogin(e,o,"active"),posting:H.fromLogin(e,o,"posting"),memo_key:H.fromLogin(e,o,"memo")}]})},...t})}function Iv(e,t,r){let n=useQueryClient(),{data:o}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let u=JSON.parse(JSON.stringify(o.posting));u.account_auths=u.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:u,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return Y([["account_update",p]],a);if(s==="keychain"){if(!r?.broadcast)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.broadcast([["account_update",p]],"active")}else return !t.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner revoke-posting; user will not be redirected after signing."),Mn.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(M(e).queryKey,u=>({...u,posting:{...u?.posting,account_auths:u?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function Vv(e,t,r,n){let{data:o}=useQuery(M(e));return useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:u})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await h()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:u,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return Y([["change_recovery_account",p]],a);if(s==="keychain"){if(!n?.broadcast)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return n.broadcast([["change_recovery_account",p]],"owner")}else return !r.hsCallbackUrl&&process.env.NODE_ENV==="development"&&console.warn("[SDK][Accounts] hsCallbackUrl not provided for HiveSigner update-recovery; user will not be redirected after signing."),Mn.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function Lv(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function bo(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([u])=>!r.has(u.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function Yv(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=bo(r,i);return Y([["account_update",s]],n)},...t})}function tP(e,t,r){return b(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[Tr(n,o)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function iP(e,t,r){return b(["accounts","grant-posting-permission"],e,n=>[Rr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await E(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}function uP(e,t,r){return b(["accounts","create"],e,n=>[n.useClaimed?Cr(e,n.newAccountName,n.keys):kr(e,n.newAccountName,n.keys,n.fee)],async()=>{await E(t?.adapter,r,[c.accounts.full(e)]);},t,"active",{broadcastMode:r})}var Ir=300*60*24,Yc=1e4,Xc=5e7;function vo(e){let t=k(e.vesting_shares).amount,r=k(e.received_vesting_shares).amount,n=k(e.delegated_vesting_shares).amount,o=k(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function Zc(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function eu(e){if(Number.isFinite(e.lastHardfork))return e.lastHardfork>=28;let[t="0",r="0"]=(e.currentHardforkVersion??"0.0.0").split(".");return Number(t)>1||Number(t)===1&&Number(r)>=28}function tu(e,t,r){let n=t.votePowerReserveRate||Number(t.raw?.globalDynamic?.vote_power_reserve_rate??0);if(!Number.isFinite(n)||n<=0)return 0;let o=vo(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/Yc/(n*Ir)),a=rr(e),u=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(u)||s>u?0:Math.max(s-Xc,0)}function ru(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(eu(t))return tu(e,t,n);let o=0;try{if(o=vo(e),!Number.isFinite(o))return 0}catch{return 0}return Zc(o,r,n)}function fP(e){return rr(e).percentage/100}function mP(e){if(!Number.isFinite(e))throw new TypeError("Voting power must be a finite number");if(e<0||e>100)throw new RangeError("Voting power must be between 0 and 100");return (100-e)*100*Ir/1e4}function gP(e){let t=parseFloat(e.vesting_shares)+parseFloat(e.received_vesting_shares)-parseFloat(e.delegated_vesting_shares),r=Math.floor(Date.now()/1e3)-e.downvote_manabar.last_update_time,n=t*1e6/4;if(n<=0)return 0;let o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/Ir;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function yP(e){return bt(e).percentage/100}function hP(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let u=ru(e,t,r,n);return Number.isFinite(u)?u/o*i*(s/a):0}var nu={vote:"posting",comment:"posting",delete_comment:"posting",comment_options:"posting",claim_reward_balance:"posting",cancel_transfer_from_savings:"active",collateralized_convert:"active",convert:"active",delegate_vesting_shares:"active",recurrent_transfer:"active",set_withdraw_vesting_route:"active",transfer:"active",transfer_from_savings:"active",transfer_to_savings:"active",transfer_to_vesting:"active",withdraw_vesting:"active",limit_order_create:"active",limit_order_cancel:"active",account_update:"active",account_update2:"active",claim_account:"active",create_claimed_account:"active",account_witness_proxy:"active",account_witness_vote:"active",remove_proposal:"active",update_proposal_votes:"active",change_recovery_account:"owner",request_account_recovery:"owner",recover_account:"owner",reset_account:"owner",set_reset_account:"owner"};function ou(e){let t=e[0],r=e[1];if(t!=="custom_json")throw new Error("Operation is not a custom_json operation");let n=r;return n.required_auths&&n.required_auths.length>0?"active":(n.required_posting_auths&&n.required_posting_auths.length>0,"posting")}function iu(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function su(e){let t=e[0];return t==="custom_json"?ou(e):t==="create_proposal"||t==="update_proposal"?iu(e):nu[t]??"posting"}function _P(e){let t="posting";for(let r of e){let n=su(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function OP(e){return useMutation({mutationKey:["operations","sign",e],mutationFn:({operation:t,keyOrSeed:r})=>{if(!e)throw new Error("[Operations][Sign] \u2013 cannot sign op with anon user");let n;return r.split(" ").length===12?n=H.fromLogin(e,r,"active"):Kn(r)?n=H.fromString(r):n=H.from(r),Y([t],n)}})}function SP(e,t,r="active"){return useMutation({mutationKey:["operations","sign-keychain",e],mutationFn:({operation:n})=>{if(!e)throw new Error("[SDK][Keychain] \u2013\xA0cannot sign operation with anon user");if(!t?.broadcast)throw new Error("[SDK][Keychain] \u2013 missing keychain broadcaster");return t.broadcast([n],r)}})}function RP(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>Mn.sendOperation(t,{callback:e},()=>{})})}function DP(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await g("condenser_api.get_chain_properties",[])})}function Po(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Ao(e,t){return {...e??{},title:t.title,body:t.body}}function VP(e,t){return useMutation({mutationKey:["posts","add-fragment",e],mutationFn:async({title:r,body:n})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let i=await h()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=_(),i=Ao(r,n);o.setQueryData(Qe(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,u)=>u===0?{...a,data:[i,...a.data]}:a)});}})}function JP(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await h()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),headers:{"Content-Type":"application/json"}});if(!s.ok)throw new Error(`[SDK][Posts] Failed to update fragment: ${s.status}`);return s.json()},onSuccess(r,n){let o=_(),i=s=>Po(s,r,n);o.setQueryData(Qe(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(u=>u.id===n.fragmentId?i(u):u)}))});}})}function rA(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await h()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=_();o.setQueryData(Qe(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.pages.map(s=>({...s,data:s.data.filter(a=>a.id!==n.fragmentId)}))});}})}async function $(e){if(!e.ok){let r;try{r=await e.json();}catch{r=void 0;}let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}let t=await e.text();if(!t||t.trim()==="")return "";try{return JSON.parse(t)}catch(r){return console.warn("[SDK] Failed to parse JSON response:",r,"Response:",t),""}}async function iA(e,t,r,n){let i=await h()(d.privateApiHost+"/private-api/account-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,email:t,referral:r,captcha_token:n})}),s=await $(i);return {status:i.status,data:s}}async function sA(e){let r=await h()(d.privateApiHost+"/private-api/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})}),n=await $(r);return {status:r.status,data:n}}async function aA(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await h()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await $(s);}async function cA(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await h()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return $(s)}async function uA(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},u=await h()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return $(u)}async function pA(e,t,r){let n={code:e,username:t,token:r},i=await h()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return $(i)}async function Oo(e,t){let r={code:e};t&&(r.id=t);let o=await h()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function xo(e,t){let r={code:e,url:t},o=await h()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}var gu="https://i.ecency.com";async function Eo(e,t,r){let n=h(),o=new FormData;o.append("file",e);let i=await n(`${gu}/hs/${t}`,{method:"POST",body:o,signal:r});return $(i)}async function lA(e,t,r,n){let o=h(),i=new FormData;i.append("file",e);let s=await o(`${d.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return $(s)}async function So(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function ko(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await h()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return $(a)}async function Co(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},u=await h()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return $(u)}async function To(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function Ro(e,t,r,n,o,i,s,a){let u={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(u.options=i);let l=await h()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return $(l)}async function Fo(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function qo(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return $(o)}async function dA(e,t,r){let n={code:e,author:t,permlink:r},i=await h()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return $(i)}async function fA(e,t,r){let n={username:e,email:t,friend:r},i=await h()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return $(i)}function wA(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return ko(t,o,i,s,a)},onSuccess:o=>{r?.();let i=_();o?.drafts?i.setQueryData(c.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:c.posts.drafts(e)}),i.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function AA(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:u})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return Co(t,o,i,s,a,u)},onSuccess:()=>{r?.();let o=_();o.invalidateQueries({queryKey:c.posts.drafts(e)}),o.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:n})}function CA(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return To(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=_(),s=c.posts.drafts(e),a=c.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let u=i.getQueryData(s);u&&i.setQueryData(s,u.filter(f=>f._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&i.setQueryData(f,{...m,pages:m.pages.map(y=>({...y,data:y.data.filter(A=>A._id!==o)}))});return {previousList:u,previousInfinite:l}},onSuccess:()=>{r?.();let o=_();o.invalidateQueries({queryKey:c.posts.drafts(e)}),o.invalidateQueries({queryKey:c.posts.draftsInfinite(e)});},onError:(o,i,s)=>{let a=_();if(s?.previousList&&a.setQueryData(c.posts.drafts(e),s.previousList),s?.previousInfinite)for(let[u,p]of s.previousInfinite)a.setQueryData(u,p);n?.(o);}})}function KA(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:u,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return Ro(t,o,i,s,a,u,p,l)},onSuccess:()=>{r?.(),_().invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function NA(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return Fo(t,o)},onSuccess:o=>{r?.();let i=_();o?i.setQueryData(c.posts.schedules(e),o):i.invalidateQueries({queryKey:c.posts.schedules(e)});},onError:n})}function jA(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return qo(t,o)},onSuccess:o=>{r?.();let i=_();o?i.setQueryData(c.posts.schedules(e),o):i.invalidateQueries({queryKey:c.posts.schedules(e)}),i.invalidateQueries({queryKey:c.posts.drafts(e)});},onError:n})}function zA(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return xo(s,o)},onSuccess:()=>{r?.(),_().invalidateQueries({queryKey:c.posts.images(e)});},onError:n})}function e0(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return So(t,o)},onSuccess:(o,i)=>{r?.();let s=_(),{imageId:a}=i;s.setQueryData(["posts","images",e],u=>u?.filter(p=>p._id!==a)),s.setQueriesData({queryKey:["posts","images","infinite",e]},u=>u&&{...u,pages:u.pages.map(p=>({...p,data:p.data.filter(l=>l._id!==a)}))});},onError:n})}function o0(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>Eo(r,n,o),onSuccess:e,onError:t})}function Ct(e,t){return `/@${e}/${t}`}function xu(e,t,r){return (r??_()).getQueryData(c.posts.entry(Ct(e,t)))}function Eu(e,t){(t??_()).setQueryData(c.posts.entry(Ct(e.author,e.permlink)),e);}function kt(e,t,r,n){let o=n??_(),i=Ct(e,t),s=o.getQueryData(c.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(c.posts.entry(i),a),s}var De;(a=>{function e(u,p,l,f,m){kt(u,p,y=>({...y,active_votes:l,stats:{...y.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:y.stats?.flag_weight||0},total_votes:l.length,payout:f,pending_payout_value:String(f)}),m);}a.updateVotes=e;function t(u,p,l,f){kt(u,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(u,p,l,f){kt(u,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(u,p,l,f){kt(p,l,m=>({...m,children:m.children+1,replies:[u,...m.replies]}),f);}a.addReply=n;function o(u,p){u.forEach(l=>Eu(l,p));}a.updateEntries=o;function i(u,p,l){(l??_()).invalidateQueries({queryKey:c.posts.entry(Ct(u,p))});}a.invalidateEntry=i;function s(u,p,l){return xu(u,p,l)}a.getEntry=s;})(De||={});function Su(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function ku(e,t,r){let n=De.getEntry(t.author,t.permlink,r);if(!n?.active_votes||Su(n.active_votes,e,t.weight))return;let o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);De.updateVotes(t.author,t.permlink,o,i,r);}function l0(e,t,r){return b(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[cr(e,n,o,i)],async(n,o)=>{ku(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([c.posts.entry(`/@${o.author}/${o.permlink}`),c.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function y0(e,t,r){return b(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[pr(e,n,o,i??false)],async(n,o)=>{let i=De.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));De.updateReblogsCount(o.author,o.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{_().invalidateQueries({queryKey:c.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([c.posts.entry(`/@${o.author}/${o.permlink}`),c.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function b0(e,t,r){return b(["posts","comment"],e,n=>{let o=[];if(o.push(Te(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Re(n.author,n.permlink,i,s,a,u,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=i?100:110,a=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&a&&t.adapter.recordActivity(s,a,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let u=[c.accounts.full(e),c.resourceCredits.account(e)];if(!i){u.push(c.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.parentPermlink;u.push({predicate:f=>{let m=f.queryKey;return Array.isArray(m)&&m[0]==="posts"&&m[1]==="discussions"&&m[2]===p&&m[3]===l}});}await t.adapter.invalidateQueries(u);}},t,"posting",{broadcastMode:r})}function A0(e,t,r,n){let o=n??_(),i=o.getQueriesData({predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="discussions"&&a[2]===t&&a[3]===r}});for(let[s,a]of i)a&&o.setQueryData(s,[e,...a]);}function Ko(e,t,r,n,o){let i=o??_(),s=new Map,a=i.getQueriesData({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===r&&p[3]===n}});for(let[u,p]of a)p&&(s.set(u,p),i.setQueryData(u,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function Do(e,t){let r=t??_();for(let[n,o]of e)r.setQueryData(n,o);}function O0(e,t,r,n){let o=n??_(),i=`/@${e}/${t}`,s=o.getQueryData(c.posts.entry(i));return s&&o.setQueryData(c.posts.entry(i),{...s,...r}),s}function x0(e,t,r,n){let o=n??_(),i=`/@${e}/${t}`;o.setQueryData(c.posts.entry(i),r);}function T0(e,t,r){return b(["posts","deleteComment"],e,({author:n,permlink:o})=>[ur(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[c.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(c.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.push({predicate:u=>{let p=u.queryKey;return Array.isArray(p)&&p[0]==="posts"&&p[1]==="discussions"&&p[2]===s&&p[3]===a}});}await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:Ko(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&Do(s);}})}function K0(e,t,r){return b(["posts","cross-post"],e,n=>{let o=[];if(o.push(Te(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true}=n.options;o.push(Re(n.author,n.permlink,i,s,a,u,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[c.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function M0(e,t,r){return b(["posts","update-reply"],e,n=>{let o=[];if(o.push(Te(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:u=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let f=[...p].sort((m,y)=>m.account.localeCompare(y.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Re(n.author,n.permlink,i,s,a,u,l));}return o},async(n,o)=>{let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(110,i,n?.block_num).catch(s=>{console.debug("[SDK][Posts][useUpdateReply] recordActivity failed",{activityType:110,blockNum:n?.block_num,transactionId:i,error:s});}),t?.adapter?.invalidateQueries){let s=[c.resourceCredits.account(e)];s.push(c.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let a=o.rootAuthor||o.parentAuthor,u=o.rootPermlink||o.parentPermlink;s.push({predicate:p=>{let l=p.queryKey;return Array.isArray(l)&&l[0]==="posts"&&l[1]==="discussions"&&l[2]===a&&l[3]===u}}),await t.adapter.invalidateQueries(s);}},t,"posting",{broadcastMode:r})}function U0(e,t,r){return b(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[Kr(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.posts._promotedPrefix],[...c.points._prefix(e)],c.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Cu=[3e3,3e3,3e3],Tu=e=>new Promise(t=>setTimeout(t,e));async function Ru(e,t){return g("condenser_api.get_content",[e,t])}async function Fu(e,t,r=0,n){let o=n?.delays??Cu,i;try{i=await Ru(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await Tu(s),Fu(e,t,r+1,n)}var Ve={};ut(Ve,{useRecordActivity:()=>Br});function Ku(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function Br(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=h(),o=Ku(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function X0(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function nO(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(d.privateApiHost+`/private-api/curation/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch curation data: ${r.status}`);let n=await r.json(),o=n.map(s=>s.account),i=await g("condenser_api.get_accounts",[o]);for(let s=0;s<i.length;s++){let a=i[s],u=n[s],p=typeof a.vesting_shares=="string"?a.vesting_shares:a.vesting_shares.toString(),l=typeof a.received_vesting_shares=="string"?a.received_vesting_shares:a.received_vesting_shares.toString(),f=typeof a.delegated_vesting_shares=="string"?a.delegated_vesting_shares:a.delegated_vesting_shares.toString(),m=typeof a.vesting_withdraw_rate=="string"?a.vesting_withdraw_rate:a.vesting_withdraw_rate.toString(),y=parseFloat(p)+parseFloat(l)-parseFloat(f)-parseFloat(m);u.efficiency=u.vests/y;}return n.sort((s,a)=>a.efficiency-s.efficiency),n}})}function aO(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,o,i,n],queryFn:async({signal:s})=>{let a=await fetch(d.privateApiHost+"/api/stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,date_range:n}),signal:s});if(!a.ok)throw new Error(`Failed to fetch page stats: ${a.status}`);return a.json()},enabled:!!e,staleTime:0})}var Qr={};ut(Qr,{getAccountTokenQueryOptions:()=>Nr,getAccountVideosQueryOptions:()=>Vu});var Mr={};ut(Mr,{getDecodeMemoQueryOptions:()=>Qu});function Qu(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new Mn.Client({accessToken:r}).decode(t)}})}var Io={queries:Mr};function Nr(e,t){return queryOptions({queryKey:["integrations","3speak","authenticate",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let n=await h()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),o=Io.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await _().prefetchQuery(o);let{memoDecoded:i}=_().getQueryData(o.queryKey);return i.replace("#","")}})}function Vu(e,t){return queryOptions({queryKey:["integrations","3speak","videos",e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Integrations][3Speak] \u2013\xA0anon user");let r=Nr(e,t);await _().prefetchQuery(r);let n=_().getQueryData(r.queryKey);if(!n)throw new Error("[SDK][Integrations][3Speak] \u2013 missing account token");return await(await h()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var kO={queries:Qr};function qO(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await h()(`https://hiveposh.com/api/v0/linked-accounts/${e}`,{headers:{"Content-Type":"application/json"}});if(r.status===400&&(await r.json().catch(()=>({})))?.message==="User Not Connected"||!r.ok)return null;let n=await r.json();return {twitter:{username:n.twitter_username,profile:n.twitter_profile},reddit:{username:n.reddit_username,profile:n.reddit_profile}}}catch{return null}}})}function BO({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await h()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function HO(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await g("rc_api.get_rc_stats",{})).rc_stats})}function LO(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await g("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}var Bo={ready:false,currentMana:0,maxMana:0,avgCost:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function GO({rcAccount:e,rcStats:t,operation:r,buffer:n=1.2}){if(!e||!t?.ops)return Bo;let{current_mana:o,max_mana:i}=bt(e),s=Number(t.ops[r]?.avg_cost??0);if(!(s>0))return {...Bo,ready:true,currentMana:o,maxMana:i};let a=Number.isFinite(n)&&n>0?n:1.2,u=s*a,p=o<u;return {ready:true,currentMana:o,maxMana:i,avgCost:s,estimatedCost:u,willLikelyFail:p,deficit:p?Math.ceil(u-o):0,remaining:Math.floor(o/s)}}function XO(e,t,r){return queryOptions({queryKey:["games","status-check",r,e],enabled:!!e&&!!t,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}function nx(e,t,r,n){let{mutateAsync:o}=Br(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return await(await h()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:r,code:t,key:n}),headers:{"Content-Type":"application/json"}})).json()},onSuccess(){o();}})}function ax(e){let t=e?.replace("@","");return queryOptions({queryKey:c.quests.status(t),enabled:!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Quests] \u2013 username wasn't provided");let n=await h()(d.privateApiHost+"/private-api/quests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t})});if(!n.ok)throw new Error(`Failed to fetch quests: ${n.status}`);return await n.json()},staleTime:3e4,refetchOnMount:true})}var Yu=[{id:"checkin",tier:"daily",goal:1,i18nKey:"checkin",icon:"check-circle"},{id:"post",tier:"daily",goal:1,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"daily",goal:3,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"daily",goal:10,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"daily",goal:1,i18nKey:"reblog",icon:"repeat"},{id:"spin",tier:"daily",goal:1,i18nKey:"spin",icon:"gift"},{id:"post",tier:"weekly",goal:5,i18nKey:"post",icon:"pencil"},{id:"comment",tier:"weekly",goal:15,i18nKey:"comment",icon:"comment"},{id:"vote",tier:"weekly",goal:50,i18nKey:"vote",icon:"chevron-up-circle"},{id:"reblog",tier:"weekly",goal:5,i18nKey:"reblog",icon:"repeat"},{id:"post",tier:"monthly",goal:20,i18nKey:"post",icon:"pencil"}];function ux(e,t){return Yu.find(r=>r.tier===e&&r.id===t)}var px=300,lx=2;function ep(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function tp(e){let r=await h()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:ep()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function gx(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["streak-freeze","buy",n],mutationFn:async()=>{if(!n||!t)throw new Error("[SDK][StreakFreeze] \u2013 missing auth");return tp(t)},onSuccess(){n&&r.invalidateQueries({queryKey:c.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:c.quests.status(n)});}})}function _x(e,t,r){return b(["communities","subscribe"],e,({community:n})=>[br(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(o.community)],c.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function Ax(e,t,r){return b(["communities","unsubscribe"],e,({community:n})=>[vr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.subscriptions(e),[...c.communities.singlePrefix(o.community)],c.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function Sx(e,t,r){return b(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[xr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[c.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function Rx(e,t,r,n){return b(["communities","set-role",e],t,({account:o,role:i})=>[Pr(t,e,o,i)],async(o,i)=>{_().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>{if(!a)return a;let u=[...a.team??[]],p=u.findIndex(([l])=>l===i.account);return p>=0?u[p]=[u[p][0],i.role,u[p][2]??""]:u.push([i.account,i.role,""]),{...a,team:u}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)],c.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function Dx(e,t,r,n){return b(["communities","update",e],t,o=>[Ar(t,e,o)],async(o,i)=>{_().setQueriesData({queryKey:c.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...c.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function Nx(e,t,r){return b(["communities","registerRewards"],e,({name:n})=>[Dr(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...c.communities.singlePrefix(o.name)],[...c.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function Vx(e,t,r){return b(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[Or(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.posts.entry(`/@${o.account}/${o.permlink}`),[...c.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function Gx(e,t,r=100,n=void 0,o=true){return queryOptions({queryKey:c.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await g("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function Zx(e,t){return queryOptions({queryKey:c.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await g("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function oE(e,t="",r=true){return queryOptions({queryKey:c.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>no(e??"",t)})}function uE(e){return queryOptions({queryKey:c.communities.subscribers(e),queryFn:async()=>await g("bridge.list_subscribers",{community:e})??[],staleTime:6e4})}function mE(e,t){return infiniteQueryOptions({queryKey:c.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>{try{return await g("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[]}catch{return []}},getNextPageParam:r=>r?.length>0?r[r.length-1].id:null})}function wE(){return queryOptions({queryKey:c.communities.rewarded(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/rewarded-communities",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch rewarded communities: ${e.status}`);return e.json()}})}var cp=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(cp||{}),bE={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function PE(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function AE({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function SE(e,t){return queryOptions({queryKey:c.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${d.privateApiHost}/private-api/notifications/unread`,{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json()).count:0,enabled:!!e&&!!t,initialData:0,refetchInterval:6e4})}function RE(e,t,r=void 0){return infiniteQueryOptions({queryKey:c.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialData:{pages:[],pageParams:[]},initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var lp=(f=>(f.VOTES="rvotes",f.MENTIONS="mentions",f.FAVORITES="nfavorites",f.BOOKMARKS="nbookmarks",f.FOLLOWS="follows",f.REPLIES="replies",f.REBLOGS="reblogs",f.TRANSFERS="transfers",f.DELEGATIONS="delegations",f.PAYOUTS="payouts",f.SCHEDULED_PUBLISHED="scheduled_published",f))(lp||{});var dp=(l=>(l[l.VOTE=1]="VOTE",l[l.MENTION=2]="MENTION",l[l.FOLLOW=3]="FOLLOW",l[l.COMMENT=4]="COMMENT",l[l.RE_BLOG=5]="RE_BLOG",l[l.TRANSFERS=6]="TRANSFERS",l[l.FAVORITES=13]="FAVORITES",l[l.BOOKMARKS=15]="BOOKMARKS",l[l.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",l.ALLOW_NOTIFY="ALLOW_NOTIFY",l))(dp||{}),Mo=[1,2,3,4,5,6,13,15,22],fp=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(fp||{});function ME(e,t,r){return queryOptions({queryKey:c.notifications.settings(e),queryFn:async()=>{let n=e+"-web";if(!t)throw new Error("Missing access token");let o=await fetch(d.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Mo]})})}function UE(){return queryOptions({queryKey:c.notifications.announcements(),queryFn:async()=>{let e=await fetch(d.privateApiHost+"/private-api/announcements",{method:"GET",headers:{"Content-Type":"application/json"}});if(!e.ok)throw new Error(`Failed to fetch announcements: ${e.status}`);return await e.json()||[]},staleTime:36e5})}function $E(e){return queryOptions({queryKey:c.notifications.spotlights(),queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/spotlights",{method:"GET",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to fetch spotlights: ${t.status}`);return await t.json()||[]},staleTime:36e5})}function wp(e,t){return {...e,read:!t||t===e.id?1:e.read}}function No(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function ZE(e,t,r,n){let o=_();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Oo(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:c.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:c.notifications._prefix,predicate:l=>{let f=l.state.data;return No(f)}});a.forEach(([l,f])=>{if(f&&No(f)){s.push([l,f]);let m={...f,pages:f.pages.map(y=>y.map(A=>wp(A,i)))};o.setQueryData(l,m);}});let u=c.notifications.unreadCount(e),p=o.getQueryData(u);return typeof p=="number"&&p>0&&(s.push([u,p]),i?a.some(([,f])=>f?.pages.some(m=>m.some(y=>y.id===i&&y.read===0)))&&o.setQueryData(u,p-1):o.setQueryData(u,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(c.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([u,p])=>{o.setQueryData(u,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:c.notifications._prefix});}})}function nS(e,t,r){return b(["notifications","set-last-read"],e,({date:n})=>gr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function aS(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await g("condenser_api.find_proposals",[[e]]))[0];return new Date(r.start_date)<new Date&&new Date(r.end_date)>=new Date?r.status="active":new Date(r.end_date)<new Date?r.status="expired":r.status="inactive",r}})}function lS(){return queryOptions({queryKey:["proposals","list"],queryFn:async()=>{let t=(await g("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function yS(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await g("condenser_api.list_proposal_votes",[[e,n??t],r,"by_proposal_voter"])).filter(l=>l.proposal?.proposal_id===e).map(l=>({id:l.id,voter:l.voter})),a=await g("condenser_api.get_accounts",[s.map(l=>l.voter)]),u=At(a);return s.map(l=>({...l,voterAccount:u.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function bS(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await g("database_api.list_proposal_votes",{start:[e],limit:1e3,order:"by_voter_proposal",order_direction:"ascending",status:"votable"})).proposal_votes||[]).filter(n=>n.voter===e)})}function OS(e,t,r){return b(["proposals","vote"],e,({proposalIds:n,approve:o})=>[_r(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.proposals.list(),c.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function kS(e,t,r){return b(["proposals","create"],e,n=>[wr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.proposals.list()]);},t,"active",{broadcastMode:r})}function FS(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await g("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.length<t?void 0:r[r.length-1]?.delegatee,enabled:!!e})}function IS(e){return queryOptions({queryKey:["assets","account-delegations",e],enabled:!!e,queryFn:({signal:t})=>X("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function QS(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await g("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function jS(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>g("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function GS(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>g("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function XS(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>g("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function rk(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function sk(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>g("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function pk(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await g("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function mk(e){return queryOptions({queryKey:["wallet","incoming-rc",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] - Missing username for incoming RC");let r=await h()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function wk(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`);if(!t.ok)throw new Error(`Failed to fetch received vesting shares: ${t.status}`);return (await t.json()).list}})}function Pk(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>g("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function pe(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function se(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=e.trim();if(!t)return;let r=Number.parseFloat(t);if(Number.isFinite(r))return r;let o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function Ip(e){if(!e||typeof e!="object")return;let t=e;return {name:pe(t.name)??"",symbol:pe(t.symbol)??"",layer:pe(t.layer)??"hive",balance:se(t.balance)??0,fiatRate:se(t.fiatRate)??0,currency:pe(t.currency)??"usd",precision:se(t.precision)??3,address:pe(t.address),error:pe(t.error),pendingRewards:se(t.pendingRewards),pendingRewardsFiat:se(t.pendingRewardsFiat),liquid:se(t.liquid),liquidFiat:se(t.liquidFiat),savings:se(t.savings),savingsFiat:se(t.savingsFiat),staked:se(t.staked),stakedFiat:se(t.stakedFiat),iconUrl:pe(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:se(t.apr)}}function Bp(e){if(!e||typeof e!="object")return [];let t=[e],r=e;r.data&&typeof r.data=="object"&&t.push(r.data),r.result&&typeof r.result=="object"&&t.push(r.result),r.portfolio&&typeof r.portfolio=="object"&&t.push(r.portfolio);for(let n of t){if(Array.isArray(n))return n;if(n&&typeof n=="object")for(let o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function Mp(e){if(!e||typeof e!="object")return;let t=e;return pe(t.username)??pe(t.name)??pe(t.account)}function Qo(e,t="usd",r=true){return queryOptions({queryKey:["wallet","portfolio","v2",e,r?"only-enabled":"all",t],enabled:!!e,staleTime:6e4,refetchInterval:12e4,queryFn:async()=>{if(!e)throw new Error("[SDK][Wallet] \u2013 username is required");let n=`${N.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=Bp(i).map(a=>Ip(a)).filter(a=>!!a).filter(a=>a.layer!=="spk");if(!s.length)throw new Error("[SDK][Wallet] \u2013 Portfolio payload contained no tokens");return {username:Mp(i)??e,currency:pe(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Tt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await _().prefetchQuery(_e()),await _().prefetchQuery(M(e));let t=_().getQueryData(_e().queryKey),r=_().getQueryData(M(e).queryKey),n=await g("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=k(r.balance).amount,s=k(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function Ho(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await _().prefetchQuery(_e()),await _().prefetchQuery(M(e));let t=_().getQueryData(M(e).queryKey),r=_().getQueryData(_e().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:k(t.hbd_balance).amount+k(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:k(t.hbd_balance).amount},{name:"savings",balance:k(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function Up(e){let u=9.5-(e.headBlock-7e6)/25e4*.01;u<.95&&(u=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,f=e.totalVestingFund;return (l*u*p/f).toFixed(3)}function Uo(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await _().prefetchQuery(_e()),await _().prefetchQuery(M(e));let t=_().getQueryData(_e().queryKey),r=_().getQueryData(M(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await g("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o:t.base/t.quote,s=k(r.vesting_shares).amount,a=k(r.delegated_vesting_shares).amount,u=k(r.received_vesting_shares).amount,p=k(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=Un(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Ne(s,t.hivePerMVests).toFixed(3),y=+Ne(a,t.hivePerMVests).toFixed(3),A=+Ne(u,t.hivePerMVests).toFixed(3),O=+Ne(l,t.hivePerMVests).toFixed(3),v=+Ne(f,t.hivePerMVests).toFixed(3),P=Math.max(m-O,0),I=Math.max(m-y,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+P.toFixed(3),apr:Up(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+I.toFixed(3)},{name:"outgoing_delegations",balance:y},{name:"incoming_delegations",balance:A},...O>0?[{name:"pending_power_down",balance:+O.toFixed(3)}]:[],...v>0&&v!==O?[{name:"next_power_down",balance:+v.toFixed(3)}]:[]]}}})}var D=te.operations,Hr={transfers:[D.transfer,D.transfer_to_savings,D.transfer_from_savings,D.cancel_transfer_from_savings,D.recurrent_transfer,D.fill_recurrent_transfer,D.escrow_transfer,D.fill_recurrent_transfer],"market-orders":[D.fill_convert_request,D.fill_order,D.fill_collateralized_convert_request,D.limit_order_create2,D.limit_order_create,D.limit_order_cancel],interests:[D.interest],"stake-operations":[D.return_vesting_delegation,D.withdraw_vesting,D.transfer_to_vesting,D.set_withdraw_vesting_route,D.update_proposal_votes,D.fill_vesting_withdraw,D.account_witness_proxy,D.delegate_vesting_shares],rewards:[D.author_reward,D.curation_reward,D.producer_reward,D.claim_reward_balance,D.comment_benefactor_reward,D.liquidity_reward,D.proposal_pay],"":[]};var Wk=Object.keys(te.operations);var Vo=te.operations,Jk=Vo,Yk=Object.entries(Vo).reduce((e,[t,r])=>(e[r]=t,e),{});var jo=te.operations;function jp(e){return Object.prototype.hasOwnProperty.call(jo,e)}function st(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in Hr){Hr[a].forEach(u=>i.add(u));return}jp(a)&&i.add(jo[a]);});let s=Lp(Array.from(i));return {filterKey:o,filterArgs:s}}function Lp(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<<BigInt(n):r|=1n<<BigInt(n-64);}),[t!==0n?t.toString():null,r!==0n?r.toString():null]}function Rt(e,t=20,r=[]){let{filterArgs:n,filterKey:o}=st(r);return infiniteQueryOptions({queryKey:["assets","hive","transactions",e,t,o],initialData:{pages:[],pageParams:[]},initialPageParam:-1,getNextPageParam:(i,s)=>i?+(i[i.length-1]?.num??0)-1:-1,queryFn:async({pageParam:i})=>(await g("condenser_api.get_account_history",[e,i,t,...n])).map(a=>({num:a[0],type:a[1].op[0],timestamp:a[1].timestamp,trx_id:a[1].trx_id,...a[1].op[1]})),select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.map(a=>a.filter(u=>{switch(u.type){case "author_reward":case "comment_benefactor_reward":return k(u.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(u.amount).symbol==="HIVE";case "transfer_from_savings":return k(u.amount).symbol==="HIVE";case "fill_recurrent_transfer":let l=k(u.amount);return ["HIVE"].includes(l.symbol);case "claim_reward_balance":return k(u.reward_hive).amount>0;case "curation_reward":case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":return true;case "limit_order_create2":return true;default:return false}}))})})}function cC(e,t=20,r=[]){let{filterKey:n}=st(r);return infiniteQueryOptions({...Rt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:o,pageParams:i})=>({pageParams:i,pages:o.map(s=>s.filter(a=>{switch(a.type){case "author_reward":case "comment_benefactor_reward":return k(a.hbd_payout).amount>0;case "claim_reward_balance":return k(a.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(a.amount).symbol==="HBD";case "transfer_from_savings":return k(a.amount).symbol==="HBD";case "fill_recurrent_transfer":let l=k(a.amount);return ["HBD"].includes(l.symbol);case "cancel_transfer_from_savings":case "fill_order":case "limit_order_create":case "limit_order_cancel":case "fill_convert_request":case "fill_collateralized_convert_request":case "proposal_pay":case "interest":return true;case "limit_order_create2":return true;default:return false}}))})})}function fC(e,t=20,r=[]){let{filterKey:n}=st(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return infiniteQueryOptions({...Rt(e,t,r),queryKey:["assets","hive-power","transactions",e,t,n],select:({pages:s,pageParams:a})=>({pageParams:a,pages:s.map(u=>u.filter(p=>{switch(p.type){case "author_reward":case "comment_benefactor_reward":return k(p.vesting_payout).amount>0;case "claim_reward_balance":return k(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(k(p.amount).symbol);case "fill_recurrent_transfer":let m=k(p.amount);return ["VESTS","HP"].includes(m.symbol);case "curation_reward":case "withdraw_vesting":case "delegate_vesting_shares":case "fill_vesting_withdraw":case "return_vesting_delegation":case "producer_reward":case "set_withdraw_vesting_route":return true;default:return i||o.has(p.type)}}))})})}function Lo(e){let t=r=>r.toString().padStart(2,"0");return `${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function Ur(e,t){return new Date(e.getTime()-t*1e3)}function hC(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await g("condenser_api.get_market_history",[e,Lo(t),Lo(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[Ur(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[Ur(n,Math.max(100*e,28800)),Ur(n,e)]})}function vC(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>g("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function xC(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>g("condenser_api.get_vesting_delegations",[e,"",t])})}function TC(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(d.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>k(n.vesting_shares).amount-k(r.vesting_shares).amount)})}function KC(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>g("condenser_api.get_order_book",[e])})}function MC(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>g("condenser_api.get_ticker",[])})}function UC(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>g("condenser_api.get_market_history",[e,n(t),n(r)])})}function $C(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await g("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await g("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function JC(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=h(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function $o(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function eT(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>g("condenser_api.get_trade_history",[$o(o),$o(n),e])})}function oT(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await g("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function cT(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await g("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function dT(e,t,r){return b(["market","limit-order-create"],e,n=>[St(e,n.amountToSell,n.minToReceive,n.fillOrKill,n.expiration,n.orderId)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function yT(e,t,r){return b(["market","limit-order-cancel"],e,({orderId:n})=>[Er(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.wallet.openOrders(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}async function at(e){let t=await e.json();if(!e.ok){let r=new Error(`Request failed with status ${e.status}`);throw r.status=e.status,r.data=t,r}return t}async function _T(e,t,r,n){let o=h(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return at(s)}async function Wo(e){if(e==="hbd")return 1;let t=h(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await at(n)).hive_dollar[e]}async function bT(e,t){let n=await h()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return at(n)}async function vT(){let t=await h()(d.privateApiHost+"/private-api/market-data/latest");return at(t)}async function PT(){let t=await h()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return at(t)}var sl={"Content-type":"application/json"};async function al(e){let t=h(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:sl});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Ae(e,t){try{return await al(e)}catch{return t}}async function xT(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([Ae({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Ae({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=a=>a.sort((u,p)=>{let l=Number(u.price??0);return Number(p.price??0)-l}),s=a=>a.sort((u,p)=>{let l=Number(u.price??0),f=Number(p.price??0);return l-f});return {buy:i(n),sell:s(o)}}async function ET(e,t=50){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"tradesHistory",query:{symbol:e},limit:t,offset:0,indexes:[{index:"timestamp",descending:true}]},id:1},[])}async function ST(e,t,r=100){let n={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:t,account:e},limit:r,offset:0},id:1},[o,i]=await Promise.all([Ae({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Ae({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.map(p=>({id:p.txId,type:"buy",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:p.tokensLocked??s(p.quantity,p.price),timestamp:Number(p.timestamp??0)})),u=i.map(p=>({id:p.txId,type:"sell",account:p.account,symbol:p.symbol,quantity:p.quantity,price:p.price,total:s(p.quantity,p.price),timestamp:Number(p.timestamp??0)}));return [...a,...u].sort((p,l)=>l.timestamp-p.timestamp)}async function cl(e,t){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...e?{symbol:e}:{},...t?{account:t}:{}}},id:1},[])}async function Ft(e,t){return cl(t,e)}async function qt(e){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Kt(e){return Ae({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Go(e,t,r,n){let o=h(),i=N.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);s.searchParams.set("account",e),s.searchParams.set("symbol",t),s.searchParams.set("limit",r.toString()),s.searchParams.set("offset",n.toString());let a=await o(s.toString(),{method:"GET",headers:{"Content-type":"application/json"}});if(!a.ok)throw new Error(`[SDK][HiveEngine] \u2013 account history failed with ${a.status}`);return await a.json()}async function zo(e,t="daily"){let r=h(),n=N.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function Jo(e){let t=h(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-reward-api/${e}?hive=1`);if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 rewards failed with ${n.status}`);return await n.json()}function Dt(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>qt(e)})}function Yo(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ft()})}function Xo(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Kt(e)})}function QT(e,t,r=20){return infiniteQueryOptions({queryKey:["assets","hive-engine",t,"transactions",e],enabled:!!t&&!!e,initialPageParam:0,queryFn:async({pageParam:n})=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");return Go(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function jT(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>zo(e,t)})}function GT(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await Jo(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function XT(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>Ft(e,t)})}function je(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");let a=Math.abs(parseFloat(e.toString()))<1e-4?0:e,u=typeof a=="string"?parseFloat(a):a;return s+=u.toLocaleString("en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:true}),i&&(s+=" "+i),s}var It=class{symbol;name;icon;precision;stakingEnabled;delegationEnabled;balance;stake;stakedBalance;delegationsIn;delegationsOut;usdValue;constructor(t){this.symbol=t.symbol,this.name=t.name||"",this.icon=t.icon||"",this.precision=t.precision||0,this.stakingEnabled=t.stakingEnabled||false,this.delegationEnabled=t.delegationEnabled||false,this.balance=parseFloat(t.balance)||0,this.stake=parseFloat(t.stake)||0,this.delegationsIn=parseFloat(t.delegationsIn)||0,this.delegationsOut=parseFloat(t.delegationsOut)||0,this.stakedBalance=this.stake+this.delegationsIn-this.delegationsOut,this.usdValue=t.usdValue;}hasDelegations=()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false;delegations=()=>this.hasDelegations()?`(${je(this.stake,{fractionDigits:this.precision})} + ${je(this.delegationsIn,{fractionDigits:this.precision})} - ${je(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():je(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():je(this.balance,{fractionDigits:this.precision})};function sR(e,t,r){return queryOptions({queryKey:["assets","hive-engine","balances-with-usd",e,t,r],queryFn:async()=>{if(!e)throw new Error("[HiveEngine] No account in a balances query");let n=await qt(e),o=await Kt(n.map(a=>a.symbol)),i=t?t.base/t.quote:0,s=Array.isArray(r)?r:[];return n.map(a=>{let u=o.find(A=>A.symbol===a.symbol),p;if(u?.metadata)try{p=JSON.parse(u.metadata);}catch{p=void 0;}let l=s.find(A=>A.symbol===a.symbol),f=Number(l?.lastPrice??"0"),m=Number(a.balance),y=a.symbol==="SWAP.HIVE"?i*m:f===0?0:Number((f*i*m).toFixed(10));return new It({symbol:a.symbol,name:u?.name??a.symbol,icon:p?.icon??"",precision:u?.precision??0,stakingEnabled:u?.stakingEnabled??false,delegationEnabled:u?.delegationEnabled??false,balance:a.balance,stake:a.stake,delegationsIn:a.delegationsIn,delegationsOut:a.delegationsOut,usdValue:y})})},enabled:!!e})}function Zo(e,t){return queryOptions({queryKey:["assets","hive-engine",t,"general-info",e],enabled:!!t&&!!e,staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{if(!t||!e)throw new Error("[SDK][HiveEngine] \u2013 token or username missed");let r=_(),n=Tt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Xo([t])),s=await r.ensureQueryData(Dt(e)),a=await r.ensureQueryData(Yo()),u=i?.find(v=>v.symbol===t),p=s?.find(v=>v.symbol===t),f=+(a?.find(v=>v.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),y=parseFloat(p?.stake??"0"),A=parseFloat(p?.pendingUnstake??"0"),O=[{name:"liquid",balance:m},{name:"staked",balance:y}];return A>0&&O.push({name:"unstaking",balance:A}),{name:t,title:u?.name??"",price:f===0?0:Number(f*(o?.price??0)),accountBalance:m+y,layer:"ENGINE",parts:O}}})}function ct(e,t=0){return queryOptions({queryKey:["points",e,t],queryFn:async()=>{if(!e)throw new Error("Get points query \u2013 username wasn't provided");let r=e.replace("@",""),n=await fetch(d.privateApiHost+"/private-api/points",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r})});if(!n.ok)throw new Error(`Failed to fetch points: ${n.status}`);let o=await n.json(),i=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function ei(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await _().prefetchQuery(ct(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(_().getQueryData(ct(e).queryKey)?.points??0)})})}function OR(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${d.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:o,type:i,amount:s,id:a,sender:u,receiver:p,memo:l})=>({created:new Date(o),type:i,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:u??void 0,to:p??void 0,memo:l??void 0}))})}function IR(e,t,r={refetch:false}){let n=_(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await Wo(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=Qo(e,o,true),u=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let f=[];if(l.liquid!==void 0&&l.liquid!==null&&f.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&f.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&f.push({name:"savings",balance:l.savings}),l.extraData&&Array.isArray(l.extraData))for(let m of l.extraData){if(!m||typeof m!="object")continue;let y=m.dataKey,A=m.value;if(typeof A=="string"){let v=A.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(v){let P=Math.abs(Number.parseFloat(v[1]));y==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:P}):y==="received_hive_power"?f.push({name:"incoming_delegations",balance:P}):y==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:P});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:f}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,o],queryFn:async()=>{let p=await u();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Tt(e));else if(t==="HP")l=await i(Uo(e));else if(t==="HBD")l=await i(Ho(e));else if(t==="POINTS")l=await i(ei(e));else if((await n.ensureQueryData(Dt(e))).some(m=>m.symbol===t))l=await i(Zo(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let f=await s(l);return {...p,price:f.price}}return await s(l)}})}var Pl=(P=>(P.Transfer="transfer",P.TransferToSavings="transfer-saving",P.WithdrawFromSavings="withdraw-saving",P.Delegate="delegate",P.PowerUp="power-up",P.PowerDown="power-down",P.WithdrawRoutes="withdraw-routes",P.ClaimInterest="claim-interest",P.Swap="swap",P.Convert="convert",P.Gift="gift",P.Promote="promote",P.Claim="claim",P.Buy="buy",P.Stake="stake",P.Unstake="unstake",P.Undelegate="undelegate",P))(Pl||{});function UR(e,t,r){return b(["wallet","transfer"],e,n=>[Fe(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function WR(e,t,r){return b(["wallet","transfer-point"],e,n=>[Ue(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function XR(e,t,r){return b(["wallet","delegate-vesting-shares"],e,n=>[nt(e,n.delegatee,n.vestingShares)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nF(e,t,r){return b(["wallet","set-withdraw-vesting-route"],e,n=>[ot(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await E(t?.adapter,r,[c.wallet.withdrawRoutes(e),c.accounts.full(e),c.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function aF(e,t,r){return b(["wallet","transfer-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"transfer",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity,memo:n.memo}});return [["custom_json",{required_auths:[e],required_posting_auths:[],id:"ssc-mainnet-hive",json:o}]]},async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function dF(e,t,r){return b(["wallet","transfer-to-savings"],e,n=>[He(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function hF(e,t,r){return b(["wallet","transfer-from-savings"],e,n=>[qe(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function PF(e,t,r){return b(["wallet","transfer-to-vesting"],e,n=>[tt(e,n.to,n.amount)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function SF(e,t,r){return b(["wallet","withdraw-vesting"],e,n=>[rt(e,n.vestingShares)],async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function FF(e,t,r){return b(["wallet","convert"],e,n=>[n.collateralized?lr(e,n.amount,n.requestId):it(e,n.amount,n.requestId)],async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function BF(e,t,r){return b(["wallet","claim-interest"],e,n=>et(e,n.to,n.amount,n.memo,n.requestId),async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var Al=5e3,Bt=new Map;function UF(e,t,r){return b(["wallet","claim-rewards"],e,n=>[Sr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e],c.assets.hiveGeneralInfo(e),c.assets.hbdGeneralInfo(e),c.assets.hivePowerGeneralInfo(e)],i=Bt.get(n);i&&(clearTimeout(i),Bt.delete(n));let s=setTimeout(async()=>{try{let a=_(),p=(await Promise.allSettled(o.map(l=>a.invalidateQueries({queryKey:l})))).filter(l=>l.status==="rejected");p.length>0&&console.error("[SDK][Wallet][useClaimRewards] delayed invalidation rejected",{username:e,rejectedCount:p.length,rejected:p});}catch(a){console.error("[SDK][Wallet][useClaimRewards] delayed invalidation failed",{username:e,error:a});}finally{Bt.delete(n);}},Al);Bt.set(n,s);},t,"posting",{broadcastMode:r})}function $F(e,t,r){return b(["wallet","delegate-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"delegate",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function JF(e,t,r){return b(["wallet","undelegate-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"undelegate",contractPayload:{symbol:n.symbol,from:n.from,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function eq(e,t,r){return b(["wallet","stake-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"stake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function oq(e,t,r){return b(["wallet","unstake-engine-token"],e,n=>{let o=JSON.stringify({contractName:"tokens",contractAction:"unstake",contractPayload:{symbol:n.symbol,to:n.to,quantity:n.quantity}});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:o}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function cq(e,t,r){return b(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function dq(e,t,r){return b(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await E(t?.adapter,r,[c.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Ol(e,t,r){let{from:n,to:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Fe(n,o,i,s)];case "transfer-saving":return [He(n,o,i,s)];case "withdraw-saving":return [qe(n,o,i,s,a)];case "power-up":return [tt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [Fe(n,o,i,s)];case "transfer-saving":return [He(n,o,i,s)];case "withdraw-saving":return [qe(n,o,i,s,a)];case "claim-interest":return et(n,o,i,s,a);case "convert":return [it(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [rt(n,i)];case "delegate":return [nt(n,o,i)];case "withdraw-routes":return [ot(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ue(n,o,i,s)];break}return null}function xl(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [Ke(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [Ke(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [Ke(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [Ke(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [Ke(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [dr(n,[e])]}return null}function El(e){return e==="claim"?"posting":"active"}function wq(e,t,r,n,o){let{mutateAsync:i}=Ve.useRecordActivity(e,r);return b(["ecency-wallets",t,r],e,s=>{let a=Ol(t,r,s);if(a)return a;let u=xl(t,r,s);if(u)return u;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();let s=[];s.push(["ecency-wallets","asset-info",e,t]),t==="HIVE"&&s.push(["ecency-wallets","asset-info",e,"HP"]),s.push(["wallet","portfolio","v2",e]),setTimeout(()=>{s.forEach(a=>{_().invalidateQueries({queryKey:a});});},5e3);},n,El(r),{broadcastMode:o})}function Pq(e,t,r){return b(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[fr(e,n,o)],async(n,o)=>{await E(t?.adapter,r,[c.accounts.full(e),c.accounts.full(o.to),c.resourceCredits.account(e),c.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function Eq(e,t,r){return b(["witnesses","vote"],e,({witness:n,approve:o})=>[yr(e,n,o)],async()=>{try{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.votes(e)]);}catch(n){console.warn("[useWitnessVote] Post-broadcast side-effect failed:",n);}},t,"active",{broadcastMode:r})}function Tq(e,t,r){return b(["witnesses","proxy"],e,({proxy:n})=>[hr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function kl(e){return {owner:e.witness_name,total_missed:e.missed_blocks,url:e.url,props:{account_creation_fee:`${(e.account_creation_fee/1e3).toFixed(3)} HIVE`,account_subsidy_budget:0,maximum_block_size:e.block_size},hbd_exchange_rate:{base:`${e.price_feed.toFixed(3)} HBD`},available_witness_account_subsidies:0,running_version:e.version,signing_key:e.signing_key,last_hbd_exchange_update:e.feed_updated_at,rank:e.rank,vests:e.vests,voters_num:e.voters_num,voters_num_daily_change:e.voters_num_daily_change,price_feed:e.price_feed,hbd_interest_rate:e.hbd_interest_rate,last_confirmed_block_num:e.last_confirmed_block_num}}function Dq(e){return infiniteQueryOptions({queryKey:c.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await X("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(kl),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function Iq(e,t,r,n="vests",o="desc"){return queryOptions({queryKey:c.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await X("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function Bq(e){return queryOptions({queryKey:c.witnesses.voterCount(e),queryFn:async()=>await X("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Cl=(y=>(y[y.CHECKIN=10]="CHECKIN",y[y.LOGIN=20]="LOGIN",y[y.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",y[y.POST=100]="POST",y[y.COMMENT=110]="COMMENT",y[y.VOTE=120]="VOTE",y[y.REBLOG=130]="REBLOG",y[y.DELEGATION=150]="DELEGATION",y[y.REFERRAL=160]="REFERRAL",y[y.COMMUNITY=170]="COMMUNITY",y[y.TRANSFER_SENT=998]="TRANSFER_SENT",y[y.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",y[y.MINTED=991]="MINTED",y))(Cl||{});async function Rl(e,t){if(!e)throw new Error("[SDK][Points][Claim] \u2013 username wasn't provided");if(!t)throw new Error("[SDK][Points][Claim] \u2013 access token wasn't found");let n=await h()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function jq(e,t,r,n){let{mutateAsync:o}=Ve.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>Rl(e,t),onError:n,onSuccess:()=>{o(),_().setQueryData(ct(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}function Gq(e,t,r,n,o,i){return queryOptions({queryKey:c.search.results(e,t,r,n,o,i),queryFn:async({signal:s})=>{let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let u=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:he(we,s)});if(!u.ok)throw new Error(`Search failed: ${u.status}`);return u.json()}})}function zq(e,t,r=true){return infiniteQueryOptions({queryKey:c.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",u=e==="rising"?"children":e,p=i?i.toISOString().split(".")[0]:void 0,l="0",f=t==="today"?50:200,m={q:a,sort:u,hide_low:l};p&&(m.since=p),n.sid&&(m.scroll_id=n.sid),(m.votes=f);let y=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:he(we,o)});if(!y.ok)throw new Error(`Search failed: ${y.status}`);return y.json()},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r})}async function Vr(e){let r=await(async()=>{try{return await e.json()}catch{try{return await e.text()}catch{return}}})();if(!e.ok){let n=new Error(`Request failed with status ${e.status}`);throw n.status=e.status,n.data=r,n}if(r===void 0)throw new Error("Response body was empty or invalid JSON");return r}async function Xq(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await h()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:he(we,s)});return Vr(p)}async function ri(e,t,r=we){let o=await h()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:he(r,t)});return Vr(o)}async function Zq(e,t){let n=await h()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:he(we,t)}),o=await Vr(n);return o?.length>0?o:[e]}var Dl=4368*60*60*1e3,Il=4,Bl=3e3,Ml=2e3,Nl=4e3,oK=2;function Ql(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Hl(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return (t>>>0).toString(36)}function iK(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=Ql(e.body??"",Bl),i=Hl(`${t}|${n.join(",")}|${o}`);return queryOptions({queryKey:c.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-Dl).toISOString().slice(0,19),u=await ri({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?Ml:Nl),p=[],l=new Set;for(let f of u.results){if(p.length>=Il)break;f.permlink!==e.permlink&&(f.tags??[]).indexOf("nsfw")===-1&&(l.has(f.author)||(l.add(f.author),p.push(f)));}return p},staleTime:300*1e3,retry:false})}function lK(e,t=5){let r=e.trim();return queryOptions({queryKey:c.search.account(r,t),queryFn:async()=>{let n=await g("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Ot(n)},enabled:!!r})}function yK(e,t=10){let r=e.trim();return queryOptions({queryKey:c.search.topics(r,t),queryFn:async()=>(await g("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function bK(e,t,r,n,o,i){return infiniteQueryOptions({queryKey:c.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let u={q:e,sort:t,hide_low:r};n&&(u.since=n),s&&(u.scroll_id=s),o!==void 0&&(u.votes=o),i&&(u.include_nsfw=1);let p=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(u),signal:he(we,a)});if(!p.ok)throw new Error(`Search failed: ${p.status}`);return p.json()},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e})}function OK(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e})});if(!t.ok)throw new Error(`Search path failed: ${t.status}`);let r=await t.json();return r?.length>0?r:[e]}})}async function Wl(e){let r=await h()(d.privateApiHost+"/private-api/support-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function kK(e,t){let r=e?.replace("@","");return queryOptions({queryKey:c.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return Wl(t)},enabled:!!r&&!!t})}async function Jl(e,t){let n=await h()(d.privateApiHost+"/private-api/support-settings-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,beneficiary_percent:t.beneficiary_percent,curation_percent:t.curation_percent})});if(!n.ok){let o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function Yl(e,t,r){return e.setQueryData(c.support.settings(t),r),e.invalidateQueries({queryKey:c.support.settings(t)})}function qK(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Jl(t,o)},onSuccess(o){n&&Yl(r,n,o);}})}function BK(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/boost-plus-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch boost plus prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function HK(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(d.privateApiHost+"/private-api/rc-delegation-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch RC delegation prices: ${t.status}`);return await t.json()},staleTime:1/0,enabled:!!e})}function LK(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/rc-delegation-active",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,username:e})});if(!r.ok)throw new Error(`Failed to fetch RC delegation active: ${r.status}`);let n=await r.json();return n&&n.expires&&n.user?{user:n.user,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function zK(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(d.privateApiHost+"/private-api/promote-price",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!t.ok)throw new Error(`Failed to fetch promote prices: ${t.status}`);return await t.json()},enabled:!!e})}function ZK(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(d.privateApiHost+"/private-api/boosted-plus-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:e})});if(!r.ok)throw new Error(`Failed to fetch boost plus account prices: ${r.status}`);let n=await r.json();return n?{account:n.account,expires:new Date(n.expires)}:null},enabled:!!e&&!!t})}function nD(e,t,r){return b(["promotions","boost-plus"],e,({account:n,duration:o})=>[Fr(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function aD(e,t,r){return b(["promotions","rc-delegation"],e,({duration:n})=>[qr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([c.accounts.full(e),c.resourceCredits.account(e),["promotions","rc-delegation-active",e]]);},t,"active",{broadcastMode:r})}async function pD(e){let r=await h()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var od="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function mD(){return queryOptions({queryKey:c.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(od,{signal:e});if(!t.ok)throw new Error(`Failed to fetch bad actors list: ${t.status}`);let r=await t.text();return new Set(r.split(`
|
|
2
2
|
`).filter(Boolean))},staleTime:1440*60*1e3,gcTime:1/0})}var yD=1.1,id=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(id||{});function hD(e){return e?e.map((t,r)=>({choice_num:r+1,choice_text:t,votes:{total_votes:0,hive_hp:0,hive_proxied_hp:0,hive_hp_incl_proxied:0}})):[]}function ad(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,o=t.map(a=>{let u=a.votes;return {choice_num:a.choice_num??0,choice_text:a.choice_text??"",votes:u?{total_votes:u.total_votes??0,hive_hp:u.hive_hp,hive_proxied_hp:u.hive_proxied_hp,hive_hp_incl_proxied:u.hive_hp_incl_proxied??null}:void 0}}),i=r.map(a=>({name:a.name??"",choices:a.choices??[],hive_hp:a.hive_hp,hive_proxied_hp:a.hive_proxied_hp,hive_hp_incl_proxied:a.hive_hp_incl_proxied})),s=n?{total_voting_accounts_num:n.total_voting_accounts_num??0,total_hive_hp:n.total_hive_hp,total_hive_proxied_hp:n.total_hive_proxied_hp,total_hive_hp_incl_proxied:n.total_hive_hp_incl_proxied??null}:void 0;return {author:e.author??"",permlink:e.permlink??"",question:e.question??"",poll_choices:o,poll_voters:i,poll_stats:s,poll_trx_id:e.poll_trx_id??"",status:e.status??"",end_time:e.end_time??"",preferred_interpretation:e.preferred_interpretation??"number_of_votes",max_choices_voted:e.max_choices_voted??1,filter_account_age_days:e.filter_account_age_days??0,protocol_version:e.protocol_version??0,created:e.created??"",post_title:e.post_title??"",post_body:e.post_body??"",parent_permlink:e.parent_permlink??"",tags:e.tags??[],image:e.image??[],token:e.token,community_membership:e.community_membership,allow_vote_changes:e.allow_vote_changes,ui_hide_res_until_voted:e.ui_hide_res_until_voted??false,platform:e.platform}}function PD(e,t){return queryOptions({queryKey:c.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=h(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,o=await r(n);if(!o.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${o.status}`);let i=await o.json();if(!Array.isArray(i)||!i[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return ad(i[0])}})}function xD(e,t,r){return b(c.polls.vote(),e??"",({pollTrxId:n,choices:o})=>{if(!e)throw new Error("[SDK][Polls] Cannot vote without an authenticated username");return [["custom_json",{id:"polls",required_auths:[],required_posting_auths:[e],json:JSON.stringify({poll:n,action:"vote",choices:o})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}/**
|
|
3
3
|
* @license bytebuffer.ts (c) 2015 Daniel Wirtz <dcode@dcode.io>
|
|
4
4
|
* Backing buffer: ArrayBuffer, Accessor: DataView
|