import{generateBip39Mnemonicasdn,deriveSeedFromBip39Mnemonicasye,deriveHdPrivateNodeFromSeedashn,deriveHdPathaspn,secp256k1asme,hash160asfn,encodeCashAddressasKo,lockingBytecodeToCashAddressasgn,cashAddressToLockingBytecodeasGo,binToHexasyn,hexToBinasWo,utf8ToBinaske,binToBase64asHt,base64ToBinasKt}from"@bitauth/libauth";varEt="bchtest";varGt="m/44'/145'/0'",mn=5,At="bns.wallet.v1";functionbe(t){lete=fn(t);returnUint8Array.from([118,169,20,...e,136,172])}functionwe(t,e,n){leto=gn({bytecode:be(t),prefix:e,tokenSupport:n});if(typeofo=="string")thrownewError(`address encoding failed: ${o}`);returno.address}varWt=classt{constructor(e,n,o=Et,s=Gt){this.mnemonic=e,this.prefix=o,this.accountPath=s,this._root=hn(n),this._keys=newMap,this._derive()}staticasynccreate(e=Et,n=Gt){leto=dn();returnnewt(o,awaitye(o),e,n)}staticasyncfromMnemonic(e,n=Et,o=Gt){lets=String(e).trim().toLowerCase().replace(/\s+/g," "),r=awaitye(s);if(typeofr=="string")thrownewError(`invalid recovery phrase: ${r}`);returnnewt(s,r,n,o)}_derive(){this.receive=[],this.change=[];for(let[e,n]of[[0,this.receive],[1,this.change]])for(leto=0;o<mn;o++){lets=`${this.accountPath}/${e}/${o}`,r=pn(this._root,s);if(typeofr=="string")thrownewError(`HD derivation failed at ${s}: ${r}`);leta=me.derivePublicKeyCompressed(r.privateKey);if(typeofa=="string")thrownewError(`pubkey derivation failed: ${a}`);leti=be(a),l={path:s,branch:e,index:o,privateKey:r.privateKey,publicKey:a,lockingBytecode:i,address:we(a,this.prefix,!1),tokenAddress:we(a,this.prefix,!0)};n.push(l),this._keys.set(yn(i),l)}}getaddress(){returnthis.receive[0].address}gettokenAddress(){returnthis.receive[0].tokenAddress}getwatchedAddresses(){return[...this.receive,...this.change].map(e=>e.address)}keyFor(e){letn=this._keys.get(e);returnn?{privateKey:n.privateKey,publicKey:n.publicKey}:null}signMessage(e,n){if(!(einstanceofUint8Array)||e.length!==32)thrownewError("signMessage expects a 32-byte Uint8Array digest");leto=n||this.address,s=[...this.receive,...this.change].find(h=>h.address===o);if(!s)thrownewError(`no key for address ${o}`);letr=me.signMessageHashRecoverableCompact(s.privateKey,e);if(typeofr=="string")thrownewError(`signMessage failed: ${r}`);let{signature:a}=r,i=r.recoveryId??r.recovery;if(typeofi!="number")thrownewError("signMessage: no recovery id in signature result");letl=31+i,c=newUint8Array(65);returnc[0]=l,c.set(a,1),c}asyncencrypt(e){letn=crypto.getRandomValues(newUint8Array(16)),o=crypto.getRandomValues(newUint8Array(12)),s=awaitxe(e,n),r=newUint8Array(awaitcrypto.subtle.encrypt({name:"AES-GCM",iv:o},s,ke(this.mnemonic)));returnJSON.stringify({v:1,kdf:"PBKDF2-SHA256",iterations:qt,prefix:this.prefix,salt:Ht(n),iv:Ht(o),ct:Ht(r)})}staticasyncdecrypt(e,n){leto=typeofe=="string"?JSON.parse(e):e,s=awaitxe(n,Kt(o.salt),o.iterations??qt),r;try{r=awaitcrypto.subtle.decrypt({name:"AES-GCM",iv:Kt(o.iv)},s,Kt(o.ct))}catch{thrownewError("wrong password")}returnt.fromMnemonic(newTextDecoder().decode(r),o.prefix??Et)}asyncsave(e,n=globalThis.localStorage){n.setItem(At,awaitthis.encrypt(e))}staticasyncload(e,n=globalThis.localStorage){leto=n.getItem(At);returno?t.decrypt(o,e):null}staticexists(e=globalThis.localStorage){return!!e?.getItem(At)}staticforget(e=globalThis.localStorage){e.removeItem(At)}},qt=25e4;asyncfunctionxe(t,e,n=qt){leto=awaitcrypto.subtle.importKey("raw",ke(String(t)),"PBKDF2",!1,["deriveKey"]);returncrypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:n,hash:"SHA-256"},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}varBt=["wss://silentmode.st/electrum","wss://chipnet.bch.ninja:50004","wss://chipnet.imaginary.cash:50004","wss://tbch4.loping.net:62002"],zt=class{constructor(e,n){this.url=e,this.WS=n||globalThis.WebSocket,this.id=0,this.pending=newMap,this.buf=""}connect(){returnnewPromise((e,n)=>{leto=newthis.WS(this.url);this.ws=o;lets=async()=>{try{awaitthis.call("server.version",["bns-web","1.4.2"]),e(this)}catch(i){n(i)}},r=i=>n(newError("el
`))>=0;){let s=this.buf.slice(0,n).trim();if(this.buf=this.buf.slice(n+1),s)try{this._handle(JSON.parse(s))}catch{}}let o=this.buf.trim();if(o)try{let s=JSON.parse(o);this._handle(s),this.buf=""}catch{}}call(e,n=[]){let o=++this.id;return new Promise((s,r)=>{this.pending.set(o,{resolve:s,reject:r}),this.ws.send(JSON.stringify({id:o,method:e,params:n})+`
`),setTimeout(()=>{this.pending.has(o)&&(this.pending.delete(o),r(new Error(`electrumtimeout:${e}`)))},2e4)})}close(){try{this.ws.close()}catch{}}};async function Se(t=Bt,e){let n=[];for(let o of t)try{return await new zt(o,e).connect()}catch(s){n.push(`${o}:${s?.message??s}`)}throw wn(t.length,n)}function wn(t,e){let n=new Error(`noelectrumserverreachable(tried${t}).Theseusenon-standardports,whichsomenetworksandVPNsblock:
${e.join(`
`)}`);returnn.code="NO_ELECTRUM",n.failures=e,n}import{cashAddressToLockingBytecodeasxn,lockingBytecodeToCashAddressaskn,sha256asbn,hash160asYo,binToHexasSn,hexToBinasVo}from"@bitauth/libauth";functionTe(t){returnSn(bn.hash(t).slice().reverse())}functionL(t){lete=xn(t);if(typeofe=="string")thrownewError(`bad address "${t}": ${e}`);returne.bytecode}functionTn(t){returnTe(L(t))}functionW(t){lete=L(t),n=String(t).includes(":")?t.split(":")[0]:"bchtest",o=kn({bytecode:e,prefix:n,tokenSupport:!0});if(typeofo=="string")thrownewError(`cannot token-encode "${t}": ${o}`);returno.address}asyncfunction_e(t,e){letn=L(e),o=Te(n);return(awaitt.call("blockchain.scripthash.listunspent",[o,"include_tokens"])).map(r=>({txid:r.tx_hash,vout:r.tx_pos,satoshis:BigInt(r.value),height:r.height,address:e,lockingBytecode:n,token:r.token_data?{category:r.token_data.category,amount:BigInt(r.token_data.amount??0),nft:r.token_data.nft?{capability:r.token_data.nft.capability,commitment:r.token_data.nft.commitment}:void0}:void0}))}asyncfunctionz(t,e){letn=[];for(letoofe)n.push(...await_e(t,o));returnn}asyncfunctionot(t,e){returnt.call("blockchain.transaction.broadcast",[e])}import{binToHexasPt,hexToBinasV,utf8ToBinaspt,binToUtf8asOe,encodeTransactionas_n,decodeTransactionasQo}from"@bitauth/libauth";varOn="BNS1",ut="bchtest:qp8njaa9a3ahg7259s5qajnce526n0rttsq8qwx4jl",Vt="bchtest:qzc4c76vtw9nd49g6x8nmvc0jz62uvk4dc7hmpmerh",v=600n,I=1000n,K=546n,jt="bch",Yt=200,En=/^[a-z0-9-]{1,32}$/,Ee=/^[a-z0-9-]{1,16}$/;functionkt(t){lete=String(t).toLowerCase().trim().replace(/^\.+/,"").replace(/\.+$/,"");if(!Ee.test(e))thrownewError(`invalid TLD "${t}" (allowed: [a-z0-9-]{1,16})`);returne}varIt=classextendsError{constructor(e){super(e),this.name="NoGenesisInputError",this.code="NO_GENESIS_INPUT"}},J=classextendsError{constructor(e,{needSats:n,haveSats:o}={}){super(e),this.name="InsufficientFundsError",this.code="INSUFFICIENT_FUNDS",this.needSats=n,this.haveSats=o}};functionM(t){lete=String(t).toLowerCase().trim().replace(/\.$/,"").split(".").filter(Boolean),n,o;if(e.length===0)thrownewError(`invalid name "${t}"`);if(e.length===1?(n=e[0],o=jt):(o=e[e.length-1],n=e[e.length-2]),!En.test(n)||!Ee.test(o))thrownewError(`invalid name "${t}" (allowed: <label>.<tld>, [a-z0-9-])`);returno===jt?n:`${n}.${o}`}functionX(t){returnt.includes(".")?t:`${t}.${jt}`}functionQ(t,e,n){leto=JSON.stringify({o:t,n:e,r:n??{}}),s=pt(On+o);if(s.length>Yt)thrownewError(`records too large (${s.length} > ${Yt} bytes)`);returns}functionJt(t,e="REG"){returnYt-Q(e,t,{}).length}functionvn(t){returnt.length<=75?Uint8Array.from([t.length,...t]):t.length<=255?Uint8Array.from([76,t.length,...t]):Uint8Array.from([77,t.length&255,t.length>>8&255,...t])}functiontt(t){returnUint8Array.from([106,...vn(t)])}functionXt(){returnUint8Array.from([65,...newUint8Array(65),33,...newUint8Array(33)])}varAn=t=>!t.token;function$(t,e,{requireGenesis:n=!0}={}){leto=t.filter(An),s=[],r=0n;if(n){leti=o.filter(l=>l.vout===0).sort((l,c)=>c.satoshis>l.satoshis?1:-1);if(i.length===0)thrownewIt("wallet has no coin at output index 0, which CashTokens requires to create a new certificate category \u2014 send a small amount to yourself first (buildPrepTx)");s.push(i[0]),r+=i[0].satoshis}leta=o.filter(i=>!s.some(l=>l.txid===i.txid&&l.vout===i.vout)).sort((i,l)=>l.satoshis>i.satoshis?1:-1);for(letiofa){if(r>=e)break;s.push(i),r+=i.satoshis}return{inputs:s,totalSats:r}}functionft(t){return{outpointTransactionHash:V(t.txid),outpointIndex:t.vout,sequenceNumber:4294967294,unlockingBytecode:Xt()}}functionxt(t){return{...ft(t),lockingBytecode:t.lockingBytecode,valueSatoshis:t.satoshis,...t.token?{token:{amount:t.token.amount??0n,category:V(t.token.category),...t.token.nft?{nft:{capability:t.token.nft.capability,commitment:V(t.token.nft.commitment||"")}}:{}}}:{}}}functionlt(t){return_n(t).length}functionQt({name:t,ownerAddress:e,ownerTokenAddress:n,changeAddress:o,records:s={},utxos:r,feeAddress:a=null,feeSats:i=0n,tldFeeAddress:l=
`))>=0;){let s=this.buf.slice(0,n).trim();if(this.buf=this.buf.slice(n+1),s)try{this._handle(JSON.parse(s))}catch{}}let o=this.buf.trim();if(o)try{let s=JSON.parse(o);this._handle(s),this.buf=""}catch{}}call(e,n=[]){let o=++this.id;return new Promise((s,r)=>{this.pending.set(o,{resolve:s,reject:r}),this.ws.send(JSON.stringify({id:o,method:e,params:n})+`
`),setTimeout(()=>{this.pending.has(o)&&(this.pending.delete(o),r(new Error(`electrumtimeout:${e}`)))},2e4)})}close(){try{this.ws.close()}catch{}}},Fn=t=>typeof t=="string"?{url:t}:t;async function $n(t,e,{directIP:n=!1}={}){let o;for(let s of t){let r=Fn(s);try{return await new Rt(r.url,e).connect()}catch(a){o=a}if(n&&r.ip)try{let a=new URL(r.url),i=`${a.protocol}//${r.ip}:${a.port}`;return await new Rt(i,e,{servername:a.hostname}).connect()}catch(a){o=a}}throw o??new Error("no electrum server reachable")}function De(t){if(!t||!t.startsWith("6a"))return null;let e=Dn(t),n=1,o=[];for(;n<e.length;){let r=e[n++],a;if(r<=75)a=r;else if(r===76)a=e[n++];else if(r===77)a=e[n]|e[n+1]<<8,n+=2;else return null;o.push(e.slice(n,n+a)),n+=a}let s=new TextDecoder().decode(o[0]??new Uint8Array);if(!s.startsWith(Le))return null;try{let r=JSON.parse(s.slice(Le.length));if(Mn.has(r.o)&&typeof r.n=="string")return r}catch{}return null}var Mn=new Set(["REG","UPD","TREG","TUPD"]);function Ue(t,e){let n=t.height>0?t.height:1/0,o=e.height>0?e.height:1/0;return n-o||t.tx_hash.localeCompare(e.tx_hash)}function Fe(t,e){let n=new Set(t.map(i=>i.tx_hash)),o=new Map(t.map(i=>{let l=new Set;for(let c of e.get(i.tx_hash)?.vin??[])c.txid&&c.txid!==i.tx_hash&&n.has(c.txid)&&l.add(c.txid);return[i.tx_hash,l]})),s=new Set,r=[],a=[...t];for(;a.length;){let i=a.findIndex(c=>[...o.get(c.tx_hash)].every(h=>s.has(h)));i<0&&(i=0);let[l]=a.splice(i,1);s.add(l.tx_hash),r.push(l)}return r}function ne(t){let e=t.lastIndexOf(".");return e<0?t:t.slice(e+1)}function Hn(t,e,n){let o=n.get(t);return o?o.regHeight>0&&e>0?o.regHeight<=e:!0:!1}async function se(t){let e=typeof t.unionHistory=="function"?(await t.unionHistory(Ne)).history:await t.call("blockchain.scripthash.get_history",[Ne]);e.sort(Ue);let n=new Map;for(let{tx_hash:s}of e)try{n.set(s,await t.call("blockchain.transaction.get",[s,!0]))}catch{}let o=new Map;for(let{tx_hash:s,height:r}of Fe(e.filter(a=>n.has(a.tx_hash)),n)){let i=n.get(s).vout||[],l=null;for(let h of i)l=De(h.scriptPubKey?.hex)??l;if(!l||typeof l.n!="string"||!Ce.test(l.n))continue;let c=l.n;if(l.o==="TREG"){if(o.has(c))continue;let h=oe(c),u=i.find(d=>d.tokenData?.nft&&d.tokenData.nft.commitment===h);if(!u)continue;o.set(c,{category:u.tokenData.category,regHeight:r,regTxid:s,mintScriptHex:u.scriptPubKey?.hex??null,records:l.r??{},updates:[{height:r,txid:s,records:l.r??{}}]})}else if(l.o==="TUPD"){let h=o.get(c);if(!h||!i.some(u=>u.tokenData&&u.tokenData.category===h.category))continue;h.records=l.r??{},h.updates.push({height:r,txid:s,records:h.records})}}return o}function Kn(t,e){if(!t)return{};let n=t.updates||[];if(!n.length)return t.records||{};let o={};for(let s of n)e>0&&(s.height<=0||s.height>e)||(o=s.records||{});return o}function Gn(t,e){let n=Kn(t,e);return n.policy==="cosign"||n.hidden===1||n.hidden===!0||n.hidden==="1"}function Wn(t,e,n){let o=oe(n);return(t||[]).some(s=>s.tokenData&&s.tokenData.category===e.category&&s.tokenData.nft&&s.tokenData.nft.commitment===o)}function Re(t){if(!t||!t.scriptPubKey)return null;let e=t.scriptPubKey;return typeof e.address=="string"?e.address:Array.isArray(e.addresses)&&e.addresses.length?e.addresses[0]:null}async function St({electrum:t=Cn,WebSocket:e,client:n,directIP:o=!1,enforceTld:s=!1,cosignGate:r=!0}={}){let a=n??await $n(t,e,{directIP:o});try{let i=null;if(s||r)try{i=await se(a)}catch(d){if(s)throw d;i=null}let l=null,c;if(typeof a.unionHistory=="function"){let d=await a.unionHistory(Pe);c=d.history,l={servers:d.servers,unreachable:d.unreachable,disagreements:d.disagreements}}else c=await a.call("blockchain.scripthash.get_history",[Pe]);c.sort(Ue);let h=new Map;for(let{tx_hash:d}of c)try{h.set(d,await a.call("blockchain.transaction.get",[d,!0]))}catch{}let u=new Map;for(let{tx_hash:d,height:p}of Fe(c.filter(m=>h.has(m.tx_hash)),h)){let g=h.get(d).vout||[],f=null;for(let x of g)f=De(x.scriptPubKey?.hex)??f;if(!f)continue;let y=f.n;if(!Ln.test(y))continue;let w=Rn(y);if(f.o==="REG"){if(u.has(w)||s&&!Hn(ne(w),p,i))continue;if(r&&i){let b=i.get(ne(w));if(b&&Gn(b,p)&&!Wn(g,b,ne(w)))contin