import{generateBip39Mnemonic as te,deriveSeedFromBip39Mnemonic as It,deriveHdPrivateNodeFromSeed as ee,deriveHdPath as ne,secp256k1 as se,hash160 as oe,encodeCashAddress as tn,lockingBytecodeToCashAddress as re,cashAddressToLockingBytecode as en,binToHex as ie,hexToBin as nn,utf8ToBin as Ot,binToBase64 as gt,base64ToBin as yt}from"@bitauth/libauth";var nt="bchtest";var ae="m/44'/145'/0'",ce=5,at="bns.wallet.v1";function Ct(e){let t=oe(e);return Uint8Array.from([118,169,20,...t,136,172])}function Dt(e,t,n){let s=re({bytecode:Ct(e),prefix:t,tokenSupport:n});if(typeof s=="string")throw new Error(`address encoding failed: ${s}`);return s.address}var wt=class e{constructor(t,n,s=nt){this.mnemonic=t,this.prefix=s,this._root=ee(n),this._keys=new Map,this._derive()}static async create(t=nt){let n=te();return new e(n,await It(n),t)}static async fromMnemonic(t,n=nt){let s=String(t).trim().toLowerCase().replace(/\s+/g," "),r=await It(s);if(typeof r=="string")throw new Error(`invalid recovery phrase: ${r}`);return new e(s,r,n)}_derive(){this.receive=[],this.change=[];for(let[t,n]of[[0,this.receive],[1,this.change]])for(let s=0;st.address)}keyFor(t){let n=this._keys.get(t);return n?{privateKey:n.privateKey,publicKey:n.publicKey}:null}async encrypt(t){let n=crypto.getRandomValues(new Uint8Array(16)),s=crypto.getRandomValues(new Uint8Array(12)),r=await Rt(t,n),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},r,Ot(this.mnemonic)));return JSON.stringify({v:1,kdf:"PBKDF2-SHA256",iterations:mt,prefix:this.prefix,salt:gt(n),iv:gt(s),ct:gt(o)})}static async decrypt(t,n){let s=typeof t=="string"?JSON.parse(t):t,r=await Rt(n,yt(s.salt),s.iterations??mt),o;try{o=await crypto.subtle.decrypt({name:"AES-GCM",iv:yt(s.iv)},r,yt(s.ct))}catch{throw new Error("wrong password")}return e.fromMnemonic(new TextDecoder().decode(o),s.prefix??nt)}async save(t,n=globalThis.localStorage){n.setItem(at,await this.encrypt(t))}static async load(t,n=globalThis.localStorage){let s=n.getItem(at);return s?e.decrypt(s,t):null}static exists(t=globalThis.localStorage){return!!t?.getItem(at)}static forget(t=globalThis.localStorage){t.removeItem(at)}},mt=25e4;async function Rt(e,t,n=mt){let s=await crypto.subtle.importKey("raw",Ot(String(e)),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:n,hash:"SHA-256"},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}var ct=["wss://silentmode.st/electrum","wss://chipnet.bch.ninja:50004","wss://chipnet.imaginary.cash:50004","wss://tbch4.loping.net:62002"],xt=class{constructor(t,n){this.url=t,this.WS=n||globalThis.WebSocket,this.id=0,this.pending=new Map,this.buf=""}connect(){return new Promise((t,n)=>{let s=new this.WS(this.url);this.ws=s;let r=async()=>{try{await this.call("server.version",["bns-web","1.4.2"]),t(this)}catch(i){n(i)}},o=i=>n(new Error("electrum ws error: "+(i?.message||this.url))),a=i=>this._onData(typeof i.data=="string"?i.data:i.data.toString());s.addEventListener?(s.addEventListener("open",r),s.addEventListener("error",o),s.addEventListener("message",a)):(s.onopen=r,s.onerror=o,s.onmessage=a)})}_handle(t){let n=this.pending.get(t.id);n&&(this.pending.delete(t.id),t.error?n.reject(new Error(JSON.stringify(t.error))):n.resolve(t.result))}_onData(t){this.buf+=t;let n;for(;(n=this.buf.indexOf(` `))>=0;){let r=this.buf.slice(0,n).trim();if(this.buf=this.buf.slice(n+1),r)try{this._handle(JSON.parse(r))}catch{}}let s=this.buf.trim();if(s)try{let r=JSON.parse(s);this._handle(r),this.buf=""}catch{}}call(t,n=[]){let s=++this.id;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.ws.send(JSON.stringify({id:s,method:t,params:n})+` `),setTimeout(()=>{this.pending.has(s)&&(this.pending.delete(s),o(new Error(`electrum timeout: ${t}`)))},2e4)})}close(){try{this.ws.close()}catch{}}};async function Lt(e=ct,t){let n=[];for(let s of e)try{return await new xt(s,t).connect()}catch(r){n.push(`${s}: ${r?.message??r}`)}throw le(e.length,n)}function le(e,t){let n=new Error(`no electrum server reachable (tried ${e}). These use non-standard ports, which some networks and VPNs block: ${t.join(` `)}`);return n.code="NO_ELECTRUM",n.failures=t,n}import{cashAddressToLockingBytecode as de,lockingBytecodeToCashAddress as ue,sha256 as he,hash160 as an,binToHex as pe,hexToBin as cn}from"@bitauth/libauth";function Ft(e){return pe(he.hash(e).slice().reverse())}function S(e){let t=de(e);if(typeof t=="string")throw new Error(`bad address "${e}": ${t}`);return t.bytecode}function fe(e){return Ft(S(e))}function L(e){let t=S(e),n=String(e).includes(":")?e.split(":")[0]:"bchtest",s=ue({bytecode:t,prefix:n,tokenSupport:!0});if(typeof s=="string")throw new Error(`cannot token-encode "${e}": ${s}`);return s.address}async function Ut(e,t){let n=S(t),s=Ft(n);return(await e.call("blockchain.scripthash.listunspent",[s,"include_tokens"])).map(o=>({txid:o.tx_hash,vout:o.tx_pos,satoshis:BigInt(o.value),height:o.height,address:t,lockingBytecode:n,token:o.token_data?{category:o.token_data.category,amount:BigInt(o.token_data.amount??0),nft:o.token_data.nft?{capability:o.token_data.nft.capability,commitment:o.token_data.nft.commitment}:void 0}:void 0}))}async function F(e,t){let n=[];for(let s of t)n.push(...await Ut(e,s));return n}async function z(e,t){return e.call("blockchain.transaction.broadcast",[t])}import{binToHex as St,hexToBin as G,utf8ToBin as st,binToUtf8 as ge,encodeTransaction as ye,decodeTransaction as un}from"@bitauth/libauth";var we="BNS1",Mt="bchtest:qp8njaa9a3ahg7259s5qajnce526n0rttsq8qwx4jl",Ht="bchtest:qzc4c76vtw9nd49g6x8nmvc0jz62uvk4dc7hmpmerh",R=600n,H=1000n,q=546n,bt="bch",kt=200,me=/^[a-z0-9-]{1,32}$/,Wt=/^[a-z0-9-]{1,16}$/;function rt(e){let t=String(e).toLowerCase().trim().replace(/^\.+/,"").replace(/\.+$/,"");if(!Wt.test(t))throw new Error(`invalid TLD "${e}" (allowed: [a-z0-9-]{1,16})`);return t}var lt=class extends Error{constructor(t){super(t),this.name="NoGenesisInputError",this.code="NO_GENESIS_INPUT"}},M=class extends Error{constructor(t,{needSats:n,haveSats:s}={}){super(t),this.name="InsufficientFundsError",this.code="INSUFFICIENT_FUNDS",this.needSats=n,this.haveSats=s}};function P(e){let t=String(e).toLowerCase().trim().replace(/\.$/,"").split(".").filter(Boolean),n,s;if(t.length===0)throw new Error(`invalid name "${e}"`);if(t.length===1?(n=t[0],s=bt):(s=t[t.length-1],n=t[t.length-2]),!me.test(n)||!Wt.test(s))throw new Error(`invalid name "${e}" (allowed: