edge-currency-plugins 3.5.1 → 3.5.2
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.
|
@@ -74,5 +74,5 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
74
74
|
`)}},Rt=()=>{ye(`socket timer with server ${T} expired, check if healthCheck needed`);const qt=Date.now()-yd;wt+sg<qt&&(ye(`submitting healthCheck to server ${T}`),wt=qt,B.healthCheck().then(()=>{Oe.emit(uo.CONNECTION_TIMER,T,qt)}).catch(ir=>Lt(ir)));for(const[ir,fr]of Object.entries(ft))fr.startTime+or<qt&&(fr.generator.throw(new Error(`Timeout for request ${ir}`)).catch(kr=>{ye.error(kr.message)}),en(ft,ir));_t(),Zt()},Zt=()=>{ye(`setupTimer with server ${T}`);let qt=yt+fg;for(const kr of Object.values(ft)){const Cr=kr.startTime+or;Cr<qt&&(qt=Cr)}const ir=Date.now()-yd,fr=qt<ir?0:qt-ir;jt=setTimeout(()=>Rt(),fr)},Vt=qt=>{try{const ir=be(qt);for(const fr of ir)if(fr.id!=null){const kr=fr.id.toString(),Cr=Ge[kr];if(Cr!=null){const Zr=w(ug)(fr.data);if((Zr==null?void 0:Zr.subscribed)!=null){Cr.subscribed=!0,Cr.deferred.resolve(fr.data);continue}Cr.subscribed||Cr.deferred.reject();try{Cr.cb(Cr.cleaner(fr.data))}catch(Fr){throw console.log({uri:T,error:Fr,response:fr,subscription:Cr}),Fr}continue}const Kr=ft[kr];if(Kr!=null){en(ft,kr);const{error:Zr}=fr;try{if(Zr!=null){const jr="message"in Zr?Zr.message:Zr.connected;throw new Error(jr)}let Fr;Kr.task.cleaner!=null?Fr=Kr.task.cleaner(fr.data):Fr=fr.data,Kr.generator.next(Fr).then(jr=>{const Cn=jr.value;typeof Cn!="boolean"&&nr.submitTask(Cn,Kr.generator)}).catch(jr=>{ye.error(jr.message)})}catch(Fr){console.log({uri:T,error:Fr,response:fr,request:Kr}),Kr.generator.throw(Fr).catch(jr=>{ye.error(jr.message)})}continue}throw new Error(`Unknown message id from incoming ws message: ${qt}`)}}catch(ir){Lt(ir)}_t()};Zt();const nr={get readyState(){var qt;return(qt=ue==null?void 0:ue.readyState)!=null?qt:mn.CLOSED},connect(){return md(this,null,function*(){return ue==null||ue.disconnect(),yield new Promise(qt=>{const ir={onOpen:()=>{Ct(),qt()},onMessage:Vt,onError:kr=>{pr=kr},onClose:xt};let fr=T;(T.startsWith("wss:")||T.startsWith("ws:"))&&!T.endsWith("/")&&s0()(T).pathname==="/"&&(fr=T+"/websocket"),fr=tg(fr,B.initOptions),T.startsWith("electrumwss:")&&(fr=T.replace(/^electrumwss:/,"wss:")),T.startsWith("electrumws:")&&(fr=T.replace(/^electrumws:/,"ws:"));try{ue=ag(fr,ir)}catch{ue=ng(fr,ir)}})})},disconnect(){ue==null||ue.disconnect(),ue=null,vt()},isConnected(){return(ue==null?void 0:ue.readyState)===mn.OPEN},submitTask:(qt,ir)=>{const fr=(ot++).toString(),kr={task:qt,startTime:Date.now(),generator:ir};ft[fr]=kr,gt(fr,kr)},subscribe:Nt};return nr}var dg=Object.defineProperty,pg=Object.defineProperties,vg=Object.getOwnPropertyDescriptors,bd=Object.getOwnPropertySymbols,gg=Object.prototype.hasOwnProperty,mg=Object.prototype.propertyIsEnumerable,yg=(T,B)=>(B=Symbol[T])?B:Symbol.for("Symbol."+T),wd=(T,B,L)=>B in T?dg(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,co=(T,B)=>{for(var L in B||(B={}))gg.call(B,L)&&wd(T,L,B[L]);if(bd)for(var L of bd(B))mg.call(B,L)&&wd(T,L,B[L]);return T},xd=(T,B)=>pg(T,vg(B)),Bn=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())}),bg=function(T,B){this[0]=T,this[1]=B},wg=(T,B,L)=>{var ue=(ye,xe,Ee,ke)=>{try{var Ke=L[ye](xe),Ge=(xe=Ke.value)instanceof bg,ft=Ke.done;Promise.resolve(Ge?xe[0]:xe).then(ot=>Ge?ue(ye==="return"?ye:"next",xe[1]?{done:ot.done,value:ot.value}:ot,Ee,ke):Ee({value:ot,done:ft})).catch(ot=>ue("throw",ot,Ee,ke))}catch(ot){ke(ot)}},be=ye=>Oe[ye]=xe=>new Promise((Ee,ke)=>ue(ye,xe,Ee,ke)),Oe={};return L=L.apply(T,B),Oe[yg("asyncIterator")]=()=>Oe,be("next"),be("throw"),be("return"),Oe};function Md(T){var B;const{asAddress:L,asResponse:ue,connectionUri:be,engineEmitter:Oe,log:ye,taskGeneratorFn:xe,socketEmitter:Ee,walletId:ke}=T;ye(`makeBlockbook with uri ${be}`);const Ke={isConnected:!1,broadcastTx(ot){return Bn(this,null,function*(){return yield Ke.promisifyWsMessage(Yv(ot.signedTx))})},connect(){return Bn(this,null,function*(){ye(`connecting to blockbook socket with uri ${be}`),!Ke.isConnected&&(yield Ge.connect(),Ke.isConnected=Ge.isConnected())})},disconnect(){return Bn(this,null,function*(){ye(`disconnecting from blockbook socket with uri ${be}, currently connected: ${Ke.isConnected}`),Ke.isConnected&&(Ge.disconnect(),Ke.isConnected=!1)})},fetchAddress(ot){return Bn(this,arguments,function*(wt,yt={}){return yield Ke.promisifyWsMessage(cd(wt,L,yt))})},fetchAddressUtxos(ot){return Bn(this,null,function*(){return yield Ke.promisifyWsMessage(sd(ot))})},fetchInfo(){return Bn(this,null,function*(){return yield Ke.promisifyWsMessage(Wv())})},fetchTransaction(ot){return Bn(this,null,function*(){return yield Ke.promisifyWsMessage(fd(ot))})},promisifyWsMessage(ot){return Bn(this,null,function*(){const wt=new tu,Bt=function(){return wg(this,null,function*(){const or=yield co({},ot);return wt.resolve(or),!1})}(),Gt=yield Bt.next();if(Gt.done!==!0){const or=Gt.value;Ge.submitTask(or,Bt)}return yield wt.promise})},watchAddresses(ot,wt){const yt=Bt=>Bn(this,null,function*(){Oe.emit(Hr.NEW_ADDRESS_TRANSACTION,be,Bt)});Ge.subscribe(xd(co({},Qv(ot,L)),{cb:yt,deferred:wt,subscribed:!1}))},watchBlocks(ot){return Bn(this,null,function*(){const wt=yt=>Bn(this,null,function*(){Oe.emit(Hr.BLOCK_HEIGHT_CHANGED,be,yt.height)});Ge.subscribe(xd(co({},$v()),{cb:wt,deferred:ot,subscribed:!1}))})},addressQueryTask:function*(ot,wt){return yield co({},cd(ot,wt.asBlockbookAddress,{details:"txs",from:wt.lastQueriedBlockHeight,pageSize:Ov,page:wt.page}))},transactionQueryTask:function*(ot){return yield co({},fd(ot))},transactionSpecialQueryTask:function*(ot){return yield co({},Xv(ot))},utxoListQueryTask:function*(ot,wt){return yield co({},sd(ot,wt.asBlockbookAddress))}},Ge=hg(be,{asResponse:ue,healthCheck:(B=T.ping)!=null?B:ft,initOptions:T.initOptions,taskGeneratorFn:xe,log:ye,emitter:Ee,walletId:ke});function ft(){return Bn(this,null,function*(){yield Ke.promisifyWsMessage(Kv())})}return Ke}const xg=x({tx_pos:m,value:m,tx_hash:p,height:m}),Iy=(T=asString)=>asObject({blockhash:asString,blocktime:asNumber,confirmations:asNumber,hash:asString,hex:asString,locktime:asNumber,size:asNumber,time:asNumber,txid:asString,version:asNumber,vin:asArray(asObject({scriptSig:asObject({asm:asString,hex:asString}),sequence:asNumber,txid:asString,vout:asNumber})),vout:asArray(asObject({n:asNumber,scriptPubKey:asObject({addresses:asArray(T),asm:asString,hex:asString,reqSigs:asNumber,type:asString}),value:asNumber}))}),Mg=x({error:x({message:p})}),ru=T=>B=>{const L=w(Mg)(B);if(L!=null)throw new Error(`Electrum Error: ${L.error.message}`);return T(B)},Eg=()=>({method:"server.ping",params:void 0,cleaner:ru(Sg)}),Sg=w(o),kg=T=>({method:"blockchain.scripthash.listunspent",params:[T],cleaner:ru(Ig)}),Ig=E(xg),_g=T=>({method:"blockchain.scripthash.get_history",params:[T],cleaner:ru(Ag)}),Ag=E(x({height:m,tx_hash:p})),_y=(T,B=asString)=>({method:"blockchain.transaction.get",params:[T,!0],cleaner:ru(Tg(B))}),Tg=null;var Pg=$t(8287).Buffer,Og=Object.defineProperty,Ed=Object.getOwnPropertySymbols,Bg=Object.prototype.hasOwnProperty,Cg=Object.prototype.propertyIsEnumerable,Rg=(T,B)=>(B=Symbol[T])?B:Symbol.for("Symbol."+T),Sd=(T,B,L)=>B in T?Og(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,kd=(T,B)=>{for(var L in B||(B={}))Bg.call(B,L)&&Sd(T,L,B[L]);if(Ed)for(var L of Ed(B))Cg.call(B,L)&&Sd(T,L,B[L]);return T},Ri=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())}),Id=function(T,B){this[0]=T,this[1]=B},Fg=(T,B,L)=>{var ue=(ye,xe,Ee,ke)=>{try{var Ke=L[ye](xe),Ge=(xe=Ke.value)instanceof Id,ft=Ke.done;Promise.resolve(Ge?xe[0]:xe).then(ot=>Ge?ue(ye==="return"?ye:"next",xe[1]?{done:ot.done,value:ot.value}:ot,Ee,ke):Ee({value:ot,done:ft})).catch(ot=>ue("throw",ot,Ee,ke))}catch(ot){ke(ot)}},be=ye=>Oe[ye]=xe=>new Promise((Ee,ke)=>ue(ye,xe,Ee,ke)),Oe={};return L=L.apply(T,B),Oe[Rg("asyncIterator")]=()=>Oe,be("next"),be("throw"),be("return"),Oe};const Ng=T=>{const B=D(x({id:p,result:g,error:M(v(x({message:p}),x({connected:p})))}))(T);return{id:B.id,data:B.result,error:B.error}},Dg=T=>p(T).trimEnd().split(`
|
|
75
75
|
`).map(Ng);function Lg(T){const{asAddress:B,connectionUri:L,engineEmitter:ue,initOptions:be,log:Oe,taskGeneratorFn:ye,pluginInfo:xe,socketEmitter:Ee,walletId:ke}=T;Oe(`makeBlockbookElectrum with uri ${L}`);const Ke=ft=>{const ot=li({address:ft,coin:xe.coinInfo.name});return qe.Et.sha256(Pg.from(ot,"hex")).reverse().toString("hex")},Ge=Md({asAddress:B,asResponse:Dg,connectionUri:L,engineEmitter:ue,initOptions:be,log:Oe,taskGeneratorFn:function(ft){return Fg(this,null,function*(){const ot=ye(ft);let wt;for(;;){const yt=yield new Id(ot.next(wt)),Bt=yt.value;if((yt==null?void 0:yt.done)===!0)return yt.value;if(typeof Bt=="boolean")return Bt;if(Bt.method==="getAccountUtxo"){const Gt=Bt.params,or=B!=null?B(Gt.descriptor):Gt.descriptor,pr=Ke(or);wt=(yield kd({},kg(pr))).map(vt=>({txid:vt.tx_hash,vout:vt.tx_pos,value:vt.value.toString(),height:vt.height}));continue}if(Bt.method==="getAccountInfo"){const Gt=Bt.params,or=B!=null?B(Gt.descriptor):Gt.descriptor,pr=Ke(or),jt=yield kd({},_g(pr));wt={address:or,balance:"0",totalReceived:"0",totalSent:"0",txs:jt.length,unconfirmedBalance:"0",unconfirmedTxs:jt.reduce((vt,xt)=>vt+xt.height>=0?1:0,0),txids:[],transactions:[],page:0,totalPages:1,itemsOnPage:0};continue}}})},ping:()=>Ri(this,null,function*(){return yield Ge.promisifyWsMessage(Eg())}),socketEmitter:Ee,walletId:ke});return Ge.broadcastTx=()=>Ri(this,null,function*(){throw new Error("broadcastTx not supported for Electrum connections")}),Ge.fetchAddress=()=>Ri(this,null,function*(){throw new Error("fetchAddress not supported for Electrum connections")}),Ge.fetchAddressUtxos=()=>Ri(this,null,function*(){throw new Error("fetchAddressUtxos not supported for Electrum connections")}),Ge.fetchInfo=()=>Ri(this,null,function*(){throw new Error("fetchInfo not supported for Electrum connections")}),Ge.fetchTransaction=()=>Ri(this,null,function*(){throw new Error("fetchTransaction not supported for Electrum connections")}),Ge.watchAddresses=()=>Ri(this,null,function*(){}),Ge.watchBlocks=()=>Ri(this,null,function*(){}),Ge}var nu=(T,B)=>(B=Symbol[T])?B:Symbol.for("Symbol."+T),iu=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())}),Wa=function(T,B){this[0]=T,this[1]=B},Ug=(T,B,L)=>{var ue=(ye,xe,Ee,ke)=>{try{var Ke=L[ye](xe),Ge=(xe=Ke.value)instanceof Wa,ft=Ke.done;Promise.resolve(Ge?xe[0]:xe).then(ot=>Ge?ue(ye==="return"?ye:"next",xe[1]?{done:ot.done,value:ot.value}:ot,Ee,ke):Ee({value:ot,done:ft})).catch(ot=>ue("throw",ot,Ee,ke))}catch(ot){ke(ot)}},be=ye=>Oe[ye]=xe=>new Promise((Ee,ke)=>ue(ye,xe,Ee,ke)),Oe={};return L=L.apply(T,B),Oe[nu("asyncIterator")]=()=>Oe,be("next"),be("throw"),be("return"),Oe},Fi=T=>{var B=T[nu("asyncIterator")],L=!1,ue,be={};return B==null?(B=T[nu("iterator")](),ue=Oe=>be[Oe]=ye=>B[Oe](ye)):(B=B.call(T),ue=Oe=>be[Oe]=ye=>{if(L){if(L=!1,Oe==="throw")throw ye;return ye}return L=!0,{done:!1,value:new Wa(new Promise(xe=>{var Ee=B[Oe](ye);if(!(Ee instanceof Object))throw TypeError("Object expected");xe(Ee)}),1)}}),be[nu("iterator")]=()=>be,ue("next"),"throw"in B?ue("throw"):be.throw=Oe=>{throw Oe},"return"in B&&ue("return"),be};function Hg(T){const{engineEmitter:B,initOptions:L,io:ue,log:be,pluginInfo:Oe,pluginState:ye,walletInfo:xe}=T,{serverConfigs:Ee=[]}=Oe.engineInfo;be("Making server states");const ke={};let Ke=!0,Ge=[],ft=0,ot=setTimeout(()=>{},0);const wt=new ig;wt.on(uo.CONNECTION_OPEN,vt=>{ft=0,be(`${vt} ** Connected **`)}),wt.on(uo.CONNECTION_CLOSE,(vt,xt)=>{en(ke,vt);const Ct=xt!=null?` !! Connection ERROR !! ${xt.message}`:"";be(`${vt} onClose ${Ct}`),xt!=null&&ye.serverScoreDown(vt),Gt()}),wt.on(uo.CONNECTION_TIMER,(vt,xt)=>{const Ct=Date.now()-xt;be(`${vt} returned healthCheck in ${Ct}ms`),ye.serverScoreUp(vt,Ct)}),B.on(Hr.NEW_ADDRESS_TRANSACTION,(vt,xt)=>{be(`${vt} received received new transaction with id ${xt.tx.txid} to address ${xt.address}`);const Ct=ke[vt];Ct!=null&&Ct.txids.add(xt.tx.txid)}),B.on(Hr.BLOCK_HEIGHT_CHANGED,(vt,xt)=>{be(`${vt} block height changed to ${xt}`),ke[vt].blockHeight=xt});let yt;const Bt=vt=>({blockbook:vt,blockSubscriptionStatus:"unsubscribed",txids:new Set,addresses:new Set,blockHeight:0}),Gt=()=>{if(Ke){be(`attempting server reconnect number ${ft}`);const vt=Math.max(5,ft++)*1e3;ot=setTimeout(()=>{clearTimeout(ot),Lt.refillServers()},vt)}},or=()=>{const vt=["wss:","ws:","electrumwss:","electrumws:"];Ge.length===0&&(Ge=ye.getLocalServers(rd,vt)),be(`refillServers: Top ${rd} servers:`,Ge);let xt=1.25;for(;Object.keys(ke).length<Cv;){let Nt=function(){return Ug(this,null,function*(){if(Ct==null||!(Ct in ke))return!1;const gt=yt(Ct);let Rt=yield new Wa(gt.next());for(;;){if((Rt==null?void 0:Rt.done)===!0)return Rt.value;const Zt=Rt.value;if(typeof Zt!="boolean"){const Vt=`${Zt.method} params: ${JSON.stringify(Zt.params)}`;be(`${Ct} nextTask: ${Vt}`)}try{const Vt=yield Zt;Rt=yield new Wa(gt.next(Vt))}catch(Vt){Rt=yield new Wa(gt.throw(Vt).catch(nr=>(be.error(nr),{done:!0,value:!1})))}}})};if(Ge.length===0)break;const Ct=Ge.shift();if(Ct==null){Gt();break}if(ke[Ct]!=null)continue;const _t=(0,nd.parse)(Ct);if(_t.scheme==null||_t.scheme.length<2||_t.host==null)continue;if(xt-=xt>.5?.25:0,Math.random()>xt){Ge.push(Ct);continue}let kt;["electrumwss","electrumws"].includes(_t.scheme)?kt=Lg({asAddress:Oe.engineInfo.asBlockbookAddress,connectionUri:Ct,engineEmitter:B,initOptions:L,log:be,taskGeneratorFn:Nt,pluginInfo:Oe,socketEmitter:wt,walletId:xe.id}):kt=Md({asAddress:Oe.engineInfo.asBlockbookAddress,connectionUri:Ct,engineEmitter:B,initOptions:L,log:be,taskGeneratorFn:Nt,socketEmitter:wt,walletId:xe.id}),ke[Ct]=Bt(kt),kt.connect().then(()=>iu(this,null,function*(){const gt=Date.now(),{bestHeight:Rt}=yield kt.fetchInfo();be("height:",Rt),ke[Ct].blockHeight=Rt,B.emit(Hr.BLOCK_HEIGHT_CHANGED,Ct,Rt);const Zt=Date.now()-gt;ye.serverScoreUp(Ct,Zt)})).catch(gt=>{be.error(`${JSON.stringify(gt.message)}`)})}},pr=(vt,xt)=>{if(ke[vt]==null)throw new Error(`No blockbook connection with ${vt}`);const _t=Date.now(),kt=new tu;return kt.promise.then(Nt=>{ye.serverScoreUp(vt,Date.now()-_t),xt.resolve(Nt)},Nt=>{ye.serverScoreDown(vt),xt.reject(Nt)}),kt};function*jt(vt,xt){if(ke[vt]==null)throw new Error(`No blockbook connection with ${vt}`);const _t=Date.now();let kt;try{kt=yield*Fi(xt),ye.serverScoreUp(vt,Date.now()-_t)}catch(Nt){throw ye.serverScoreDown(vt),Nt}return kt}const Lt={broadcastTx(vt){return iu(this,null,function*(){return yield new Promise((xt,Ct)=>{let _t=!1,kt=0;const Nt=Object.keys(ke).filter(Rt=>ke[Rt].blockbook!=null);if(Nt.length<1){Ct(new Error("Unexpected error. Missing WebSocket connections."));return}const gt=Nt.some(Rt=>ke[Rt].blockbook.isConnected);if(gt)for(const Rt of Nt){const{blockbook:Zt}=ke[Rt];Zt!=null&&Zt.broadcastTx(vt).then(Vt=>{_t||(_t=!0,xt(Vt.result))}).catch(Vt=>{if(++kt===Nt.length){const nr=Vt!=null?`With error ${Vt.message}`:"";be.error(`broadcastTx fail: ${JSON.stringify(vt)}
|
|
76
76
|
${nr}`),Ct(Vt)}})}if(!gt){const{nowNodesApiKey:Rt}=L,Zt=Ee.filter(Vt=>Vt.type==="blockbook-nownode").map(Vt=>Vt.uris).flat(1);if(Zt.length<1){Ct(new Error("No available connections. Check your internet signal."));return}if(Rt==null){Ct(new Error("Missing connection key for fallback servers."));return}for(const Vt of Zt)be.warn("Falling back to NOWNode server broadcast over HTTP:",Vt),ue.fetchCors(`${Vt}/api/v2/sendtx/`,{method:"POST",headers:{"api-key":Rt},body:vt.signedTx}).then(nr=>iu(this,null,function*(){if(!nr.ok)throw new Error(`Failed to broadcast transaction via Blockbook: HTTP ${nr.status}`);const qt=yield nr.json();return $n(ud)(qt)})).then(nr=>{_t||(_t=!0,xt(nr.result))}).catch(nr=>{if(++kt===Zt.length){const qt=nr!=null?`With error ${nr.message}`:"";be.error(`broadcastTx fail: ${JSON.stringify(vt)}
|
|
77
|
-
${qt}`),Ct(nr)}})}})})},getBlockHeight(vt){return ke[vt].blockHeight},getServerList(){return Ge},getServerState(vt){return ke[vt]},refillServers(){be("refilling servers..."),Ke=!0,pd({id:xe.id,updateFunc:()=>{or()}})},setPickNextTaskCB(vt){yt=vt},setServerList(vt){Ge=vt},serverCanGetTx(vt,xt){const Ct=ke[vt];if(Ct==null)return!1;if(Ct.txids.has(xt))return!0;for(const _t of Object.values(ke))if(_t.txids.has(xt))return!1;return!0},serverCanGetAddress(vt,xt){const Ct=ke[vt];if(Ct==null)return!1;if(Ct.addresses.has(xt))return!0;for(const _t of Object.values(ke))if(_t.addresses.has(xt))return!1;return!0},serverIsAwareOfAddress(vt,xt){const Ct=ke[vt];return Ct==null?!1:!!Ct.addresses.has(xt)},stop(){return iu(this,null,function*(){Ke=!1,be("stopping server states"),vd(xe.id),clearTimeout(ot);for(const vt of Object.keys(ke)){const xt=ke[vt],{blockbook:Ct}=xt;Ct!=null&&(yield Ct.disconnect(),en(ke,vt))}})},watchAddresses(vt,xt,Ct){const _t=ke[vt];if(_t==null)throw new Error(`No blockbook connection with ${vt}`);const{blockbook:kt}=_t;for(const gt of xt)_t.addresses.add(gt);const Nt=new tu;Nt.promise.catch(gt=>{for(const Rt of xt)_t.addresses.delete(Rt);Ct==null||Ct.reject(gt)}),kt.watchAddresses(Array.from(_t.addresses),pr(vt,Nt))},watchBlocks(vt){const xt=ke[vt];if(xt==null)throw new Error(`No blockbook connection with ${vt}`);const{blockbook:Ct}=xt;xt.blockSubscriptionStatus="subscribing";const _t=new tu;_t.promise.then(()=>{xt.blockSubscriptionStatus="subscribed"}).catch(()=>{xt.blockSubscriptionStatus="unsubscribed"}),Ct.watchBlocks(pr(vt,_t))},addressQueryTask:function*(vt,xt,Ct){const _t=ke[vt];if(_t==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return yield*Fi(_t.blockbook.addressQueryTask(xt,{asBlockbookAddress:Oe.engineInfo.asBlockbookAddress,lastQueriedBlockHeight:Ct.lastQueriedBlockHeight,page:Ct.page}))}()))},transactionQueryTask:function*(vt,xt){const Ct=ke[vt];if(Ct==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return yield*Fi(Ct.blockbook.transactionQueryTask(xt))}()))},transactionSpecialQueryTask:function*(vt,xt){const Ct=ke[vt];if(Ct==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return Ct.blockbook.transactionSpecialQueryTask(xt)}()))},utxoListQueryTask:function*(vt,xt){const Ct=ke[vt];if(Ct==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return yield*Fi(Ct.blockbook.utxoListQueryTask(xt,{asBlockbookAddress:Oe.engineInfo.asBlockbookAddress}))}()))}};return Lt}var zg=Object.defineProperty,Kg=Object.defineProperties,jg=Object.getOwnPropertyDescriptors,_d=Object.getOwnPropertySymbols,Wg=Object.prototype.hasOwnProperty,Gg=Object.prototype.propertyIsEnumerable,ou=(T,B)=>(B=Symbol[T])?B:Symbol.for("Symbol."+T),Ad=(T,B,L)=>B in T?zg(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,Ni=(T,B)=>{for(var L in B||(B={}))Wg.call(B,L)&&Ad(T,L,B[L]);if(_d)for(var L of _d(B))Gg.call(B,L)&&Ad(T,L,B[L]);return T},Di=(T,B)=>Kg(T,jg(B)),Yr=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())}),Vr=function(T,B){this[0]=T,this[1]=B},Vo=(T,B,L)=>{var ue=(ye,xe,Ee,ke)=>{try{var Ke=L[ye](xe),Ge=(xe=Ke.value)instanceof Vr,ft=Ke.done;Promise.resolve(Ge?xe[0]:xe).then(ot=>Ge?ue(ye==="return"?ye:"next",xe[1]?{done:ot.done,value:ot.value}:ot,Ee,ke):Ee({value:ot,done:ft})).catch(ot=>ue("throw",ot,Ee,ke))}catch(ot){ke(ot)}},be=ye=>Oe[ye]=xe=>new Promise((Ee,ke)=>ue(ye,xe,Ee,ke)),Oe={};return L=L.apply(T,B),Oe[ou("asyncIterator")]=()=>Oe,be("next"),be("throw"),be("return"),Oe},Jn=T=>{var B=T[ou("asyncIterator")],L=!1,ue,be={};return B==null?(B=T[ou("iterator")](),ue=Oe=>be[Oe]=ye=>B[Oe](ye)):(B=B.call(T),ue=Oe=>be[Oe]=ye=>{if(L){if(L=!1,Oe==="throw")throw ye;return ye}return L=!0,{done:!1,value:new Vr(new Promise(xe=>{var Ee=B[Oe](ye);if(!(Ee instanceof Object))throw TypeError("Object expected");xe(Ee)}),1)}}),be[ou("iterator")]=()=>be,ue("next"),"throw"in B?ue("throw"):be.throw=Oe=>{throw Oe},"return"in B&&ue("return"),be};function Td(T){const{dataLayer:B,initOptions:L,io:ue,emitter:be,engineOptions:Oe,pluginState:ye,pluginInfo:xe,seenTxCheckpoint:Ee,walletInfo:ke,walletTools:Ke}=T,{log:Ge}=Oe,{walletFormats:ft}=ke.keys,ot={addressForTransactionsCache:{},addressForUtxosCache:{},addressSubscribeCache:{},blockbookUtxoCache:{},dataLayerUtxoCache:{},transactionSpecificUpdateCache:{},transactionUpdateCache:{}},wt=()=>{for(const kt of Object.keys(ot.addressForTransactionsCache))en(ot.addressForTransactionsCache,kt);for(const kt of Object.keys(ot.addressForUtxosCache))en(ot.addressForUtxosCache,kt);for(const kt of Object.keys(ot.addressSubscribeCache))en(ot.addressSubscribeCache,kt);for(const kt of Object.keys(ot.blockbookUtxoCache))en(ot.blockbookUtxoCache,kt);for(const kt of Object.keys(ot.dataLayerUtxoCache))en(ot.dataLayerUtxoCache,kt);for(const kt of Object.keys(ot.transactionSpecificUpdateCache))en(ot.transactionSpecificUpdateCache,kt);for(const kt of Object.keys(ot.transactionUpdateCache))en(ot.transactionUpdateCache,kt)},yt=2;let Bt=0,Gt=0;const or=()=>Yr(this,null,function*(){if(Gt>=1)return;const kt=Object.keys(ot.addressSubscribeCache).length*yt;if(Bt=Bt+1,kt===0)throw new Error("No addresses to process");const Nt=Bt/kt;(Nt-Gt>Bv||Nt===1)&&(Ge(`processed changed, percent: ${Nt}, processedCount: ${Bt}, totalCount: ${kt}`),Gt=Nt,be.emit(Hr.ADDRESSES_CHECKED,Nt))}),pr=()=>{if(Gt<1)return;const kt=vt.seenTxCheckpoint(),Nt=kt!=null?parseInt(kt):void 0;if(Nt==null||vt.maxSeenTxBlockHeight>Nt){const gt=vt.maxSeenTxBlockHeight.toString();vt.emitter.emit(Hr.SEEN_TX_CHECKPOINT,gt)}},jt=new Th,Lt=Hg({engineEmitter:be,initOptions:L,io:ue,log:Ge,pluginInfo:xe,pluginState:ye,walletInfo:ke}),vt={pluginInfo:xe,walletInfo:ke,walletTools:Ke,dataLayer:B,emitter:be,taskCache:ot,updateProgressRatio:or,updateSeenTxCheckpoint:pr,io:ue,log:Ge,maxSeenTxBlockHeight:0,seenTxCheckpoint:Ee,serverStates:Lt,walletFormats:ft,lock:jt};Lt.setPickNextTaskCB(kt=>qg(vt,kt));let xt=!1;const Ct=()=>Yr(this,null,function*(){xt||(xt=!0,yield _t(),yield au(vt))});be.on(Hr.BLOCK_HEIGHT_CHANGED,(kt,Nt)=>Yr(this,null,function*(){const gt=yield B.fetchTransactions({blockHeight:0});for(const Rt of gt)Rt!=null&&(ot.transactionUpdateCache[Rt.txid]={processing:!1})})),be.on(Hr.NEW_ADDRESS_TRANSACTION,(kt,Nt)=>Yr(this,null,function*(){const gt=ot.addressSubscribeCache[Nt.address];if(gt!=null){const{path:Rt}=gt;ot.addressForUtxosCache[Nt.address]={processing:!1,path:Rt},Od(vt,{address:Nt.address,changePath:Rt,blockHeight:0,addressForTransactionsCache:ot.addressForTransactionsCache}).catch(()=>{throw new Error("failed to add to transaction cache")}),au(vt).catch(Zt=>{Ge(Zt)})}}));const _t=()=>Yr(this,null,function*(){const kt=[];for(const Nt of ft){const gt=Yh(xe.engineInfo,Nt);for(const Rt of gt){const Zt=new Set,Vt={format:Nt,changeIndex:Rt},nr=B.numAddressesByFormatPath(Vt);for(let qt=0;qt<nr;qt++){const ir=yield B.fetchAddress({format:Nt,changeIndex:Rt,addressIndex:qt});if(ir==null)throw new Error(`Missing data-layer address with '${Nt}/${Rt}/${qt}' path during initialization`);const{address:fr}=Ke.scriptPubkeyToAddress({changePath:Vt,scriptPubkey:ir.scriptPubkey});Zt.add(fr),ir.balance!=null&&kt.push({scriptPubkey:ir.scriptPubkey,balance:ir.balance})}u0(vt.taskCache,Zt,{format:Nt,changeIndex:Rt})}}be.emit(Hr.ADDRESS_BALANCE_CHANGED,xe.currencyInfo.currencyCode,kt)});return{processedPercent:Gt,start(){return Yr(this,null,function*(){Bt=0,Gt=0,yield Ct(),Lt.refillServers()})},stop(){return Yr(this,null,function*(){Lt.stop(),wt(),xt=!1})},getFreshAddress(kt){return Yr(this,arguments,function*({branch:Nt=0,forceIndex:gt}){const{privateKeyFormat:Rt}=ke.keys;Rt==="bip32"&&(Nt=0);const{address:Zt,nativeBalance:Vt="0",legacyAddress:nr}=yield Pd(vt,{forceIndex:gt,changePath:{format:Rt,changeIndex:Nt}}),qt={publicAddress:Zt,nativeBalance:Vt,legacyAddress:nr!==Zt?nr:void 0,legacyNativeBalance:nr!==Zt?Vt:void 0},ir=Jf(xe.engineInfo,ke.keys.privateKeyFormat).filter(fr=>fr!==Rt);for(const fr of ir)if(fr==="bip84"){const{address:kr,nativeBalance:Cr="0"}=yield Pd(vt,{forceIndex:gt,changePath:{format:fr,changeIndex:Nt}});qt.segwitAddress=kr,qt.segwitNativeBalance=Cr}return qt})},deriveScriptAddress(kt){return Yr(this,null,function*(){const{address:Nt}=yield Vg({walletTools:vt.walletTools,engineInfo:vt.pluginInfo.engineInfo,dataLayer:vt.dataLayer,taskCache:vt.taskCache,format:ke.keys.privateKeyFormat,script:kt});return{publicAddress:Nt}})},addGapLimitAddresses(kt){return Yr(this,null,function*(){const Nt=kt.map(gt=>Yr(this,null,function*(){const Rt=Ke.addressToScriptPubkey(gt);yield B.saveAddress(_r({scriptPubkey:Rt,used:!0}))}));yield Promise.all(Nt),yield Ct()})},broadcastTx(kt){return Yr(this,null,function*(){return yield Lt.broadcastTx(kt)})},refillServers(){Lt.refillServers()},getServerList(){return Lt.getServerList()},setServerList(kt){Lt.setServerList(kt)},loadWifs(kt){return Yr(this,null,function*(){for(const Nt of kt)for(const gt of ft){const Rt={format:gt,changeIndex:0},Zt=Di(Ni({},Rt),{addressIndex:0}),{scriptPubkey:Vt,redeemScript:nr}=Ke.getScriptPubkeyFromWif(Nt,gt),{address:qt}=Ke.scriptPubkeyToAddress({changePath:Zt,scriptPubkey:Vt});yield B.saveAddress(_r({scriptPubkey:Vt,redeemScript:nr,path:Zt})),ot.addressSubscribeCache[qt]={path:Rt,processing:!1}}})},processUtxos(kt){return Yr(this,null,function*(){var Nt;const gt=new Map,Rt=new Set;for(const Zt of kt){const Vt=(Nt=gt.get(Zt.scriptPubkey))!=null?Nt:[];gt.has(Zt.scriptPubkey)||gt.set(Zt.scriptPubkey,Vt),Vt.push(Zt),Rt.add(Zt.id)}for(const[Zt,Vt]of gt.entries()){const ir=[...(yield B.fetchUtxos({scriptPubkey:Zt})).filter(fr=>fr!=null&&!Rt.has(fr==null?void 0:fr.id)),...Vt];yield Cd(vt,{scriptPubkey:Zt,utxos:ir})}})}}}const Vg=T=>Yr(void 0,null,function*(){const{walletTools:B,engineInfo:L,dataLayer:ue,format:be,taskCache:Oe,script:ye}=T;if(L.scriptTemplates==null)throw new Error(`cannot derive script address ${ye} without defined script template`);const xe=L.scriptTemplates[ye],Ee={format:be,changeIndex:Da(xe),addressIndex:0},{address:ke,scriptPubkey:Ke,redeemScript:Ge}=B.getScriptAddress({path:Ee,scriptTemplate:xe});yield ue.saveAddress(_r({scriptPubkey:Ke,redeemScript:Ge,path:Ee}));const ft=new Set;return ft.add(ke),u0(Oe,ft,{format:Ee.format,changeIndex:Ee.changeIndex}),{address:ke,scriptPubkey:Ke,redeemScript:Ge}}),Pd=(T,B)=>Yr(void 0,null,function*(){var L;const{changePath:ue,forceIndex:be}=B,Oe=T.dataLayer.numAddressesByFormatPath(ue),ye={format:ue.format,changeIndex:ue.changeIndex,addressIndex:Math.max(Oe-T.pluginInfo.engineInfo.gapLimit,0)};be!=null&&(ye.addressIndex=be);const xe=yield T.dataLayer.fetchAddress(ye),Ee=(L=xe==null?void 0:xe.balance)!=null?L:"0",{scriptPubkey:ke}=xe!=null?xe:yield T.walletTools.getScriptPubkey(ye);if(ke==null)throw new Error("Unknown address path");const Ke=T.walletTools.scriptPubkeyToAddress({changePath:ye,scriptPubkey:ke});return Di(Ni({},Ke),{nativeBalance:Ee})}),au=T=>Yr(void 0,null,function*(){yield T.lock.acquireAsync();try{for(const L of T.walletFormats){const ue=Yh(T.pluginInfo.engineInfo,L);for(const be of ue)yield B({format:L,changeIndex:be})}}finally{T.lock.release()}function B(L){return Yr(this,null,function*(){const ue=new Set,be=T.dataLayer.numAddressesByFormatPath(L);let Oe=yield T.dataLayer.lastUsedIndexByFormatPath(L),ye=Oe+T.pluginInfo.engineInfo.gapLimit,xe=be;for(;xe<=ye;){const Ee=Di(Ni({},L),{addressIndex:xe}),{scriptPubkey:ke,redeemScript:Ke}=T.walletTools.getScriptPubkey(Ee),{address:Ge}=T.walletTools.scriptPubkeyToAddress({changePath:Ee,scriptPubkey:ke});yield T.dataLayer.saveAddress(_r({scriptPubkey:ke,redeemScript:Ke,path:Ee})),ue.add(Ge),Oe=yield T.dataLayer.lastUsedIndexByFormatPath(L),ye=Oe+T.pluginInfo.engineInfo.gapLimit,xe=T.dataLayer.numAddressesByFormatPath(L)}u0(T.taskCache,ue,L)})}}),u0=(T,B,L)=>{B.forEach(ue=>{T.addressSubscribeCache[ue]={path:L,processing:!1}})},Od=(T,B)=>Yr(void 0,null,function*(){var L;const{address:ue,changePath:be,addressForTransactionsCache:Oe}=B;let{blockHeight:ye}=B;const xe=T.walletTools.addressToScriptPubkey(ue);if(ye===0){const{lastQueriedBlockHeight:Ee=0}=(L=yield T.dataLayer.fetchAddress(xe))!=null?L:{};ye=Ee}Oe[ue]={processing:!1,path:be,page:1,blockHeight:ye}}),Bd=T=>T.pluginInfo.engineInfo.txSpecificHandling!=null;function qg(T,B){return Vo(this,null,function*(){const{addressForTransactionsCache:L,addressForUtxosCache:ue,addressSubscribeCache:be,blockbookUtxoCache:Oe,dataLayerUtxoCache:ye,transactionSpecificUpdateCache:xe,transactionUpdateCache:Ee}=T.taskCache,ke=T.serverStates.getServerState(B);if(ke==null)return!1;if(ke.blockSubscriptionStatus==="unsubscribed")return T.serverStates.watchBlocks(B),!0;if(Object.keys(ye).length>0){for(const[Ke,Ge]of Object.entries(ye))if(!Ge.processing&&Ge.full)return Ge.processing=!0,yield new Vr(Cd(T,{scriptPubkey:Ke,utxos:Ge.utxos})),en(ye,Ke),!0}for(const[Ke,Ge]of Object.entries(Oe)){const ft=Ge.blockbookUtxo;if(!Ge.processing){const ot=so(Ge.path,T.pluginInfo.engineInfo.scriptTemplates);if((ot===Mr.Airbitz||ot===Mr.Legacy||ot===Mr.ReplayProtection)&&!T.serverStates.serverCanGetTx(B,ft.txid))return!1;Ge.processing=!0,en(Oe,Ke),yield*Jn(Jg(T,{serverUri:B,cacheItem:Ge}))}}for(const[Ke,Ge]of Object.entries(ue))!Ge.processing&&T.serverStates.serverCanGetAddress(B,Ke)&&(Ge.processing=!0,en(ue,Ke),yield*Jn($g(T,{address:Ke,cacheItem:Ge,serverState:ke,serverUri:B})));if(Object.keys(be).length>0){const Ke=[],Ge=T.serverStates.getBlockHeight(B);for(const[ft,ot]of Object.entries(be)){const wt=!T.serverStates.serverIsAwareOfAddress(B,ft);wt&&Ke.push(ft),!ot.processing&&(wt&&(ue[ft]={processing:!1,path:ot.path}),yield new Vr(Od(T,{address:ft,changePath:ot.path,blockHeight:Ge,addressForTransactionsCache:L})),ot.processing=!0)}if(Ke.length>0)return T.serverStates.watchAddresses(B,Ke),!0}if(Object.keys(xe).length>0){let Ke=!1;for(const[Ge,ft]of Object.entries(xe))!ft.processing&&T.serverStates.serverCanGetTx(B,Ge)&&(Ke=!0,ft.processing=!0,en(xe,Ge),yield*Jn(Xg(T,{serverState:ke,serverUri:B,txId:Ge})));if(Ke)return!0}if(Object.keys(Ee).length>0){let Ke=!1;for(const[Ge,ft]of Object.entries(Ee))!ft.processing&&T.serverStates.serverCanGetTx(B,Ge)&&(Ke=!0,ft.processing=!0,en(Ee,Ge),yield*Jn(Yg(T,{serverState:ke,serverUri:B,txId:Ge})));if(Ke)return!0}for(const[Ke,Ge]of Object.entries(L))!Ge.processing&&T.serverStates.serverCanGetAddress(B,Ke)&&(Ge.processing=!0,en(L,Ke),yield*Jn(Zg(T,{address:Ke,cacheItem:Ge,serverState:ke,serverUri:B})));return!1})}function Xg(T,B){return Vo(this,null,function*(){const{serverState:L,serverUri:ue,txId:be}=B;try{const Oe=yield*Jn(T.serverStates.transactionSpecialQueryTask(ue,be));let xe=(yield new Vr(T.dataLayer.fetchTransactions({txId:be})))[0];if(xe==null)return!0;T.pluginInfo.engineInfo.txSpecificHandling!=null&&(xe=T.pluginInfo.engineInfo.txSpecificHandling(xe,Oe));const Ee=yield new Vr(T.dataLayer.saveTransaction({tx:xe})),ke=yield new Vr(ja({dataLayer:T.dataLayer,pluginInfo:T.pluginInfo,tx:Ee,walletId:T.walletInfo.id,walletTools:T.walletTools}));return T.emitter.emit(Hr.TRANSACTIONS,[{isNew:!1,transaction:ke}]),L.txids.add(be),!0}catch(Oe){return console.error(Oe),T.log("error while processing transaction specific update:",Oe),T.taskCache.transactionSpecificUpdateCache[be]={processing:!1},!1}})}function Yg(T,B){return Vo(this,null,function*(){const{serverState:L,serverUri:ue,txId:be}=B;try{const Oe=yield*Jn(T.serverStates.transactionQueryTask(ue,be));if(Oe.blockHeight<1)return!1;const ye=c0(T,{txResponse:Oe});for(const Ge of ye.inputs)yield new Vr(T.dataLayer.removeUtxos([`${Ge.txId}_${Ge.outputIndex}`]));const xe=ye.outputs.map(Ge=>`${ye.txid}_${Ge.n}`),Ee=yield new Vr(T.dataLayer.fetchUtxos({utxoIds:xe}));for(const Ge of Ee)Ge!=null&&(Ge.blockHeight=ye.blockHeight,yield new Vr(T.dataLayer.saveUtxo(Ge)));const ke=yield new Vr(T.dataLayer.saveTransaction({tx:ye})),Ke=yield new Vr(ja({dataLayer:T.dataLayer,pluginInfo:T.pluginInfo,tx:ke,walletId:T.walletInfo.id,walletTools:T.walletTools}));return T.emitter.emit(Hr.TRANSACTIONS,[{isNew:!1,transaction:Ke}]),Bd(T)&&(T.taskCache.transactionSpecificUpdateCache[be]={processing:!1}),L.txids.add(be),!0}catch(Oe){return console.error(Oe),T.log("error while processing transaction update:",Oe),T.taskCache.transactionUpdateCache[be]={processing:!1},!1}})}function Zg(T,B){return Vo(this,null,function*(){const{address:L,cacheItem:ue,serverState:be,serverUri:Oe}=B,{page:ye=1,blockHeight:xe}=ue,Ee=T.taskCache.addressForTransactionsCache,ke=T.walletTools.addressToScriptPubkey(L),Ke=yield new Vr(T.dataLayer.fetchAddress(ke));if(Ke==null)throw new Error(`could not find address with script pubkey ${ke}`);try{const Ge=yield*Jn(T.serverStates.addressQueryTask(Oe,L,{lastQueriedBlockHeight:Ke.lastQueriedBlockHeight,page:ye})),{transactions:ft=[],txs:ot,unconfirmedTxs:wt,totalPages:yt}=Ge,Bt=ot>0||wt>0;!Ke.used&&Bt&&ye===1&&(Ke.used=!0);const Gt=T.seenTxCheckpoint(),or=Gt!=null?parseInt(Gt):void 0;for(const pr of ft){const[jt]=yield new Vr(T.dataLayer.fetchTransactions({txId:pr.txid})),Lt=c0(T,{txResponse:pr}),vt=yield new Vr(T.dataLayer.saveTransaction({tx:Lt,scriptPubkeys:[ke]})),xt=yield new Vr(ja({dataLayer:T.dataLayer,pluginInfo:T.pluginInfo,tx:vt,walletId:T.walletInfo.id,walletTools:T.walletTools})),Ct=or!=null&&jt==null&&(Lt.blockHeight===0||Lt.blockHeight>or);T.emitter.emit(Hr.TRANSACTIONS,[{isNew:Ct,transaction:xt}]),xt.blockHeight>T.maxSeenTxBlockHeight&&(T.maxSeenTxBlockHeight=xt.blockHeight),Bd(T)&&(T.taskCache.transactionSpecificUpdateCache[Lt.txid]={processing:!1})}return T.updateSeenTxCheckpoint(),ye<yt?(Ee[L]=Di(Ni({},ue),{processing:!1,page:ye+1}),!0):(Ke.lastQueriedBlockHeight=xe,yield new Vr(T.dataLayer.saveAddress(Ke)),yield new Vr(T.updateProgressRatio()),yield new Vr(au(T)),be.addresses.add(L),!0)}catch(Ge){return console.error(Ge),T.log("error while processing address for transactions:",Ge),Ee[L]=Di(Ni({},ue),{processing:!1}),!1}})}const c0=(T,B)=>{const{txResponse:L}=B;let ue="0";const be=L.vout.map(ye=>{var xe;const Ee=(xe=ye.hex)!=null?xe:w(ke=>Xh(ke),"unknown")({address:ye.addresses[0],coin:T.pluginInfo.coinInfo.name});return ue=(0,ce.add)(ue,ye.value),{n:ye.n,scriptPubkey:Ee,amount:ye.value}}),Oe=L.vin.map(ye=>{if(!ye.isAddress)return{amount:ue,n:0,outputIndex:4294967295,scriptPubkey:"",sequence:ye.sequence,txId:"0000000000000000000000000000000000000000000000000000000000000000"};const xe=w(Ee=>Xh(Ee),"unknown")({address:ye.addresses[0],coin:T.pluginInfo.coinInfo.name});return{txId:ye.txid,outputIndex:ye.vout,n:ye.n,scriptPubkey:xe,sequence:ye.sequence,amount:ye.value}});return{txid:L.txid,hex:L.hex,blockHeight:L.blockHeight>0?L.blockHeight:0,date:L.blockTime,fees:L.fees,inputs:Oe,outputs:be,ourIns:[],ourOuts:[],ourAmount:"0"}};function $g(T,B){return Vo(this,null,function*(){const{address:L,cacheItem:ue,serverState:be,serverUri:Oe}=B,{addressForUtxosCache:ye,blockbookUtxoCache:xe,dataLayerUtxoCache:Ee}=T.taskCache;try{const ke=yield*Jn(T.serverStates.utxoListQueryTask(Oe,L)),Ke=T.walletTools.addressToScriptPubkey(L),Ge=yield new Vr(T.dataLayer.fetchAddress(Ke));if(Ge==null||Ge.path==null)return!0;if(ke.length===0)return Rd(Ee,ue.path,Ke,0),!0;for(const ft of ke){const ot=`${ft.txid}_${ft.vout}`;xe[ot]={blockbookUtxo:ft,processing:!1,requiredCount:ke.length,path:ue.path,address:Di(Ni({},Ge),{path:Ge.path})}}return be.addresses.add(L),!0}catch(ke){return console.error(ke),T.log("error while processing address for UTXOs:",ke),ye[L]=Di(Ni({},ue),{processing:!1}),!1}})}const Cd=(T,B)=>Yr(void 0,null,function*(){const{utxos:L,scriptPubkey:ue}=B,be=Object.fromEntries([...L].map(ke=>[ke.id,ke])),Oe=[],ye=yield T.dataLayer.fetchUtxos({scriptPubkey:ue});let xe="0";for(const ke of ye){if(ke==null)throw new Error("Unexpected undefined utxo when processing unspent transactions");ke.spent||(xe=(0,ce.add)(ke.value,xe)),be[ke.id]==null&&Oe.push(ke.id)}yield T.dataLayer.removeUtxos(Oe);let Ee="0";for(const ke of Object.values(be))ke.spent||(Ee=(0,ce.add)(ke.value,Ee)),yield T.dataLayer.saveUtxo(ke);if(Ee!==xe){T.log("address balance changed:",{scriptPubkey:ue,oldBalance:xe,newBalance:Ee}),T.emitter.emit(Hr.ADDRESS_BALANCE_CHANGED,T.pluginInfo.currencyInfo.currencyCode,[{scriptPubkey:ue,balance:Ee}]);const ke=yield T.dataLayer.fetchAddress(ue);if(ke==null)throw new Error("address not found when processing UTXO transactions");yield T.dataLayer.saveAddress(Di(Ni({},ke),{balance:Ee,used:!0}))}yield T.updateProgressRatio(),yield au(T).catch(ke=>{throw T.log.error(ke),ke})});function Jg(T,B){return Vo(this,null,function*(){const{serverUri:L,cacheItem:ue}=B,{blockbookUtxoCache:be,dataLayerUtxoCache:Oe}=T.taskCache,ye=so(ue.path,T.pluginInfo.engineInfo.scriptTemplates),xe=eu(ye);let Ee,ke;const Ke=()=>{var Ge;const ft={id:`${ue.blockbookUtxo.txid}_${ue.blockbookUtxo.vout}`,txid:ue.blockbookUtxo.txid,vout:ue.blockbookUtxo.vout,value:ue.blockbookUtxo.value,scriptPubkey:ue.address.scriptPubkey,script:Ee,redeemScript:ke,scriptType:xe,blockHeight:(Ge=ue.blockbookUtxo.height)!=null?Ge:-1,spent:!1};Rd(Oe,ue.path,ue.address.scriptPubkey,ue.requiredCount,ft)};switch(ye){case Mr.Airbitz:case Mr.Legacy:case Mr.ReplayProtection:ke=ue.address.redeemScript;{const[Ge]=yield new Vr(T.dataLayer.fetchTransactions({txId:ue.blockbookUtxo.txid}));if(Ge==null)try{const ft=yield*Jn(T.serverStates.transactionQueryTask(L,ue.blockbookUtxo.txid));return Ee=c0(T,{txResponse:ft}).hex,Ke(),!0}catch(ft){T.log("error while processing Blockbook UTXO:",ft);const ot=`${ue.blockbookUtxo.txid}_${ue.blockbookUtxo.vout}`;return be[ot]={blockbookUtxo:ue.blockbookUtxo,processing:!1,path:ue.path,address:ue.address,requiredCount:ue.requiredCount},!1}else Ee=Ge.hex}break;case Mr.WrappedSegwit:if(Ee=ue.address.scriptPubkey,ue.address.redeemScript==null)throw new Error("Address redeem script not defined, but required for p2sh wrapped segwit utxo processing");ke=ue.address.redeemScript;break;case Mr.Segwit:Ee=ue.address.scriptPubkey;break}return Ke(),!0})}const Rd=(T,B,L,ue,be)=>{var Oe;const ye=(Oe=T[L])!=null?Oe:{utxos:[],processing:!1,path:B,full:!1};be!=null&&ye.utxos.push(be),T[L]=ye,ye.full=ye.utxos.length>=ue};function Fd(T){const{pluginInfo:B,publicKey:L}=T,{engineInfo:ue}=B,{name:be}=B.coinInfo,Oe=L.publicKeys,ye={getPubkey(xe){var Ee;if(Oe[xe.format]==null)throw new Error(`wallet tools: xpub with format ${xe.format} does not exist`);return Sl({xpub:(Ee=Oe[xe.format])!=null?Ee:"",coin:be,type:Ci(xe.format),bip44ChangeIndex:xe.changeIndex,bip44AddressIndex:xe.addressIndex})},getScriptPubkey(xe){const Ee=so(xe,ue.scriptTemplates),ke=eu(Ee);return La({pubkey:ye.getPubkey(xe),scriptTemplates:ue.scriptTemplates,scriptType:ke})},getScriptPubkeyFromWif(xe,Ee){const ke=Ci(Ee),Ke=eu(ke),Ge=te({wifKey:xe,coin:be});[Mr.Segwit,Mr.WrappedSegwit].includes(ke)&&!Ge.compressed&&(Ge.compressed=!0);const ft=oe(Ge);return La({pubkey:ft,scriptTemplates:ue.scriptTemplates,scriptType:Ke})},getAddress(xe){const Ee=so(xe,B.engineInfo.scriptTemplates),{scriptPubkey:ke}=ye.getScriptPubkey(xe),Ke=a0(Ee);return io({scriptPubkey:ke,addressType:Ke,coin:be})},addressToScriptPubkey(xe){return li({address:xe,coin:be})},scriptPubkeyToAddress(xe){const{changePath:Ee}=xe,ke=so(Ee,B.engineInfo.scriptTemplates),Ke=a0(ke);return io({scriptPubkey:xe.scriptPubkey,addressType:Ke,coin:be})},getPrivateKey(xe){const{path:Ee,xprivKeys:ke}=xe,Ke=ke[Ee.format];if(Ke==null)throw new Error(`wallet tools: xpriv with format ${Ee.format} does not exist`);return O({xpriv:Ke,type:Ci(Ee.format),coin:be,bip44ChangeIndex:Ee.changeIndex,bip44AddressIndex:Ee.addressIndex})},getPrivateKeyEncodingFromWif(xe){return te({wifKey:xe,coin:be})},getScriptAddress({path:xe,scriptTemplate:Ee}){const ke=ye.getPubkey(xe),Ke=Ee(ke),{address:Ge,scriptPubkey:ft,redeemScript:ot}=oo({coin:be,scriptPubkey:Ke});if(Ge==null)throw new Error("Failed to derive address for script");return{address:Ge,scriptPubkey:ft,redeemScript:ot}},signMessageBase64({path:xe,message:Ee,xprivKeys:ke}){const Ke=ye.getPrivateKey({path:xe,xprivKeys:ke});return he(Ee,Ke)}};return ye}var Nd=$t(8287).Buffer,Qg=Object.defineProperty,em=Object.defineProperties,tm=Object.getOwnPropertyDescriptors,Dd=Object.getOwnPropertySymbols,rm=Object.prototype.hasOwnProperty,nm=Object.prototype.propertyIsEnumerable,Ld=(T,B,L)=>B in T?Qg(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,Li=(T,B)=>{for(var L in B||(B={}))rm.call(B,L)&&Ld(T,L,B[L]);if(Dd)for(var L of Dd(B))nm.call(B,L)&&Ld(T,L,B[L]);return T},Ui=(T,B)=>em(T,tm(B)),Br=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())});function im(T){return Br(this,null,function*(){const{pluginInfo:B,pluginDisklet:L,emitter:ue,engineOptions:be,io:Oe,pluginState:ye}=T,{walletLocalDisklet:xe,walletLocalEncryptedDisklet:Ee,log:ke}=be,{currencyInfo:Ke,engineInfo:Ge,coinInfo:ft}=B,ot=Ua(be.userSettings);ye.updateServers(ot).catch(gt=>{ke.error(gt)});const wt=n0(ft.name,ft.coinType),yt=w(wt),Bt=Gh(B)(T.walletInfo),{privateKeyFormat:Gt,publicKey:or,walletFormats:pr}=Bt.keys;if(!Ge.formats.includes(Gt)){const gt=`Wallet format is not supported: ${Gt}`;throw ke.error(gt),new Error(gt)}const jt=Fd({pluginInfo:B,publicKey:or}),Lt=yield cp({disklet:L,pluginInfo:B,io:Oe,log:T.engineOptions.log}),vt=yield Ph({disklet:xe,emitter:ue,log:ke}),xt=yield Hh({disklet:xe});let Ct;const _t=(gt=>Rt=>(Rt!=null&&(gt=Rt),gt))();_t(T.engineOptions.seenTxCheckpoint),ue.on(Hr.SEEN_TX_CHECKPOINT,gt=>{_t(gt)});const kt=Td(Ui(Li({},T),{dataLayer:xt,pluginState:ye,seenTxCheckpoint:_t,walletTools:jt,walletInfo:Bt})),Nt={accelerate(gt){return Br(this,null,function*(){var Rt;const{canReplaceByFee:Zt=!1}=Ke;if(!Zt||Gt==="bip32"||Gt==="bip44")return null;const Vt=gt.txid,[nr]=yield xt.fetchTransactions({txId:Vt});if(nr==null||nr.inputs.every(Nr=>Nr.sequence>4294967293)||nr.blockHeight!==0)return null;const qt=To(nr.hex),ir=Math.round(parseInt(nr.fees)/qt*2),fr=nr.inputs,kr=yield Promise.all(fr.map((Nr,Wr)=>Br(this,null,function*(){const Qn=yield gv(xt,nr,Wr);return Qn.spent=!1,Qn}))),Cr=kr.reduce((Nr,Wr)=>Wr.value>Nr.value?Wr:Nr),Kr=[],Zr=[];let Fr;for(const Nr of nr.outputs){const Wr=yield xt.fetchAddress(Nr.scriptPubkey);if(Wr==null){Kr.push({scriptPubkey:Nr.scriptPubkey,value:parseInt(Nr.amount)});continue}if(Wr.path==null)throw new Error("Expecting path for address");const Qn=so(Wr.path,Ge.scriptTemplates),ho=a0(Qn),{address:yn}=io({scriptPubkey:Wr.scriptPubkey,addressType:ho,coin:ft.name,redeemScript:Wr.redeemScript});Zr.push(yn),Wr.path.changeIndex===1?Fr=yn:Kr.push({scriptPubkey:Nr.scriptPubkey,value:parseInt(Nr.amount)})}const jr=Fr==null?yield kt.getFreshAddress({branch:1}):{publicAddress:Fr},Cn=(Rt=jr.segwitAddress)!=null?Rt:jr.publicAddress,Hi=Al(yield xt.fetchUtxos({utxoIds:[]})).filter(Nr=>Nr.txid!==Vt),Sn={utxos:[...kr,...Hi],forceUseUtxo:[Cr],targets:Kr,memos:gt.memos,feeRate:ir,coin:ft.name,currencyCode:Ke.currencyCode,enableRbf:!0,freshChangeAddress:Cn,subtractFee:!1,log:ke,outputSort:"bip69"},on=(()=>{try{return Ae(Sn)}catch(Nr){const Wr=ul(Nr);if((Wr==null?void 0:Wr.networkFeeShortage)!=null){let Qn=parseInt(Wr.networkFeeShortage);for(const ho of Kr){if(ho.value==null)continue;const yn=Math.min(ho.value,Qn);ho.value-=yn,Qn-=yn}return Ae(Sn)}throw Nr}})();on.changeUsed&&Zr.push(Cn);const kn=on.inputs.map(Nr=>Nr.scriptPubkey.toString("hex"));let hn="0";for(const Nr of on.outputs){const Wr=Nr.scriptPubkey.toString("hex");(yield xt.fetchAddress(Wr))==null?hn=ce.sub(hn,Nr.value.toString()):kn.push(Wr)}const zi=on.fee.toString();hn=ce.sub(hn,zi);const Zo={unsignedTx:on.hex,psbt:{base64:on.psbtBase64,inputs:on.inputs,outputs:on.outputs},ourScriptPubkeys:kn,replacedTxid:Vt};return Ui(Li({},gt),{blockHeight:0,currencyCode:Ke.currencyCode,date:za(),feeRateUsed:{satPerVByte:ir},isSend:!0,nativeAmount:hn,networkFee:zi,otherParams:Zo,ourReceiveAddresses:Zr,parentNetworkFee:void 0,signedTx:"",txid:"",walletId:Bt.id})})},startEngine(){return Br(this,null,function*(){ue.emit(Hr.WALLET_BALANCE_CHANGED,Ke.currencyCode,vt.state.balance),ye.addEngine(kt),yield Lt.start(),yield kt.start()})},killEngine(){return Br(this,null,function*(){yield kt.stop(),Lt.stop(),ye.removeEngine(kt)})},getBalance(gt){return vt.state.balance},getBlockHeight(){return vt.state.lastSeenBlockHeight},addCustomToken(gt){return Br(this,null,function*(){return yield Promise.resolve(void 0)})},addGapLimitAddresses(gt){return Br(this,null,function*(){return yield kt.addGapLimitAddresses(gt)})},broadcastTx(gt){return Br(this,null,function*(){var Rt,Zt;const{otherParams:Vt}=gt;if(((Rt=Vt==null?void 0:Vt.paymentProtocolInfo)==null?void 0:Rt.payment)!=null&&((Zt=Vt==null?void 0:Vt.paymentProtocolInfo)==null?void 0:Zt.paymentUrl)!=null&&typeof(yield xv(Oe.fetch,Vt.paymentProtocolInfo.paymentUrl,Vt.paymentProtocolInfo.payment))>"u")throw new Error(`Error when sending to ${Vt.paymentProtocolInfo.paymentUrl}`);if((yield kt.broadcastTx(gt).catch(qt=>{throw String(qt).includes("Error: Blockbook Error: -26: dust")?new $d:qt}))!==gt.txid)throw new Error("broadcast response txid does not match original");return gt})},changeUserSettings(gt){return Br(this,null,function*(){yield ye.updateServers(Ua(gt))})},disableTokens(gt){return Br(this,null,function*(){return yield Promise.resolve(void 0)})},dumpData(){return Br(this,null,function*(){return{walletId:Bt.id.split(" - ")[0],walletType:Bt.type,data:{walletInfo:{pluginType:Ke.pluginId,privateKeyFormat:Gt,walletFormats:pr},metadataState:vt.state,storageState:yield xt.dumpData(),pluginState:ye.dumpData()}}})},enableTokens(gt){return Br(this,null,function*(){return yield Promise.resolve(void 0)})},getDisplayPrivateSeed(gt){const Rt=yt(gt);return Rt==null?null:Rt.format==="bip32"?Nd.from(Rt.seed,"base64").toString("hex"):Rt.seed},getDisplayPublicSeed(){const gt=or.publicKeys;return Object.values(gt).filter(Rt=>Rt!=null).join(`
|
|
77
|
+
${qt}`),Ct(nr)}})}})})},getBlockHeight(vt){return ke[vt].blockHeight},getServerList(){return Ge},getServerState(vt){return ke[vt]},refillServers(){be("refilling servers..."),Ke=!0,pd({id:xe.id,updateFunc:()=>{or()}})},setPickNextTaskCB(vt){yt=vt},setServerList(vt){Ge=vt},serverCanGetTx(vt,xt){const Ct=ke[vt];if(Ct==null)return!1;if(Ct.txids.has(xt))return!0;for(const _t of Object.values(ke))if(_t.txids.has(xt))return!1;return!0},serverCanGetAddress(vt,xt){const Ct=ke[vt];if(Ct==null)return!1;if(Ct.addresses.has(xt))return!0;for(const _t of Object.values(ke))if(_t.addresses.has(xt))return!1;return!0},serverIsAwareOfAddress(vt,xt){const Ct=ke[vt];return Ct==null?!1:!!Ct.addresses.has(xt)},stop(){return iu(this,null,function*(){Ke=!1,be("stopping server states"),vd(xe.id),clearTimeout(ot);for(const vt of Object.keys(ke)){const xt=ke[vt],{blockbook:Ct}=xt;Ct!=null&&(yield Ct.disconnect(),en(ke,vt))}})},watchAddresses(vt,xt,Ct){const _t=ke[vt];if(_t==null)throw new Error(`No blockbook connection with ${vt}`);const{blockbook:kt}=_t;for(const gt of xt)_t.addresses.add(gt);const Nt=new tu;Nt.promise.catch(gt=>{for(const Rt of xt)_t.addresses.delete(Rt);Ct==null||Ct.reject(gt)}),kt.watchAddresses(Array.from(_t.addresses),pr(vt,Nt))},watchBlocks(vt){const xt=ke[vt];if(xt==null)throw new Error(`No blockbook connection with ${vt}`);const{blockbook:Ct}=xt;xt.blockSubscriptionStatus="subscribing";const _t=new tu;_t.promise.then(()=>{xt.blockSubscriptionStatus="subscribed"}).catch(()=>{xt.blockSubscriptionStatus="unsubscribed"}),Ct.watchBlocks(pr(vt,_t))},addressQueryTask:function*(vt,xt,Ct){const _t=ke[vt];if(_t==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return yield*Fi(_t.blockbook.addressQueryTask(xt,{asBlockbookAddress:Oe.engineInfo.asBlockbookAddress,lastQueriedBlockHeight:Ct.lastQueriedBlockHeight,page:Ct.page}))}()))},transactionQueryTask:function*(vt,xt){const Ct=ke[vt];if(Ct==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return yield*Fi(Ct.blockbook.transactionQueryTask(xt))}()))},transactionSpecialQueryTask:function*(vt,xt){const Ct=ke[vt];if(Ct==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return Ct.blockbook.transactionSpecialQueryTask(xt)}()))},utxoListQueryTask:function*(vt,xt){const Ct=ke[vt];if(Ct==null)throw new Error(`No blockbook connection with ${vt}`);return yield*Fi(jt(vt,function*(){return yield*Fi(Ct.blockbook.utxoListQueryTask(xt,{asBlockbookAddress:Oe.engineInfo.asBlockbookAddress}))}()))}};return Lt}var zg=Object.defineProperty,Kg=Object.defineProperties,jg=Object.getOwnPropertyDescriptors,_d=Object.getOwnPropertySymbols,Wg=Object.prototype.hasOwnProperty,Gg=Object.prototype.propertyIsEnumerable,ou=(T,B)=>(B=Symbol[T])?B:Symbol.for("Symbol."+T),Ad=(T,B,L)=>B in T?zg(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,Ni=(T,B)=>{for(var L in B||(B={}))Wg.call(B,L)&&Ad(T,L,B[L]);if(_d)for(var L of _d(B))Gg.call(B,L)&&Ad(T,L,B[L]);return T},Di=(T,B)=>Kg(T,jg(B)),Yr=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())}),Vr=function(T,B){this[0]=T,this[1]=B},Vo=(T,B,L)=>{var ue=(ye,xe,Ee,ke)=>{try{var Ke=L[ye](xe),Ge=(xe=Ke.value)instanceof Vr,ft=Ke.done;Promise.resolve(Ge?xe[0]:xe).then(ot=>Ge?ue(ye==="return"?ye:"next",xe[1]?{done:ot.done,value:ot.value}:ot,Ee,ke):Ee({value:ot,done:ft})).catch(ot=>ue("throw",ot,Ee,ke))}catch(ot){ke(ot)}},be=ye=>Oe[ye]=xe=>new Promise((Ee,ke)=>ue(ye,xe,Ee,ke)),Oe={};return L=L.apply(T,B),Oe[ou("asyncIterator")]=()=>Oe,be("next"),be("throw"),be("return"),Oe},Jn=T=>{var B=T[ou("asyncIterator")],L=!1,ue,be={};return B==null?(B=T[ou("iterator")](),ue=Oe=>be[Oe]=ye=>B[Oe](ye)):(B=B.call(T),ue=Oe=>be[Oe]=ye=>{if(L){if(L=!1,Oe==="throw")throw ye;return ye}return L=!0,{done:!1,value:new Vr(new Promise(xe=>{var Ee=B[Oe](ye);if(!(Ee instanceof Object))throw TypeError("Object expected");xe(Ee)}),1)}}),be[ou("iterator")]=()=>be,ue("next"),"throw"in B?ue("throw"):be.throw=Oe=>{throw Oe},"return"in B&&ue("return"),be};function Td(T){const{dataLayer:B,initOptions:L,io:ue,emitter:be,engineOptions:Oe,pluginState:ye,pluginInfo:xe,seenTxCheckpoint:Ee,walletInfo:ke,walletTools:Ke}=T,{log:Ge}=Oe,{walletFormats:ft}=ke.keys,ot={addressForTransactionsCache:{},addressForUtxosCache:{},addressSubscribeCache:{},blockbookUtxoCache:{},dataLayerUtxoCache:{},transactionSpecificUpdateCache:{},transactionUpdateCache:{}},wt=()=>{for(const kt of Object.keys(ot.addressForTransactionsCache))en(ot.addressForTransactionsCache,kt);for(const kt of Object.keys(ot.addressForUtxosCache))en(ot.addressForUtxosCache,kt);for(const kt of Object.keys(ot.addressSubscribeCache))en(ot.addressSubscribeCache,kt);for(const kt of Object.keys(ot.blockbookUtxoCache))en(ot.blockbookUtxoCache,kt);for(const kt of Object.keys(ot.dataLayerUtxoCache))en(ot.dataLayerUtxoCache,kt);for(const kt of Object.keys(ot.transactionSpecificUpdateCache))en(ot.transactionSpecificUpdateCache,kt);for(const kt of Object.keys(ot.transactionUpdateCache))en(ot.transactionUpdateCache,kt)},yt=2;let Bt=0,Gt=0;const or=()=>Yr(this,null,function*(){if(Gt>=1)return;const kt=Object.keys(ot.addressSubscribeCache).length*yt;if(Bt=Bt+1,kt===0)throw new Error("No addresses to process");const Nt=Bt/kt;(Nt-Gt>Bv||Nt===1)&&(Ge(`processed changed, percent: ${Nt}, processedCount: ${Bt}, totalCount: ${kt}`),Gt=Nt,vt.updateSeenTxCheckpoint(),be.emit(Hr.ADDRESSES_CHECKED,Nt))}),pr=()=>{if(Gt<1)return;const kt=vt.seenTxCheckpoint(),Nt=kt!=null?parseInt(kt):void 0;if(Nt==null||vt.maxSeenTxBlockHeight>Nt){const gt=vt.maxSeenTxBlockHeight.toString();vt.emitter.emit(Hr.SEEN_TX_CHECKPOINT,gt)}},jt=new Th,Lt=Hg({engineEmitter:be,initOptions:L,io:ue,log:Ge,pluginInfo:xe,pluginState:ye,walletInfo:ke}),vt={pluginInfo:xe,walletInfo:ke,walletTools:Ke,dataLayer:B,emitter:be,taskCache:ot,updateProgressRatio:or,updateSeenTxCheckpoint:pr,io:ue,log:Ge,maxSeenTxBlockHeight:0,seenTxCheckpoint:Ee,serverStates:Lt,walletFormats:ft,lock:jt};Lt.setPickNextTaskCB(kt=>qg(vt,kt));let xt=!1;const Ct=()=>Yr(this,null,function*(){xt||(xt=!0,yield _t(),yield au(vt))});be.on(Hr.BLOCK_HEIGHT_CHANGED,(kt,Nt)=>Yr(this,null,function*(){const gt=yield B.fetchTransactions({blockHeight:0});for(const Rt of gt)Rt!=null&&(ot.transactionUpdateCache[Rt.txid]={processing:!1})})),be.on(Hr.NEW_ADDRESS_TRANSACTION,(kt,Nt)=>Yr(this,null,function*(){const gt=ot.addressSubscribeCache[Nt.address];if(gt!=null){const{path:Rt}=gt;ot.addressForUtxosCache[Nt.address]={processing:!1,path:Rt},Od(vt,{address:Nt.address,changePath:Rt,blockHeight:0,addressForTransactionsCache:ot.addressForTransactionsCache}).catch(()=>{throw new Error("failed to add to transaction cache")}),au(vt).catch(Zt=>{Ge(Zt)})}}));const _t=()=>Yr(this,null,function*(){const kt=[];for(const Nt of ft){const gt=Yh(xe.engineInfo,Nt);for(const Rt of gt){const Zt=new Set,Vt={format:Nt,changeIndex:Rt},nr=B.numAddressesByFormatPath(Vt);for(let qt=0;qt<nr;qt++){const ir=yield B.fetchAddress({format:Nt,changeIndex:Rt,addressIndex:qt});if(ir==null)throw new Error(`Missing data-layer address with '${Nt}/${Rt}/${qt}' path during initialization`);const{address:fr}=Ke.scriptPubkeyToAddress({changePath:Vt,scriptPubkey:ir.scriptPubkey});Zt.add(fr),ir.balance!=null&&kt.push({scriptPubkey:ir.scriptPubkey,balance:ir.balance})}u0(vt.taskCache,Zt,{format:Nt,changeIndex:Rt})}}be.emit(Hr.ADDRESS_BALANCE_CHANGED,xe.currencyInfo.currencyCode,kt)});return{processedPercent:Gt,start(){return Yr(this,null,function*(){Bt=0,Gt=0,yield Ct(),Lt.refillServers()})},stop(){return Yr(this,null,function*(){Lt.stop(),wt(),xt=!1})},getFreshAddress(kt){return Yr(this,arguments,function*({branch:Nt=0,forceIndex:gt}){const{privateKeyFormat:Rt}=ke.keys;Rt==="bip32"&&(Nt=0);const{address:Zt,nativeBalance:Vt="0",legacyAddress:nr}=yield Pd(vt,{forceIndex:gt,changePath:{format:Rt,changeIndex:Nt}}),qt={publicAddress:Zt,nativeBalance:Vt,legacyAddress:nr!==Zt?nr:void 0,legacyNativeBalance:nr!==Zt?Vt:void 0},ir=Jf(xe.engineInfo,ke.keys.privateKeyFormat).filter(fr=>fr!==Rt);for(const fr of ir)if(fr==="bip84"){const{address:kr,nativeBalance:Cr="0"}=yield Pd(vt,{forceIndex:gt,changePath:{format:fr,changeIndex:Nt}});qt.segwitAddress=kr,qt.segwitNativeBalance=Cr}return qt})},deriveScriptAddress(kt){return Yr(this,null,function*(){const{address:Nt}=yield Vg({walletTools:vt.walletTools,engineInfo:vt.pluginInfo.engineInfo,dataLayer:vt.dataLayer,taskCache:vt.taskCache,format:ke.keys.privateKeyFormat,script:kt});return{publicAddress:Nt}})},addGapLimitAddresses(kt){return Yr(this,null,function*(){const Nt=kt.map(gt=>Yr(this,null,function*(){const Rt=Ke.addressToScriptPubkey(gt);yield B.saveAddress(_r({scriptPubkey:Rt,used:!0}))}));yield Promise.all(Nt),yield Ct()})},broadcastTx(kt){return Yr(this,null,function*(){return yield Lt.broadcastTx(kt)})},refillServers(){Lt.refillServers()},getServerList(){return Lt.getServerList()},setServerList(kt){Lt.setServerList(kt)},loadWifs(kt){return Yr(this,null,function*(){for(const Nt of kt)for(const gt of ft){const Rt={format:gt,changeIndex:0},Zt=Di(Ni({},Rt),{addressIndex:0}),{scriptPubkey:Vt,redeemScript:nr}=Ke.getScriptPubkeyFromWif(Nt,gt),{address:qt}=Ke.scriptPubkeyToAddress({changePath:Zt,scriptPubkey:Vt});yield B.saveAddress(_r({scriptPubkey:Vt,redeemScript:nr,path:Zt})),ot.addressSubscribeCache[qt]={path:Rt,processing:!1}}})},processUtxos(kt){return Yr(this,null,function*(){var Nt;const gt=new Map,Rt=new Set;for(const Zt of kt){const Vt=(Nt=gt.get(Zt.scriptPubkey))!=null?Nt:[];gt.has(Zt.scriptPubkey)||gt.set(Zt.scriptPubkey,Vt),Vt.push(Zt),Rt.add(Zt.id)}for(const[Zt,Vt]of gt.entries()){const ir=[...(yield B.fetchUtxos({scriptPubkey:Zt})).filter(fr=>fr!=null&&!Rt.has(fr==null?void 0:fr.id)),...Vt];yield Cd(vt,{scriptPubkey:Zt,utxos:ir})}})}}}const Vg=T=>Yr(void 0,null,function*(){const{walletTools:B,engineInfo:L,dataLayer:ue,format:be,taskCache:Oe,script:ye}=T;if(L.scriptTemplates==null)throw new Error(`cannot derive script address ${ye} without defined script template`);const xe=L.scriptTemplates[ye],Ee={format:be,changeIndex:Da(xe),addressIndex:0},{address:ke,scriptPubkey:Ke,redeemScript:Ge}=B.getScriptAddress({path:Ee,scriptTemplate:xe});yield ue.saveAddress(_r({scriptPubkey:Ke,redeemScript:Ge,path:Ee}));const ft=new Set;return ft.add(ke),u0(Oe,ft,{format:Ee.format,changeIndex:Ee.changeIndex}),{address:ke,scriptPubkey:Ke,redeemScript:Ge}}),Pd=(T,B)=>Yr(void 0,null,function*(){var L;const{changePath:ue,forceIndex:be}=B,Oe=T.dataLayer.numAddressesByFormatPath(ue),ye={format:ue.format,changeIndex:ue.changeIndex,addressIndex:Math.max(Oe-T.pluginInfo.engineInfo.gapLimit,0)};be!=null&&(ye.addressIndex=be);const xe=yield T.dataLayer.fetchAddress(ye),Ee=(L=xe==null?void 0:xe.balance)!=null?L:"0",{scriptPubkey:ke}=xe!=null?xe:yield T.walletTools.getScriptPubkey(ye);if(ke==null)throw new Error("Unknown address path");const Ke=T.walletTools.scriptPubkeyToAddress({changePath:ye,scriptPubkey:ke});return Di(Ni({},Ke),{nativeBalance:Ee})}),au=T=>Yr(void 0,null,function*(){yield T.lock.acquireAsync();try{for(const L of T.walletFormats){const ue=Yh(T.pluginInfo.engineInfo,L);for(const be of ue)yield B({format:L,changeIndex:be})}}finally{T.lock.release()}function B(L){return Yr(this,null,function*(){const ue=new Set,be=T.dataLayer.numAddressesByFormatPath(L);let Oe=yield T.dataLayer.lastUsedIndexByFormatPath(L),ye=Oe+T.pluginInfo.engineInfo.gapLimit,xe=be;for(;xe<=ye;){const Ee=Di(Ni({},L),{addressIndex:xe}),{scriptPubkey:ke,redeemScript:Ke}=T.walletTools.getScriptPubkey(Ee),{address:Ge}=T.walletTools.scriptPubkeyToAddress({changePath:Ee,scriptPubkey:ke});yield T.dataLayer.saveAddress(_r({scriptPubkey:ke,redeemScript:Ke,path:Ee})),ue.add(Ge),Oe=yield T.dataLayer.lastUsedIndexByFormatPath(L),ye=Oe+T.pluginInfo.engineInfo.gapLimit,xe=T.dataLayer.numAddressesByFormatPath(L)}u0(T.taskCache,ue,L)})}}),u0=(T,B,L)=>{B.forEach(ue=>{T.addressSubscribeCache[ue]={path:L,processing:!1}})},Od=(T,B)=>Yr(void 0,null,function*(){var L;const{address:ue,changePath:be,addressForTransactionsCache:Oe}=B;let{blockHeight:ye}=B;const xe=T.walletTools.addressToScriptPubkey(ue);if(ye===0){const{lastQueriedBlockHeight:Ee=0}=(L=yield T.dataLayer.fetchAddress(xe))!=null?L:{};ye=Ee}Oe[ue]={processing:!1,path:be,page:1,blockHeight:ye}}),Bd=T=>T.pluginInfo.engineInfo.txSpecificHandling!=null;function qg(T,B){return Vo(this,null,function*(){const{addressForTransactionsCache:L,addressForUtxosCache:ue,addressSubscribeCache:be,blockbookUtxoCache:Oe,dataLayerUtxoCache:ye,transactionSpecificUpdateCache:xe,transactionUpdateCache:Ee}=T.taskCache,ke=T.serverStates.getServerState(B);if(ke==null)return!1;if(ke.blockSubscriptionStatus==="unsubscribed")return T.serverStates.watchBlocks(B),!0;if(Object.keys(ye).length>0){for(const[Ke,Ge]of Object.entries(ye))if(!Ge.processing&&Ge.full)return Ge.processing=!0,yield new Vr(Cd(T,{scriptPubkey:Ke,utxos:Ge.utxos})),en(ye,Ke),!0}for(const[Ke,Ge]of Object.entries(Oe)){const ft=Ge.blockbookUtxo;if(!Ge.processing){const ot=so(Ge.path,T.pluginInfo.engineInfo.scriptTemplates);if((ot===Mr.Airbitz||ot===Mr.Legacy||ot===Mr.ReplayProtection)&&!T.serverStates.serverCanGetTx(B,ft.txid))return!1;Ge.processing=!0,en(Oe,Ke),yield*Jn(Jg(T,{serverUri:B,cacheItem:Ge}))}}for(const[Ke,Ge]of Object.entries(ue))!Ge.processing&&T.serverStates.serverCanGetAddress(B,Ke)&&(Ge.processing=!0,en(ue,Ke),yield*Jn($g(T,{address:Ke,cacheItem:Ge,serverState:ke,serverUri:B})));if(Object.keys(be).length>0){const Ke=[],Ge=T.serverStates.getBlockHeight(B);for(const[ft,ot]of Object.entries(be)){const wt=!T.serverStates.serverIsAwareOfAddress(B,ft);wt&&Ke.push(ft),!ot.processing&&(wt&&(ue[ft]={processing:!1,path:ot.path}),yield new Vr(Od(T,{address:ft,changePath:ot.path,blockHeight:Ge,addressForTransactionsCache:L})),ot.processing=!0)}if(Ke.length>0)return T.serverStates.watchAddresses(B,Ke),!0}if(Object.keys(xe).length>0){let Ke=!1;for(const[Ge,ft]of Object.entries(xe))!ft.processing&&T.serverStates.serverCanGetTx(B,Ge)&&(Ke=!0,ft.processing=!0,en(xe,Ge),yield*Jn(Xg(T,{serverState:ke,serverUri:B,txId:Ge})));if(Ke)return!0}if(Object.keys(Ee).length>0){let Ke=!1;for(const[Ge,ft]of Object.entries(Ee))!ft.processing&&T.serverStates.serverCanGetTx(B,Ge)&&(Ke=!0,ft.processing=!0,en(Ee,Ge),yield*Jn(Yg(T,{serverState:ke,serverUri:B,txId:Ge})));if(Ke)return!0}for(const[Ke,Ge]of Object.entries(L))!Ge.processing&&T.serverStates.serverCanGetAddress(B,Ke)&&(Ge.processing=!0,en(L,Ke),yield*Jn(Zg(T,{address:Ke,cacheItem:Ge,serverState:ke,serverUri:B})));return!1})}function Xg(T,B){return Vo(this,null,function*(){const{serverState:L,serverUri:ue,txId:be}=B;try{const Oe=yield*Jn(T.serverStates.transactionSpecialQueryTask(ue,be));let xe=(yield new Vr(T.dataLayer.fetchTransactions({txId:be})))[0];if(xe==null)return!0;T.pluginInfo.engineInfo.txSpecificHandling!=null&&(xe=T.pluginInfo.engineInfo.txSpecificHandling(xe,Oe));const Ee=yield new Vr(T.dataLayer.saveTransaction({tx:xe})),ke=yield new Vr(ja({dataLayer:T.dataLayer,pluginInfo:T.pluginInfo,tx:Ee,walletId:T.walletInfo.id,walletTools:T.walletTools}));return T.emitter.emit(Hr.TRANSACTIONS,[{isNew:!1,transaction:ke}]),L.txids.add(be),!0}catch(Oe){return console.error(Oe),T.log("error while processing transaction specific update:",Oe),T.taskCache.transactionSpecificUpdateCache[be]={processing:!1},!1}})}function Yg(T,B){return Vo(this,null,function*(){const{serverState:L,serverUri:ue,txId:be}=B;try{const Oe=yield*Jn(T.serverStates.transactionQueryTask(ue,be));if(Oe.blockHeight<1)return!1;const ye=c0(T,{txResponse:Oe});for(const Ge of ye.inputs)yield new Vr(T.dataLayer.removeUtxos([`${Ge.txId}_${Ge.outputIndex}`]));const xe=ye.outputs.map(Ge=>`${ye.txid}_${Ge.n}`),Ee=yield new Vr(T.dataLayer.fetchUtxos({utxoIds:xe}));for(const Ge of Ee)Ge!=null&&(Ge.blockHeight=ye.blockHeight,yield new Vr(T.dataLayer.saveUtxo(Ge)));const ke=yield new Vr(T.dataLayer.saveTransaction({tx:ye})),Ke=yield new Vr(ja({dataLayer:T.dataLayer,pluginInfo:T.pluginInfo,tx:ke,walletId:T.walletInfo.id,walletTools:T.walletTools}));return T.emitter.emit(Hr.TRANSACTIONS,[{isNew:!1,transaction:Ke}]),Bd(T)&&(T.taskCache.transactionSpecificUpdateCache[be]={processing:!1}),L.txids.add(be),!0}catch(Oe){return console.error(Oe),T.log("error while processing transaction update:",Oe),T.taskCache.transactionUpdateCache[be]={processing:!1},!1}})}function Zg(T,B){return Vo(this,null,function*(){const{address:L,cacheItem:ue,serverState:be,serverUri:Oe}=B,{page:ye=1,blockHeight:xe}=ue,Ee=T.taskCache.addressForTransactionsCache,ke=T.walletTools.addressToScriptPubkey(L),Ke=yield new Vr(T.dataLayer.fetchAddress(ke));if(Ke==null)throw new Error(`could not find address with script pubkey ${ke}`);try{const Ge=yield*Jn(T.serverStates.addressQueryTask(Oe,L,{lastQueriedBlockHeight:Ke.lastQueriedBlockHeight,page:ye})),{transactions:ft=[],txs:ot,unconfirmedTxs:wt,totalPages:yt}=Ge,Bt=ot>0||wt>0;!Ke.used&&Bt&&ye===1&&(Ke.used=!0);const Gt=T.seenTxCheckpoint(),or=Gt!=null?parseInt(Gt):void 0;for(const pr of ft){const[jt]=yield new Vr(T.dataLayer.fetchTransactions({txId:pr.txid})),Lt=c0(T,{txResponse:pr}),vt=yield new Vr(T.dataLayer.saveTransaction({tx:Lt,scriptPubkeys:[ke]})),xt=yield new Vr(ja({dataLayer:T.dataLayer,pluginInfo:T.pluginInfo,tx:vt,walletId:T.walletInfo.id,walletTools:T.walletTools})),Ct=or!=null&&jt==null&&(Lt.blockHeight===0||Lt.blockHeight>or);T.emitter.emit(Hr.TRANSACTIONS,[{isNew:Ct,transaction:xt}]),xt.blockHeight>T.maxSeenTxBlockHeight&&(T.maxSeenTxBlockHeight=xt.blockHeight),Bd(T)&&(T.taskCache.transactionSpecificUpdateCache[Lt.txid]={processing:!1})}return T.updateSeenTxCheckpoint(),ye<yt?(Ee[L]=Di(Ni({},ue),{processing:!1,page:ye+1}),!0):(Ke.lastQueriedBlockHeight=xe,yield new Vr(T.dataLayer.saveAddress(Ke)),yield new Vr(T.updateProgressRatio()),yield new Vr(au(T)),be.addresses.add(L),!0)}catch(Ge){return console.error(Ge),T.log("error while processing address for transactions:",Ge),Ee[L]=Di(Ni({},ue),{processing:!1}),!1}})}const c0=(T,B)=>{const{txResponse:L}=B;let ue="0";const be=L.vout.map(ye=>{var xe;const Ee=(xe=ye.hex)!=null?xe:w(ke=>Xh(ke),"unknown")({address:ye.addresses[0],coin:T.pluginInfo.coinInfo.name});return ue=(0,ce.add)(ue,ye.value),{n:ye.n,scriptPubkey:Ee,amount:ye.value}}),Oe=L.vin.map(ye=>{if(!ye.isAddress)return{amount:ue,n:0,outputIndex:4294967295,scriptPubkey:"",sequence:ye.sequence,txId:"0000000000000000000000000000000000000000000000000000000000000000"};const xe=w(Ee=>Xh(Ee),"unknown")({address:ye.addresses[0],coin:T.pluginInfo.coinInfo.name});return{txId:ye.txid,outputIndex:ye.vout,n:ye.n,scriptPubkey:xe,sequence:ye.sequence,amount:ye.value}});return{txid:L.txid,hex:L.hex,blockHeight:L.blockHeight>0?L.blockHeight:0,date:L.blockTime,fees:L.fees,inputs:Oe,outputs:be,ourIns:[],ourOuts:[],ourAmount:"0"}};function $g(T,B){return Vo(this,null,function*(){const{address:L,cacheItem:ue,serverState:be,serverUri:Oe}=B,{addressForUtxosCache:ye,blockbookUtxoCache:xe,dataLayerUtxoCache:Ee}=T.taskCache;try{const ke=yield*Jn(T.serverStates.utxoListQueryTask(Oe,L)),Ke=T.walletTools.addressToScriptPubkey(L),Ge=yield new Vr(T.dataLayer.fetchAddress(Ke));if(Ge==null||Ge.path==null)return!0;if(ke.length===0)return Rd(Ee,ue.path,Ke,0),!0;for(const ft of ke){const ot=`${ft.txid}_${ft.vout}`;xe[ot]={blockbookUtxo:ft,processing:!1,requiredCount:ke.length,path:ue.path,address:Di(Ni({},Ge),{path:Ge.path})}}return be.addresses.add(L),!0}catch(ke){return console.error(ke),T.log("error while processing address for UTXOs:",ke),ye[L]=Di(Ni({},ue),{processing:!1}),!1}})}const Cd=(T,B)=>Yr(void 0,null,function*(){const{utxos:L,scriptPubkey:ue}=B,be=Object.fromEntries([...L].map(ke=>[ke.id,ke])),Oe=[],ye=yield T.dataLayer.fetchUtxos({scriptPubkey:ue});let xe="0";for(const ke of ye){if(ke==null)throw new Error("Unexpected undefined utxo when processing unspent transactions");ke.spent||(xe=(0,ce.add)(ke.value,xe)),be[ke.id]==null&&Oe.push(ke.id)}yield T.dataLayer.removeUtxos(Oe);let Ee="0";for(const ke of Object.values(be))ke.spent||(Ee=(0,ce.add)(ke.value,Ee)),yield T.dataLayer.saveUtxo(ke);if(Ee!==xe){T.log("address balance changed:",{scriptPubkey:ue,oldBalance:xe,newBalance:Ee}),T.emitter.emit(Hr.ADDRESS_BALANCE_CHANGED,T.pluginInfo.currencyInfo.currencyCode,[{scriptPubkey:ue,balance:Ee}]);const ke=yield T.dataLayer.fetchAddress(ue);if(ke==null)throw new Error("address not found when processing UTXO transactions");yield T.dataLayer.saveAddress(Di(Ni({},ke),{balance:Ee,used:!0}))}yield T.updateProgressRatio(),yield au(T).catch(ke=>{throw T.log.error(ke),ke})});function Jg(T,B){return Vo(this,null,function*(){const{serverUri:L,cacheItem:ue}=B,{blockbookUtxoCache:be,dataLayerUtxoCache:Oe}=T.taskCache,ye=so(ue.path,T.pluginInfo.engineInfo.scriptTemplates),xe=eu(ye);let Ee,ke;const Ke=()=>{var Ge;const ft={id:`${ue.blockbookUtxo.txid}_${ue.blockbookUtxo.vout}`,txid:ue.blockbookUtxo.txid,vout:ue.blockbookUtxo.vout,value:ue.blockbookUtxo.value,scriptPubkey:ue.address.scriptPubkey,script:Ee,redeemScript:ke,scriptType:xe,blockHeight:(Ge=ue.blockbookUtxo.height)!=null?Ge:-1,spent:!1};Rd(Oe,ue.path,ue.address.scriptPubkey,ue.requiredCount,ft)};switch(ye){case Mr.Airbitz:case Mr.Legacy:case Mr.ReplayProtection:ke=ue.address.redeemScript;{const[Ge]=yield new Vr(T.dataLayer.fetchTransactions({txId:ue.blockbookUtxo.txid}));if(Ge==null)try{const ft=yield*Jn(T.serverStates.transactionQueryTask(L,ue.blockbookUtxo.txid));return Ee=c0(T,{txResponse:ft}).hex,Ke(),!0}catch(ft){T.log("error while processing Blockbook UTXO:",ft);const ot=`${ue.blockbookUtxo.txid}_${ue.blockbookUtxo.vout}`;return be[ot]={blockbookUtxo:ue.blockbookUtxo,processing:!1,path:ue.path,address:ue.address,requiredCount:ue.requiredCount},!1}else Ee=Ge.hex}break;case Mr.WrappedSegwit:if(Ee=ue.address.scriptPubkey,ue.address.redeemScript==null)throw new Error("Address redeem script not defined, but required for p2sh wrapped segwit utxo processing");ke=ue.address.redeemScript;break;case Mr.Segwit:Ee=ue.address.scriptPubkey;break}return Ke(),!0})}const Rd=(T,B,L,ue,be)=>{var Oe;const ye=(Oe=T[L])!=null?Oe:{utxos:[],processing:!1,path:B,full:!1};be!=null&&ye.utxos.push(be),T[L]=ye,ye.full=ye.utxos.length>=ue};function Fd(T){const{pluginInfo:B,publicKey:L}=T,{engineInfo:ue}=B,{name:be}=B.coinInfo,Oe=L.publicKeys,ye={getPubkey(xe){var Ee;if(Oe[xe.format]==null)throw new Error(`wallet tools: xpub with format ${xe.format} does not exist`);return Sl({xpub:(Ee=Oe[xe.format])!=null?Ee:"",coin:be,type:Ci(xe.format),bip44ChangeIndex:xe.changeIndex,bip44AddressIndex:xe.addressIndex})},getScriptPubkey(xe){const Ee=so(xe,ue.scriptTemplates),ke=eu(Ee);return La({pubkey:ye.getPubkey(xe),scriptTemplates:ue.scriptTemplates,scriptType:ke})},getScriptPubkeyFromWif(xe,Ee){const ke=Ci(Ee),Ke=eu(ke),Ge=te({wifKey:xe,coin:be});[Mr.Segwit,Mr.WrappedSegwit].includes(ke)&&!Ge.compressed&&(Ge.compressed=!0);const ft=oe(Ge);return La({pubkey:ft,scriptTemplates:ue.scriptTemplates,scriptType:Ke})},getAddress(xe){const Ee=so(xe,B.engineInfo.scriptTemplates),{scriptPubkey:ke}=ye.getScriptPubkey(xe),Ke=a0(Ee);return io({scriptPubkey:ke,addressType:Ke,coin:be})},addressToScriptPubkey(xe){return li({address:xe,coin:be})},scriptPubkeyToAddress(xe){const{changePath:Ee}=xe,ke=so(Ee,B.engineInfo.scriptTemplates),Ke=a0(ke);return io({scriptPubkey:xe.scriptPubkey,addressType:Ke,coin:be})},getPrivateKey(xe){const{path:Ee,xprivKeys:ke}=xe,Ke=ke[Ee.format];if(Ke==null)throw new Error(`wallet tools: xpriv with format ${Ee.format} does not exist`);return O({xpriv:Ke,type:Ci(Ee.format),coin:be,bip44ChangeIndex:Ee.changeIndex,bip44AddressIndex:Ee.addressIndex})},getPrivateKeyEncodingFromWif(xe){return te({wifKey:xe,coin:be})},getScriptAddress({path:xe,scriptTemplate:Ee}){const ke=ye.getPubkey(xe),Ke=Ee(ke),{address:Ge,scriptPubkey:ft,redeemScript:ot}=oo({coin:be,scriptPubkey:Ke});if(Ge==null)throw new Error("Failed to derive address for script");return{address:Ge,scriptPubkey:ft,redeemScript:ot}},signMessageBase64({path:xe,message:Ee,xprivKeys:ke}){const Ke=ye.getPrivateKey({path:xe,xprivKeys:ke});return he(Ee,Ke)}};return ye}var Nd=$t(8287).Buffer,Qg=Object.defineProperty,em=Object.defineProperties,tm=Object.getOwnPropertyDescriptors,Dd=Object.getOwnPropertySymbols,rm=Object.prototype.hasOwnProperty,nm=Object.prototype.propertyIsEnumerable,Ld=(T,B,L)=>B in T?Qg(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,Li=(T,B)=>{for(var L in B||(B={}))rm.call(B,L)&&Ld(T,L,B[L]);if(Dd)for(var L of Dd(B))nm.call(B,L)&&Ld(T,L,B[L]);return T},Ui=(T,B)=>em(T,tm(B)),Br=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())});function im(T){return Br(this,null,function*(){const{pluginInfo:B,pluginDisklet:L,emitter:ue,engineOptions:be,io:Oe,pluginState:ye}=T,{walletLocalDisklet:xe,walletLocalEncryptedDisklet:Ee,log:ke}=be,{currencyInfo:Ke,engineInfo:Ge,coinInfo:ft}=B,ot=Ua(be.userSettings);ye.updateServers(ot).catch(gt=>{ke.error(gt)});const wt=n0(ft.name,ft.coinType),yt=w(wt),Bt=Gh(B)(T.walletInfo),{privateKeyFormat:Gt,publicKey:or,walletFormats:pr}=Bt.keys;if(!Ge.formats.includes(Gt)){const gt=`Wallet format is not supported: ${Gt}`;throw ke.error(gt),new Error(gt)}const jt=Fd({pluginInfo:B,publicKey:or}),Lt=yield cp({disklet:L,pluginInfo:B,io:Oe,log:T.engineOptions.log}),vt=yield Ph({disklet:xe,emitter:ue,log:ke}),xt=yield Hh({disklet:xe});let Ct;const _t=(gt=>Rt=>(Rt!=null&&(gt=Rt),gt))();_t(T.engineOptions.seenTxCheckpoint),ue.on(Hr.SEEN_TX_CHECKPOINT,gt=>{_t(gt)});const kt=Td(Ui(Li({},T),{dataLayer:xt,pluginState:ye,seenTxCheckpoint:_t,walletTools:jt,walletInfo:Bt})),Nt={accelerate(gt){return Br(this,null,function*(){var Rt;const{canReplaceByFee:Zt=!1}=Ke;if(!Zt||Gt==="bip32"||Gt==="bip44")return null;const Vt=gt.txid,[nr]=yield xt.fetchTransactions({txId:Vt});if(nr==null||nr.inputs.every(Nr=>Nr.sequence>4294967293)||nr.blockHeight!==0)return null;const qt=To(nr.hex),ir=Math.round(parseInt(nr.fees)/qt*2),fr=nr.inputs,kr=yield Promise.all(fr.map((Nr,Wr)=>Br(this,null,function*(){const Qn=yield gv(xt,nr,Wr);return Qn.spent=!1,Qn}))),Cr=kr.reduce((Nr,Wr)=>Wr.value>Nr.value?Wr:Nr),Kr=[],Zr=[];let Fr;for(const Nr of nr.outputs){const Wr=yield xt.fetchAddress(Nr.scriptPubkey);if(Wr==null){Kr.push({scriptPubkey:Nr.scriptPubkey,value:parseInt(Nr.amount)});continue}if(Wr.path==null)throw new Error("Expecting path for address");const Qn=so(Wr.path,Ge.scriptTemplates),ho=a0(Qn),{address:yn}=io({scriptPubkey:Wr.scriptPubkey,addressType:ho,coin:ft.name,redeemScript:Wr.redeemScript});Zr.push(yn),Wr.path.changeIndex===1?Fr=yn:Kr.push({scriptPubkey:Nr.scriptPubkey,value:parseInt(Nr.amount)})}const jr=Fr==null?yield kt.getFreshAddress({branch:1}):{publicAddress:Fr},Cn=(Rt=jr.segwitAddress)!=null?Rt:jr.publicAddress,Hi=Al(yield xt.fetchUtxos({utxoIds:[]})).filter(Nr=>Nr.txid!==Vt),Sn={utxos:[...kr,...Hi],forceUseUtxo:[Cr],targets:Kr,memos:gt.memos,feeRate:ir,coin:ft.name,currencyCode:Ke.currencyCode,enableRbf:!0,freshChangeAddress:Cn,subtractFee:!1,log:ke,outputSort:"bip69"},on=(()=>{try{return Ae(Sn)}catch(Nr){const Wr=ul(Nr);if((Wr==null?void 0:Wr.networkFeeShortage)!=null){let Qn=parseInt(Wr.networkFeeShortage);for(const ho of Kr){if(ho.value==null)continue;const yn=Math.min(ho.value,Qn);ho.value-=yn,Qn-=yn}return Ae(Sn)}throw Nr}})();on.changeUsed&&Zr.push(Cn);const kn=on.inputs.map(Nr=>Nr.scriptPubkey.toString("hex"));let hn="0";for(const Nr of on.outputs){const Wr=Nr.scriptPubkey.toString("hex");(yield xt.fetchAddress(Wr))==null?hn=ce.sub(hn,Nr.value.toString()):kn.push(Wr)}const zi=on.fee.toString();hn=ce.sub(hn,zi);const Zo={unsignedTx:on.hex,psbt:{base64:on.psbtBase64,inputs:on.inputs,outputs:on.outputs},ourScriptPubkeys:kn,replacedTxid:Vt};return Ui(Li({},gt),{blockHeight:0,currencyCode:Ke.currencyCode,date:za(),feeRateUsed:{satPerVByte:ir},isSend:!0,nativeAmount:hn,networkFee:zi,otherParams:Zo,ourReceiveAddresses:Zr,parentNetworkFee:void 0,signedTx:"",txid:"",walletId:Bt.id})})},startEngine(){return Br(this,null,function*(){ue.emit(Hr.WALLET_BALANCE_CHANGED,Ke.currencyCode,vt.state.balance),ye.addEngine(kt),yield Lt.start(),yield kt.start()})},killEngine(){return Br(this,null,function*(){yield kt.stop(),Lt.stop(),ye.removeEngine(kt)})},getBalance(gt){return vt.state.balance},getBlockHeight(){return vt.state.lastSeenBlockHeight},addCustomToken(gt){return Br(this,null,function*(){return yield Promise.resolve(void 0)})},addGapLimitAddresses(gt){return Br(this,null,function*(){return yield kt.addGapLimitAddresses(gt)})},broadcastTx(gt){return Br(this,null,function*(){var Rt,Zt;const{otherParams:Vt}=gt;if(((Rt=Vt==null?void 0:Vt.paymentProtocolInfo)==null?void 0:Rt.payment)!=null&&((Zt=Vt==null?void 0:Vt.paymentProtocolInfo)==null?void 0:Zt.paymentUrl)!=null&&typeof(yield xv(Oe.fetch,Vt.paymentProtocolInfo.paymentUrl,Vt.paymentProtocolInfo.payment))>"u")throw new Error(`Error when sending to ${Vt.paymentProtocolInfo.paymentUrl}`);if((yield kt.broadcastTx(gt).catch(qt=>{throw String(qt).includes("Error: Blockbook Error: -26: dust")?new $d:qt}))!==gt.txid)throw new Error("broadcast response txid does not match original");return gt})},changeUserSettings(gt){return Br(this,null,function*(){yield ye.updateServers(Ua(gt))})},disableTokens(gt){return Br(this,null,function*(){return yield Promise.resolve(void 0)})},dumpData(){return Br(this,null,function*(){return{walletId:Bt.id.split(" - ")[0],walletType:Bt.type,data:{walletInfo:{pluginType:Ke.pluginId,privateKeyFormat:Gt,walletFormats:pr},metadataState:vt.state,storageState:yield xt.dumpData(),pluginState:ye.dumpData()}}})},enableTokens(gt){return Br(this,null,function*(){return yield Promise.resolve(void 0)})},getDisplayPrivateSeed(gt){const Rt=yt(gt);return Rt==null?null:Rt.format==="bip32"?Nd.from(Rt.seed,"base64").toString("hex"):Rt.seed},getDisplayPublicSeed(){const gt=or.publicKeys;return Object.values(gt).filter(Rt=>Rt!=null).join(`
|
|
78
78
|
`)},getFreshAddress(gt){return Br(this,null,function*(){const{forceIndex:Rt}=gt;return yield kt.getFreshAddress({forceIndex:Rt})})},getNumTransactions(gt){return xt.numTransactions()},getPaymentProtocolInfo(gt){return Br(this,null,function*(){return yield bv(gt,Ke.currencyCode,Oe.fetch)})},getTransactions(gt){return Br(this,null,function*(){const Rt=Al(yield xt.fetchTransactions({options:gt}));return yield Promise.all(Rt.map(Zt=>Br(this,null,function*(){return yield ja({walletId:Bt.id,tx:Zt,walletTools:jt,dataLayer:xt,pluginInfo:B})})))})},isAddressUsed(gt){return Br(this,null,function*(){const Rt=jt.addressToScriptPubkey(gt),Zt=yield xt.fetchAddress(Rt);if(Zt==null)throw new Error("Address not found in wallet");return Zt.used})},makeSpend(gt){return Br(this,null,function*(){var Rt,Zt,Vt,nr,qt,ir,fr;const kr=Ct!=null?Ct:xt;Ct!=null&&(Ct=void 0),gt=Tp(gt,Ke);const{memos:Cr=[],spendTargets:Kr}=gt,Zr=_l((Rt=gt.otherParams)!=null?Rt:{}),Fr=(Zt=Zr.txOptions)!=null?Zt:{},{outputSort:jr,utxoSourceAddress:Cn,forceChangeAddress:Hi}=Zr;let lo;if(Cn!=null&&(lo=jt.addressToScriptPubkey(Cn)),Fr.CPFP==null&&Kr.length<1)throw new Error("Need to provide Spend Targets");const Sn=Kr.reduce((Gr,{nativeAmount:In})=>ce.add(Gr,In!=null?In:"0"),"0"),on=(Vt=Fr.utxos)!=null?Vt:Al(yield kr.fetchUtxos({scriptPubkey:lo,utxoIds:[]}));if(ce.gt(Sn,`${vv(on)}`)||on.length===0)throw new Jd({tokenId:null});let kn=[];const hn=[];for(const Gr of Kr){if(Gr.publicAddress==null||Gr.nativeAmount==null)throw new Error("Invalid spend target");if(((nr=Gr.otherParams)==null?void 0:nr.script)!=null){const{script:In}=Gr.otherParams;if(In.type==="replayProtection"){const{publicAddress:po}=yield kt.deriveScriptAddress(In.type);kn.push({address:po,value:Gr.nativeAmount==null?void 0:parseInt(Gr.nativeAmount)})}}else{if(Gr.publicAddress!=null){const In=jt.addressToScriptPubkey(Gr.publicAddress);(yield kr.fetchAddress(In))!=null&&hn.push(Gr.publicAddress)}kn.push({address:Gr.publicAddress,value:Gr.nativeAmount==null?void 0:parseInt(Gr.nativeAmount)})}}if(kn.length+Cr.length<1)throw new Error("Need to provide Spend Targets");const zi=yield kt.getFreshAddress({branch:1}),Zo=(qt=Hi!=null?Hi:zi.segwitAddress)!=null?qt:zi.publicAddress,Nr=parseInt(yield Lt.getRate(gt));let Wr;if(Fr.CPFP!=null){const[Gr]=yield kr.fetchTransactions({txId:Fr.CPFP});if(Gr==null)throw new Error("transaction not found");const In=[];for(const po of Gr.ourOuts){const[Va]=yield kr.fetchUtxos({utxoIds:[po]});Va!=null&&In.push(Va)}Wr=In.reduce((po,Va)=>ce.gt(po.value,Va.value)?po:Va),kn=[]}const Qn=Ke.canReplaceByFee===!0?(fr=(ir=gt.enableRbf)!=null?ir:Zr.enableRbf)!=null?fr:!0:!1;ke.warn(`spend: Using fee rate ${Nr} sat/B`);const ho=Fr.subtractFee!=null?Fr.subtractFee:!1,yn=Ae({utxos:on,forceUseUtxo:Wr!=null?[Wr]:[],targets:kn,memos:Cr,feeRate:Nr,coin:ft.name,currencyCode:Ke.currencyCode,enableRbf:Qn,freshChangeAddress:Zo,subtractFee:ho,log:ke,outputSort:jr});yn.changeUsed&&hn.push(Zo);let Ga="0";const Zd=yn.inputs.map(Gr=>Gr.scriptPubkey.toString("hex"));for(const Gr of yn.outputs){const In=Gr.scriptPubkey.toString("hex");(yield kr.fetchAddress(In))==null?Ga=ce.sub(Ga,Gr.value.toString()):Zd.push(In)}const p0=yn.fee.toString();Ga=ce.sub(Ga,p0);const Mm={unsignedTx:yn.hex,psbt:{base64:yn.psbtBase64,inputs:yn.inputs,outputs:yn.outputs},edgeSpendInfo:gt,ourScriptPubkeys:Zd};return{blockHeight:0,currencyCode:Ke.currencyCode,date:za(),feeRateUsed:{satPerVByte:Nr},isSend:!0,memos:Cr,nativeAmount:Ga,networkFee:p0,networkFees:[{tokenId:null,nativeAmount:p0}],otherParams:Mm,ourReceiveAddresses:hn,signedTx:"",tokenId:null,txid:"",walletId:Bt.id}})},resyncBlockchain(){return Br(this,null,function*(){yield Nt.killEngine(),yield xt.clearAll(),yield ye.clearCache(),yield vt.clear(),yield Lt.clearCache(),yield ye.refreshServers(),yield Nt.startEngine()})},saveTx(gt){return Br(this,null,function*(){var Rt,Zt;const Vt=(Rt=gt.otherParams)==null?void 0:Rt.replacedTxid;if(Vt!=null){const[ir]=yield xt.fetchTransactions({txId:Vt});if(ir!=null){ir.blockHeight=-1,yield xt.saveTransaction({tx:ir});const fr=yield ja({dataLayer:xt,pluginInfo:B,tx:ir,walletId:Bt.id,walletTools:jt});ue.emit(Hr.TRANSACTIONS,[{isNew:!1,transaction:fr}])}}const nr=$p(gt);yield xt.saveTransaction({tx:nr,scriptPubkeys:(Zt=gt.otherParams)==null?void 0:Zt.ourScriptPubkeys});const qt=yield Pv(Ge,xt,nr);yield kt.processUtxos(qt)})},signMessage(gt,Rt,Zt){return Br(this,null,function*(){const Vt=Zn(Zt.otherParams),{publicAddress:nr}=Vt,qt=jt.addressToScriptPubkey(nr),ir=yield xt.fetchAddress(qt);if((ir==null?void 0:ir.path)==null)throw new Error("Missing data-layer address to sign with");const fr=yt(Rt);if(fr==null)throw new Error("Cannot sign a message for a read-only wallet");const kr=yield Zh({privateKey:fr,walletLocalEncryptedDisklet:Ee,coin:ft.name});return yield jt.signMessageBase64({path:ir==null?void 0:ir.path,message:gt,xprivKeys:kr})})},signTx(gt,Rt){return Br(this,null,function*(){var Zt,Vt,nr;const qt=gt.otherParams;if(qt==null)throw new Error("Invalid transaction data");const{psbt:ir,edgeSpendInfo:fr}=qt;if(ir==null)throw new Error("Invalid transaction data");const kr=yt(Rt);if(kr==null)throw new Error("Cannot sign a transaction for a read-only wallet");const Cr=yield Zh({privateKey:kr,walletLocalEncryptedDisklet:Ee,coin:ft.name}),Kr=yield Br(this,null,function*(){return(fr==null?void 0:fr.privateKeys)!=null?fr.privateKeys.map(jr=>jt.getPrivateKeyEncodingFromWif(jr)):yield Promise.all(ir.inputs.map(jr=>Br(this,[jr],function*({hash:Cn,index:Hi}){const lo=Nd.from(Cn).reverse().toString("hex"),[Sn]=yield xt.fetchTransactions({txId:lo});if(Sn==null)throw new Error("Unable to find previous transaction data for input");const on=Sn.outputs.find(Zo=>Zo.n===Hi);if(on==null)throw new Error("Unable to find prevout in transaction");const{scriptPubkey:kn}=on,hn=yield xt.fetchAddress(kn);if(hn==null)throw new Error(`Address for scriptPubkey '${kn}' not found`);if(hn.path==null)throw new Error(`Invalid scriptPubkey ${hn.scriptPubkey}; Missing path`);return{hex:jt.getPrivateKey({path:hn.path,xprivKeys:Cr}),compressed:!0}})))}),Zr=yield Te({coin:ft.name,feeInfo:Lt.feeInfo,privateKeyEncodings:Kr,psbtBase64:ir.base64});gt.txid=Zr.id,gt.signedTx=Zr.hex;const{paymentProtocolInfo:Fr}=(nr=(Vt=(Zt=gt.otherParams)==null?void 0:Zt.edgeSpendInfo)==null?void 0:Vt.otherParams)!=null?nr:{};if(Fr!=null){const jr=wv(gt.signedTx,gt.currencyCode);gt.otherParams==null&&(gt.otherParams={}),Object.assign(gt.otherParams,{paymentProtocolInfo:Ui(Li({},Fr),{payment:jr})})}return gt.date=za(),gt})},sweepPrivateKeys(gt){return Br(this,null,function*(){var Rt;const Zt=Ge.formats,Vt={id:Bt.id,type:Bt.type,keys:{privateKeyFormat:Bt.keys.privateKeyFormat,walletFormats:Zt,publicKey:{publicKeys:{}}}},nr=(Rt=gt.privateKeys)!=null?Rt:[];if(nr.length<1)throw new Error("No private keys given");const qt=(0,Ha.cQ)(),ir=(0,Ha.cQ)(),fr=new Ah,kr={disklet:qt,emitter:fr,log:ke},Cr=yield Ph(kr),Kr=yield Hh(kr),Zr=Fd({pluginInfo:B,publicKey:Vt.keys.publicKey}),Fr=new Promise((Cn,Hi)=>{fr.on(Hr.ADDRESSES_CHECKED,lo=>Br(this,null,function*(){if(lo===1)try{yield jr.stop();const Sn=yield Kr.fetchUtxos({utxoIds:[]});if(Sn===null||Sn.length<1)throw new Error("Private key has no funds");const on=yield this.getFreshAddress({tokenId:null}),kn=Cr.state.balance,hn={utxos:Sn,subtractFee:!0};gt.spendTargets=[{publicAddress:on.publicAddress,nativeAmount:kn}],gt.otherParams=Ui(Li({},gt.otherParams),{txOptions:hn}),Ct=Kr;const zi=yield Nt.makeSpend(gt);Cn(zi)}catch(Sn){Hi(Sn)}}))}),jr=Td(Ui(Li({},T),{dataLayer:Kr,emitter:fr,engineOptions:Ui(Li({},T.engineOptions),{walletLocalDisklet:qt,walletLocalEncryptedDisklet:ir}),pluginInfo:Ui(Li({},B),{engineInfo:Ui(Li({},Ge),{gapLimit:0})}),seenTxCheckpoint:()=>"0",walletTools:Zr,walletInfo:Vt}));return yield jr.loadWifs(nr),yield jr.start(),yield Fr})},otherMethods:{}};return Nt})}var Ud=$t(8287).Buffer,qo=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())});function om(T,B){const{currencyInfo:L,engineInfo:ue,coinInfo:be}=B,Oe=n0(be.name,be.coinType),ye=C(Oe),xe=Gh(B);return{checkPublicKey(ke){return qo(this,null,function*(){const Ke=w(jh)(ke);if(Ke==null)return!1;const Ge=Wh(Ke);return Jf(ue,Ge).every(ot=>Ke.publicKeys[ot]!=null)})},createPrivateKey(ke,Ke){return qo(this,null,function*(){var Ge,ft,ot,wt;const Bt={imported:!1,seed:le.VF(Ud.from(T.random(32))),format:(ft=(Ge=Ke==null?void 0:Ke.format)!=null?Ge:ue.formats[0])!=null?ft:"bip44",coinType:(wt=(ot=Ke==null?void 0:Ke.coinType)!=null?ot:be.coinType)!=null?wt:0};return ye(Bt)})},importPrivateKey(ke,Ke){return qo(this,null,function*(){var Ge,ft,ot,wt,yt;if(!le.JB(ke))throw Ud.from(ke,"base64").length===32?new Error("Import for Airbitz seeds is unsupported."):new Error("Invalid mnemonic");const Gt={imported:!0,seed:ke,format:(ot=(ft=Ke==null?void 0:Ke.format)!=null?ft:(Ge=ue.formats)==null?void 0:Ge[0])!=null?ot:"bip44",coinType:(yt=(wt=Ke==null?void 0:Ke.coinType)!=null?wt:be.coinType)!=null?yt:0};return ye(Gt)})},derivePublicKey(ke){return qo(this,null,function*(){return xe(ke).keys.publicKey})},parseUri(ke){return qo(this,null,function*(){const Ke=ke.toLocaleLowerCase().startsWith(`${be.name}://`);Ke&&(ke=ke.replace("//",""));const Ge=s0()(ke,{},!0),ft=Ge.protocol.replace(":","").toLowerCase();if(ft!==""&&ft!==L.pluginId&&ft!==ue.uriPrefix&&ft!=="pay")throw new Error("InvalidUriError");const{pathname:ot,query:wt}=Ge;if(ot===""&&wt.r==null)throw new Error("InvalidUriError");const yt={};if(ot!==""){const or=pv({pathname:Ge.pathname,coin:be.name});if(or==null)throw new Error("InvalidUriError");Object.assign(yt,or)}const Bt={};wt.label!=null&&(Bt.name=wt.label),wt.message!=null&&(Bt.notes=wt.message),wt.category!=null&&(Bt.category=wt.category),wt.r!=null&&(yt.paymentProtocolUrl=wt.r),Ke&&(Bt.gateway=!0),Object.assign(yt,{metadata:Bt});const Gt=L.denominations.find(({name:or})=>or===L.currencyCode);if(Gt!=null&&wt.amount!=null){const{multiplier:or="1"}=Gt,pr=ce.mul(wt.amount,or.toString());yt.currencyCode=L.currencyCode,yt.nativeAmount=ce.toFixed(pr,0,0)}return yt})},encodeUri(ke,Ke){return qo(this,null,function*(){var Ge,ft;const{publicAddress:ot}=ke;if(ot==="")throw new Error("InvalidPublicAddressError");const wt=[];if(ke.nativeAmount!=null){const Bt=(Ge=ke.currencyCode)!=null?Ge:L.currencyCode,Gt=L.denominations.find(({name:pr})=>pr===Bt);if(Gt==null)throw new Error("InvalidDenominationError");const or=ce.div(ke.nativeAmount,Gt.multiplier,8);wt.push(`amount=${or}`)}ke.label!=null&&wt.push(`label=${ke.label}`),ke.message!=null&&wt.push(`message=${ke.message}`);const yt=ke.metadata;return yt!=null&&(yt.name!=null&&wt.push(`label=${yt.name}`),yt.notes!=null&&wt.push(`message=${yt.notes}`)),wt.length>0?nd.serialize({scheme:(ft=ue.uriPrefix)!=null?ft:L.pluginId,path:ot,query:wt.join("&")}):ot})},getSplittableTypes(ke){var Ke;const{keys:{format:Ge="bip32"}={}}=ke;return((Ke=ue.forks)!=null?Ke:[]).filter(ot=>mp(ot).includes(Ge)).map(ot=>`wallet:${ot}`)}}}const am=x({serverUrl:p,serverScore:m,responseTime:m,numResponseTimes:m}),Hd=x(am),sm=x({customServers:Hd,enableCustomServers:w(k,!1),internalServers:Hd}),Xo=999999999,su=500,l0=-100,zd=-100,Kd=-10;class fm{constructor(B){const{log:L,onDirtyServer:ue=()=>{}}=B;this.log=L,this.scoresLastLoaded=Date.now(),this.lastScoreUpTime=Date.now(),this.onDirtyServer=ue}serverScoresLoad(B,L=[]){for(const ue of L)if(B[ue]===void 0){const be={serverUrl:ue,serverScore:0,responseTime:Xo,numResponseTimes:0};B[ue]=be}for(const ue in B){const be=B[ue];let Oe=!1;for(const Ee of L)if(Ee===ue){Oe=!0;break}let ye=be.serverScore;Oe?ye<Kd&&(ye=Kd):ye>zd&&(ye=zd),this.scoresLastLoaded===0&&(ye=Math.min(ye,su-100)),ue.startsWith("ws")&&ye>0&&(ye=0,be.responseTime=Xo),ld(ue).length>0&&(ye=ye-(su+l0)),be.serverScore=ye,this.onDirtyServer(ue)}}clearServerScoreTimes(){this.scoresLastLoaded=Date.now(),this.lastScoreUpTime=Date.now()}printServers(B){this.log("**** printServers ****");const L=[];for(const ue in B)L.push(B[ue]);L.sort((ue,be)=>be.serverScore-ue.serverScore);for(const ue of L){const be=ue.serverScore.toString(),Oe=ue.responseTime.toString(),ye=ue.numResponseTimes.toString(),xe=ue.serverUrl;this.log(`ServerInfo ${be} ${Oe}ms ${ye} ${xe}`)}this.log("**************************")}serverScoreUp(B,L,ue,be=1){const Oe=B[L];Oe.serverScore+=be,Oe.serverScore>su&&(Oe.serverScore=su),this.lastScoreUpTime=Date.now(),ue!==0&&this.setResponseTime(B,L,ue),this.log(`${L}: score UP to ${Oe.serverScore} ${ue}ms`),this.onDirtyServer(L)}serverScoreDown(B,L,ue=10){if(Date.now()-this.lastScoreUpTime>6e4){this.log(`${L}: score DOWN cancelled`);return}const Oe=B[L];Oe.serverScore-=ue,Oe.serverScore<l0&&(Oe.serverScore=l0),Oe.numResponseTimes===0&&this.setResponseTime(B,L,9999),this.log(`${L}: score DOWN to ${Oe.serverScore}`),this.onDirtyServer(L)}setResponseTime(B,L,ue){const be=B[L];be.numResponseTimes++;const Oe=be.responseTime;let ye=0;Xo===Oe?ye=ue:be.numResponseTimes%10===0?ye=(Oe+ue*4)/5:ye=(Oe+ue)/2,be.responseTime=ye,this.onDirtyServer(L)}getServers(B,L,ue=[]){if(B==null||Object.keys(B).length===0)return[];let be=[],Oe=[];for(const ot in B){const wt=B[ot];be.push(wt),wt.responseTime===Xo&&wt.serverScore===0&&Oe.push(wt)}if(be.length===0)return[];if(ue.length>0){const ot=wt=>{for(const yt of ue)if(typeof yt=="string"&&wt.serverUrl.indexOf(yt)===0||yt instanceof RegExp&&yt.test(wt.serverUrl))return!0;return!1};be=be.filter(ot),Oe=Oe.filter(ot)}be.sort((ot,wt)=>wt.serverScore-ot.serverScore);const ye=be[0];let xe=0,Ee=0;for(let ot=0;ot<be.length;ot++){const wt=be[ot];wt.serverScore<ye.serverScore-100||wt.serverScore<5||wt.responseTime>=Xo||(xe++,!(xe<L)&&(xe>=be.length/2||(Ee=ot)))}let ke=be.slice(0,Ee);ke.sort((ot,wt)=>ot.responseTime-wt.responseTime),ke=ke.concat(be.slice(Ee));const Ke=[];let Ge=0,ft=0;for(const ot of ke)if(Ge++,Ke.push(ot.serverUrl),ot.responseTime===Xo&&ot.serverScore===0&&ft++,Ge>=L||Ge>=L/2&&ft===0&&Oe.length>=L-Ge)break;if(ft===0){for(const ot of Oe)if(Ke.unshift(ot.serverUrl),Ge++,Ge>=L)break}return Ke}removeServers(B,L){for(const ue of L)delete B[ue]}}var um=Object.defineProperty,cm=Object.defineProperties,lm=Object.getOwnPropertyDescriptors,jd=Object.getOwnPropertySymbols,hm=Object.prototype.hasOwnProperty,dm=Object.prototype.propertyIsEnumerable,Wd=(T,B,L)=>B in T?um(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,pm=(T,B)=>{for(var L in B||(B={}))hm.call(B,L)&&Wd(T,L,B[L]);if(jd)for(var L of jd(B))dm.call(B,L)&&Wd(T,L,B[L]);return T},vm=(T,B)=>cm(T,lm(B)),Yo=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())});const h0="serverCache.json";function gm(T){const{defaultSettings:B,log:L,pluginDisklet:ue,pluginId:be}=T;let Oe=[];const ye=t(ue);let xe={customServers:{},enableCustomServers:B.enableCustomServers,internalServers:{}},Ee=!1;const ke=()=>{const yt=xe.enableCustomServers?"customServers":"internalServers";return xe[yt]},Ke=()=>Yo(this,null,function*(){ft.printServers(ke()),Ee&&(yield ye.setJson(h0,xe).catch(yt=>{L(`${be} - ${JSON.stringify(yt.toString())}`)}),Ee=!1,ft.scoresLastLoaded=Date.now(),L(`${be} - Saved server cache`))}),Ge=yt=>{Ee=!0;for(const Bt of Oe)if(Bt.processedPercent===1&&Bt.getServerList().includes(yt)){Ke().catch(or=>{L(`${be} - ${JSON.stringify(or.toString())}`)});return}},ft=new fm({log:L,onDirtyServer:Ge}),ot=()=>Yo(this,null,function*(){if(wt.infoPayload==null)return L.warn("info server list list empty"),[];const yt=Object.keys(wt.infoPayload.blockbookServers);return L.warn("info server list",yt),yt}),wt={infoPayload:T.infoPayload,addEngine(yt){Oe.push(yt)},removeEngine(yt){Oe=Oe.filter(Bt=>Bt!==yt)},dumpData(){return{"pluginState.servers_":ke()}},load(){return Yo(this,null,function*(){try{xe=sm(yield ye.getJson(h0))}catch(yt){L(`${be}: Failed to load server cache: ${JSON.stringify(yt)}`)}return wt.refreshServers().catch(yt=>{L(`${be} - ${JSON.stringify(yt.toString())}`)}),this})},serverScoreDown(yt){ft.serverScoreDown(ke(),yt)},serverScoreUp(yt,Bt){ft.serverScoreUp(ke(),yt,Bt)},clearCache(){return Yo(this,null,function*(){ft.clearServerScoreTimes(),Ee=!0,yield ye.delete(h0)})},getLocalServers(yt,Bt=[]){return ft.getServers(ke(),yt,Bt)},refreshServers(yt){return Yo(this,null,function*(){var Bt;const Gt=ke();let or;if(xe.enableCustomServers)or=(Bt=yt!=null?yt:Object.keys(xe.customServers))!=null?Bt:B.blockbookServers;else{const pr=yield ot();or=pr.length>0?pr:B.blockbookServers;const jt=Object.keys(Gt).filter(Lt=>!or.includes(Lt));ft.removeServers(Gt,jt)}ft.serverScoresLoad(Gt,or),yield Ke();for(const pr of Oe)pr.refillServers()})},updateServers(yt){return Yo(this,null,function*(){const Bt=()=>{const jt=Object.keys(xe.customServers),Lt=new Set(yt.blockbookServers),vt=new Set(jt);if(Lt.size!==vt.size)return!1;for(const xt of yt.blockbookServers)if(!vt.has(xt))return!1;return!0};if(yt.enableCustomServers===xe.enableCustomServers&&Bt())return;const Gt=yt.enableCustomServers&&yt.blockbookServers.length!==0,or=[],pr=[];for(const jt of Oe)or.push(jt),jt.setServerList([]),pr.push(jt.stop());yield Promise.all(pr),ft.clearServerScoreTimes(),xe=vm(pm({},xe),{enableCustomServers:Gt,customServers:{}}),Ee=!0,yield Ke(),yield wt.refreshServers(yt.blockbookServers);for(const jt of or)yield jt.start()})}};return wt}var mm=Object.defineProperty,Gd=Object.getOwnPropertySymbols,ym=Object.prototype.hasOwnProperty,bm=Object.prototype.propertyIsEnumerable,Vd=(T,B,L)=>B in T?mm(T,B,{enumerable:!0,configurable:!0,writable:!0,value:L}):T[B]=L,wm=(T,B)=>{for(var L in B||(B={}))ym.call(B,L)&&Vd(T,L,B[L]);if(Gd)for(var L of Gd(B))bm.call(B,L)&&Vd(T,L,B[L]);return T},d0=(T,B,L)=>new Promise((ue,be)=>{var Oe=Ee=>{try{xe(L.next(Ee))}catch(ke){be(ke)}},ye=Ee=>{try{xe(L.throw(Ee))}catch(ke){be(ke)}},xe=Ee=>Ee.done?ue(Ee.value):Promise.resolve(Ee.value).then(Oe,ye);xe((L=L.apply(T,B)).next())});let qd=!1;function xm(T,B){const{currencyInfo:L}=B,{initOptions:ue,io:be,log:Oe,nativeIo:ye,pluginDisklet:xe}=T,Ee=om(be,B),{defaultSettings:ke,pluginId:Ke,currencyCode:Ge}=L,ft=gm({defaultSettings:Ua(ke),currencyCode:Ge,infoPayload:w(Pn)(T.infoPayload),io:be,log:Oe,pluginId:Ke,pluginDisklet:xe});if(!qd){const{memletConfig:wt}=ye["edge-currency-plugins"];wt!=null&&(qd=!0,a(wt))}return{currencyInfo:L,makeCurrencyEngine(wt,yt){return d0(this,null,function*(){const Bt=vp(yt.callbacks),Gt={walletInfo:wt,pluginInfo:B,pluginDisklet:xe,currencyTools:Ee,initOptions:Vf(ue),io:be,emitter:Bt,engineOptions:wm({},yt),pluginState:ft};return yield im(Gt)})},makeCurrencyTools(){return d0(this,null,function*(){return ft.load().catch(wt=>{throw wt}),Ee})},updateInfoPayload(wt){return d0(this,null,function*(){try{ft.infoPayload=Pn(wt)}catch{Oe.warn("invalid infoPayload",wt)}})}}}var Xd;const Yd={};for(const T of No)Yd[T.currencyInfo.pluginId]=B=>xm(B,T);typeof window<"u"&&((Xd=window.addEdgeCorePlugins)==null||Xd.call(window,Yd));const Ay=null})()})();})();
|
|
@@ -168,6 +168,7 @@ var _utils3 = require('./utils');
|
|
|
168
168
|
`processed changed, percent: ${percent}, processedCount: ${processedCount}, totalCount: ${expectedProcessCount}`
|
|
169
169
|
)
|
|
170
170
|
processedPercent = percent
|
|
171
|
+
common.updateSeenTxCheckpoint()
|
|
171
172
|
emitter.emit(_EngineEmitter.EngineEvent.ADDRESSES_CHECKED, percent)
|
|
172
173
|
}
|
|
173
174
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "edge-currency-plugins",
|
|
3
|
-
"version": "3.5.
|
|
3
|
+
"version": "3.5.2",
|
|
4
4
|
"description": "Edge currency plugins to fetch and process wallet accounts, balances and transactions.",
|
|
5
5
|
"homepage": "https://edge.app/",
|
|
6
6
|
"repository": "https://github.com/EdgeApp/edge-currency-plugins",
|