edge-currency-accountbased 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # edge-currency-accountbased
2
2
 
3
+ ## 1.2.1 (2023-05-01)
4
+
5
+ - ZEC/ARRR: Prevent sending overlapping queries to synchronizer
6
+ - Fix accessing already deleted wallet connector
7
+ - ZEC/ARRR: Update checkpoints
8
+
3
9
  ## 1.2.0 (2023-04-24)
4
10
 
5
11
  - Add WalletConnect v1 support to Algorand
@@ -1,2 +1,2 @@
1
- (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[741],{37011:function(de,_,m){"use strict";m.r(_),m.d(_,{AlgorandTools:function(){return ie},makeCurrencyEngine:function(){return Ae},makeCurrencyTools:function(){return be}});var v=m(88814),w=m(77591),Z=m(20918),X=m(79014),S=m(76714),t=m(82448),F=m(62177);const j=(0,t.su)({latestRound:(0,t.Vk)(t.mH,0),latestTxid:(0,t.Vk)(t.XC,"")}),z=(0,t.su)({amount:t.mH,assets:(0,t._2)((0,t.su)({amount:t.mH,"asset-id":t.mH})),"min-balance":t.mH,round:t.mH}),Q=(0,t.su)({"confirmed-round":t.mH,fee:t.mH,"first-valid":t.mH,id:t.XC,note:(0,t.Zz)(t.XC),"round-time":t.mH,sender:t.XC,"tx-type":t.XC}).withRest,K=(0,t.Wf)("pay"),V=(0,t.su)({"payment-transaction":(0,t.su)({amount:t.mH,"close-amount":t.mH,receiver:t.XC}),"tx-type":K}),G=(0,t.Wf)("axfer"),J=(0,t.su)({"asset-transfer-transaction":(0,t.su)({amount:t.mH,"asset-id":t.mH}),"tx-type":G}),f=(0,t.su)({"current-round":t.mH,"next-token":(0,t.Zz)(t.XC),transactions:(0,t._2)(Q)}),T=(0,t.su)({flatFee:t.jK,fee:t.mH,firstRound:t.mH,lastRound:t.mH,genesisID:t.XC,genesisHash:t.XC}),I=(0,t.su)({type:t.XC}).withRest,x=(0,t.su)({encodedTx:t.XC,recipient:(0,t.Zz)(t.XC)}),q=(0,t.su)({type:K,to:t.XC,amount:t.mH}).withRest,p=(0,t.Vk)((0,t.su)({fee:(0,t.Zz)(t.XC)}),{fee:void 0}),H=(0,t.Vk)((0,t.su)({contractAddress:F.jD})),ne=F.BQ,E=y=>{const e=(0,t.su)({[`${y}Mnemonic`]:t.XC});return(0,t.W1)(n=>({mnemonic:e(n)[`${y}Mnemonic`]}),n=>({[`${y}Mnemonic`]:n.mnemonic}))},Y=(0,t.su)({id:(0,t._C)(t.XC,t.mH),method:(0,t.Wf)("algo_signTxn"),params:(0,t.vq)((0,t.vq)((0,t.su)({txn:t.XC,message:(0,t.Zz)(t.XC)})))}),N=(0,t.su)({id:t.mH,jsonrpc:(0,t.Wf)("2.0"),method:(0,t.Wf)("algo_signTxn"),params:(0,t.vq)((0,t.vq)((0,t.su)({txn:t.XC,message:(0,t.Zz)(t.XC)})))}).withRest;var $=m(12614),R=m(94935),D=m(35620),W=m(50244),he=m(48764).Buffer,fe=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptors,se=Object.getOwnPropertySymbols,pe=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty,we=Object.prototype.propertyIsEnumerable,Te=Reflect.get,re=(y,e,n)=>e in y?fe(y,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):y[e]=n,L=(y,e)=>{for(var n in e||(e={}))ge.call(e,n)&&re(y,n,e[n]);if(se)for(var n of se(e))we.call(e,n)&&re(y,n,e[n]);return y},Ie=(y,e)=>ye(y,me(e)),ve=(y,e,n)=>Te(pe(y),n,e),h=(y,e,n)=>new Promise((o,l)=>{var s=a=>{try{i(n.next(a))}catch(c){l(c)}},r=a=>{try{i(n.throw(a))}catch(c){l(c)}},i=a=>a.done?o(a.value):Promise.resolve(a.value).then(s,r);i((n=n.apply(y,e)).next())});const{Algodv2:ee,Indexer:ke}=v.ZP,oe=5e3,Ce=3e3;class te extends W.P{constructor(e,n,o,l){super(e,n,o,l),this.getRecipientBalance=s=>h(this,null,function*(){try{return(yield this.fetchAccountInfo(s)).amount.toString()}catch{return this.minimumAddressBalance}}),this.engineGetActivationAssets=s=>h(this,null,function*(){return{assetOptions:[{paymentWalletId:this.walletId,currencyPluginId:this.currencyInfo.pluginId}]}}),this.engineActivateWallet=s=>h(this,[s],function*({activateTokenIds:r,paymentTokenId:i,paymentWallet:a}){var c;if(r==null)throw new Error(`Must specify activateTokenIds for ${this.currencyInfo.currencyCode}`);if(i!=null)throw new Error(`Must activate with ${this.currencyInfo.currencyCode}`);if((a==null?void 0:a.id)!==this.walletId)throw new Error("Must pay with same wallet you are activating token with");const d=this.networkInfo.minimumTxFee.toFixed();let u="0";const g=[];for(const k of r){if(this.allTokensMap[k]==null)throw new Error(`Invalid tokenId to activate ${k}`);const b={currencyCode:this.allTokensMap[k].currencyCode,skipChecks:!0,spendTargets:[{publicAddress:this.walletInfo.keys.publicKey,nativeAmount:"0"}]};try{const C=yield this.makeSpend(b);u=(0,w.add)(u,(c=C.parentNetworkFee)!=null?c:d)}catch{u=(0,w.add)(u,d)}g.push(b)}return{paymentWalletId:this.walletId,fromNativeAmount:"0",networkFee:{nativeAmount:u,currencyPluginId:this.currencyInfo.pluginId},approve:(...k)=>h(this,[...k],function*(b={}){const{metadata:C}=b,A=[];for(const U of g){const M=yield this.makeSpend(U);M.metadata=L({},C);let O=yield a.signTx(M);O=yield a.broadcastTx(O),A.push(O),yield a.saveTx(O)}return{transactions:A}}),close:()=>h(this,null,function*(){})}}),this.networkInfo=e.networkInfo,this.queryTxMutex=(0,S.jT)(),this.suggestedTransactionParams={flatFee:!1,fee:0,firstRound:0,lastRound:0,genesisID:this.networkInfo.genesisID,genesisHash:this.networkInfo.genesisHash},this.minimumAddressBalance=this.networkInfo.minimumAddressBalance,this.totalReserve=this.minimumAddressBalance,this.otherMethods={wcInit:(s,r="Edge")=>h(this,null,function*(){return yield(0,S.Vs)(new Promise((i,a)=>{const c=new $.Z({uri:s.uri,storageId:s.uri,clientMeta:{description:"Edge Wallet",url:"https://www.edge.app",icons:["https://content.edge.app/Edge_logo_Icon.png"],name:r}});c.on("session_request",(d,u)=>{if(d!=null)throw this.error("Wallet connect session_request",d),d;const g=(0,F.ff)(u).params[0],P=Ie(L({},g),{timeConnected:Date.now()/1e3});this.tools.walletConnectors[s.uri]={connector:c,wcProps:s,dApp:P},i(P)}),c.on("call_request",(d,u)=>{try{if(d!=null)throw d;const g=N(u),P=g.params[0][0],k=(0,v.wj)(D.US.parse(P.txn)),b=k.amount!=null?k.amount.toString():"0",C=k.fee.toFixed();let A;if(k.type==="axfer"){const M=k.assetIndex.toString();if(this.allTokensMap[M]==null)throw new Error("Unrecognized token");A=M}const U={uri:s.uri,dApp:this.tools.walletConnectors[s.uri].dApp,payload:g,walletId:this.tools.walletConnectors[s.uri].walletId,nativeAmount:b,networkFee:C,tokenId:A};this.currencyEngineCallbacks.onWcNewContractCall(U)}catch(g){throw this.warn("Wallet connect call_request ",g),g}}),c.on("disconnect",(d,u)=>{if(d!=null)throw d;delete this.tools.walletConnectors[s.uri]})}),5e3)}),wcConnect:(s,r,i)=>{this.tools.walletConnectors[s].connector.approveSession({accounts:[r],chainId:416001}),this.tools.walletConnectors[s].walletId=i},wcDisconnect:s=>{this.tools.walletConnectors[s].connector.killSession().catch(()=>{}),delete this.tools.walletConnectors[s]},wcApproveRequest:(s,r,i)=>h(this,null,function*(){this.tools.walletConnectors[s].connector.approveRequest({id:Number(r.id),jsonrpc:"2.0",result:[i]})}),wcRejectRequest:(s,r)=>h(this,null,function*(){this.tools.walletConnectors[s].connector.rejectRequest({id:Number(r.id),jsonrpc:"2.0",error:{message:"rejected"}})}),wcGetConnections:()=>Object.keys(this.tools.walletConnectors).filter(s=>this.tools.walletConnectors[s].walletId===this.walletInfo.id).map(s=>L(L({},this.tools.walletConnectors[s].dApp),this.tools.walletConnectors[s].wcProps))}}setOtherData(e){this.otherData=j(e)}fetchAccountInfo(e){return h(this,null,function*(){return yield(0,S.QJ)(this.networkInfo.algodServers.map(n=>()=>h(this,null,function*(){const l=yield new ee("",n,"").accountInformation(e).do();return z(l)})))})}queryBalance(){return h(this,null,function*(){try{const e=yield this.fetchAccountInfo(this.walletLocalData.publicKey),{assets:n,amount:o,"min-balance":l,round:s}=e;this.totalReserve=l.toString();const r=[];for(const i of this.enabledTokens)if(i===this.currencyInfo.currencyCode)this.updateBalance(this.currencyInfo.currencyCode,o.toString());else{const a=Object.keys(this.allTokensMap).find(d=>this.allTokensMap[d].currencyCode===i);if(a==null){this.updateBalance(i,"0");continue}const c=n.find(d=>d["asset-id"].toFixed()===a);if(c==null){r.push(a),this.updateBalance(i,"0");continue}this.updateBalance(i,c.amount.toString())}s>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=s,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight)),(0,S.dQ)(r,this.walletLocalData.unactivatedTokenIds)||(this.walletLocalData.unactivatedTokenIds=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onUnactivatedTokenIdsChanged(this.walletLocalData.unactivatedTokenIds))}catch(e){this.log.warn("queryBalance Error ",e)}})}queryTransactionParams(){return h(this,null,function*(){try{const e=yield(0,S.QJ)(this.networkInfo.algodServers.map(n=>()=>h(this,null,function*(){const l=yield new ee("",n,"").getTransactionParams().do(),s=T(l);if(s.genesisHash!==this.networkInfo.genesisHash)throw new Error("Server genesisHash mismatch");return s})));this.suggestedTransactionParams=e}catch(e){this.log.warn("queryTransactionParams error:",e)}})}processAlgorandTransaction(e){const{fee:n,"confirmed-round":o,id:l,"round-time":s,sender:r,"tx-type":i}=e;let a,c,d,u,g=!1;const P=[];switch(i){case"pay":{const{amount:b}=V(e)["payment-transaction"];c=b.toString(),d=n.toString(),r===this.walletInfo.keys.publicKey?(c=`-${(0,w.add)(c,d)}`,g=!0):(d="0",P.push(this.walletInfo.keys.publicKey)),a=this.currencyInfo.currencyCode;break}case"axfer":{const{amount:b,"asset-id":C}=J(e)["asset-transfer-transaction"];c=b.toString(),d="0",r===this.walletInfo.keys.publicKey?(c=`-${c}`,u=n.toString(),g=!0):P.push(this.walletInfo.keys.publicKey);const A=this.allTokensMap[C];if(A==null)return;a=A.currencyCode;break}default:return}const k={txid:l,date:s,currencyCode:a,blockHeight:o,nativeAmount:c,isSend:g,networkFee:d,ourReceiveAddresses:P,parentNetworkFee:u,signedTx:"",walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,k)}queryTransactions(){return h(this,null,function*(){return yield this.queryTxMutex(()=>h(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return h(this,null,function*(){const e=this.otherData.latestRound;let n,o=this.otherData.latestRound,l=0,s,r=!0;do{const i=yield(0,S.QJ)(this.networkInfo.indexerServers.map(u=>()=>h(this,null,function*(){const P=yield new ke({},u,"").lookupAccountTransactions(this.walletLocalData.publicKey).minRound(e).nextToken(s!=null?s:"").do();return f(P)}))),{"next-token":a,transactions:c}=i;if(c.length===0)break;for(const u of c){if(n==null&&(n=u.id,o=u["confirmed-round"]),l=u["confirmed-round"],u.id===this.otherData.latestTxid){r=!1;break}try{this.processAlgorandTransaction(u)}catch(g){this.log.warn("processAlgorandTransaction error:",g)}}o=o!=null?o:this.walletLocalData.blockHeight;const d=(o-l)/(o-e);this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=d,this.updateOnAddressesChecked(),s=a}while(s!=null&&r);n!=null&&this.otherData.latestTxid!==n&&(this.otherData.latestTxid=n,this.otherData.latestRound=o,this.walletLocalDataDirty=!0);for(const i of this.enabledTokens)this.tokenCheckTransactionsStatus[i]=1;this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return h(this,null,function*(){this.engineOn=!0,this.addToLoop("queryBalance",oe).catch(()=>{}),this.addToLoop("queryTransactionParams",oe).catch(()=>{}),this.addToLoop("queryTransactions",Ce).catch(()=>{}),yield ve(te.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return h(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}calcFee(e){const n=e.estimateSize();return Math.max(this.suggestedTransactionParams.fee*n,this.networkInfo.minimumTxFee).toString()}getMaxSpendable(e){return h(this,null,function*(){let n=this.getBalance({currencyCode:e.currencyCode});if(e.currencyCode===this.currencyInfo.currencyCode&&(n=(0,w.sub)(n,this.totalReserve)),e.spendTargets[0].publicAddress==null)throw new Error("makeSpend Missing publicAddress");const{customNetworkFee:l}=e;let r=p(l).fee;r==null&&(e.spendTargets[0].nativeAmount="1",r=(yield this.makeSpend(e)).networkFee);const i=(a,c)=>h(this,null,function*(){const d=(0,w.sub)(c,a);if((0,w.lte)(d,"1"))return a;const u=(0,w.add)(a,(0,w.div)(d,"2"));e.spendTargets[0].nativeAmount=u;const g=(0,w.add)(u,r!=null?r:this.networkInfo.minimumTxFee.toString());return(0,w.gt)(g,n)?yield i(a,u):yield i(u,c)});return yield i("0",(0,w.add)(n,"1"))})}makeSpend(e){return h(this,null,function*(){var n,o,l;const{edgeSpendInfo:s,currencyCode:r,nativeBalance:i}=this.makeSpendCheck(e),a=(0,w.sub)(this.getBalance({currencyCode:this.currencyInfo.currencyCode}),this.totalReserve);if(s.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:c,memo:d,publicAddress:u}=s.spendTargets[0];if(u==null)throw new Error("makeSpend Missing publicAddress");if(c==null)throw new R.$D;const{type:g}=(n=(0,t.Vk)(I)(s.otherParams))!=null?n:{type:r===this.currencyInfo.currencyCode?"pay":"axfer"};let P;d!=null&&(P=Uint8Array.from(he.from(d,"ascii")));const{customNetworkFee:k}=s,b=p(k).fee;let C,A=c,U="0",M,O,ce;switch(g){case"pay":{if(C=v.ZP.makePaymentTxnWithSuggestedParamsFromObject({to:u,from:this.walletInfo.keys.publicKey,amount:BigInt(c),note:P,suggestedParams:L({},this.suggestedTransactionParams)}),O=b!=null?b:this.calcFee(C),U=O,A=`-${(0,w.add)(A,U)}`,ce=u,(0,w.gt)((0,w.abs)(A),a))throw new R.C_;break}case"axfer":{const le=Object.keys(this.allTokensMap).find(Se=>this.allTokensMap[Se].currencyCode===r);if(le==null)throw new Error("Unrecognized asset");const ue=H((l=(o=this.allTokensMap)==null?void 0:o[le])==null?void 0:l.networkLocation);if(ue==null)throw new Error("Unrecognized asset");if(C=v.ZP.makeAssetTransferTxnWithSuggestedParamsFromObject({assetIndex:parseInt(ue.contractAddress),to:u,from:this.walletInfo.keys.publicKey,amount:BigInt(c),note:P,suggestedParams:L({},this.suggestedTransactionParams)}),O=b!=null?b:this.calcFee(C),A=`-${A}`,M=O,(0,w.gt)(M,a))throw new R.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:O});if((0,w.gt)((0,w.abs)(A),i))throw new R.C_;break}default:throw new Error("Unrecognized transaction type")}C.flatFee=!0,C.fee=parseInt(O);const Ee={encodedTx:D.YU.stringify((0,v.nJ)(C)),recipient:ce};return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:A,isSend:!0,networkFee:U,ourReceiveAddresses:[],parentNetworkFee:M,signedTx:"",otherParams:Ee,walletId:this.walletId}})}signMessage(e,n){return h(this,null,function*(){const o=E(this.currencyInfo.pluginId)(n),l=(0,v.wj)(D.US.parse(e)),s=v.ZP.mnemonicToSecretKey(o.mnemonic),r=l.signTxn(s.sk);return D.US.stringify(r)})}signTx(e,n){return h(this,null,function*(){const{encodedTx:o,recipient:l}=x((0,S.Xp)(e)),s=(0,v.wj)(Uint8Array.from(D.YU.parse(o)));l!=null&&(yield this.checkRecipientMinimumBalance(this.getRecipientBalance,s.amount.toString(),l));const r=E(this.currencyInfo.pluginId)(n),i=v.ZP.mnemonicToSecretKey(r.mnemonic),a=s.signTxn(i.sk),c=D.YU.stringify(a);return e.signedTx=c,e})}broadcastTx(e){return h(this,null,function*(){const n=Uint8Array.from(D.YU.parse(e.signedTx));try{const{txId:o}=yield(0,S.QJ)(this.networkInfo.algodServers.map(l=>()=>h(this,null,function*(){return yield new ee("",l,"").sendRawTransaction(n).do()})));e.txid=o,e.date=Date.now()/1e3}catch(o){throw this.warn("FAILURE broadcastTx failed: ",o),o}return this.warn(`SUCCESS broadcastTx
1
+ (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[741],{37011:function(de,_,m){"use strict";m.r(_),m.d(_,{AlgorandTools:function(){return ie},makeCurrencyEngine:function(){return Ae},makeCurrencyTools:function(){return be}});var v=m(88814),w=m(77591),Z=m(20918),X=m(79014),S=m(76714),t=m(82448),F=m(62177);const j=(0,t.su)({latestRound:(0,t.Vk)(t.mH,0),latestTxid:(0,t.Vk)(t.XC,"")}),z=(0,t.su)({amount:t.mH,assets:(0,t._2)((0,t.su)({amount:t.mH,"asset-id":t.mH})),"min-balance":t.mH,round:t.mH}),Q=(0,t.su)({"confirmed-round":t.mH,fee:t.mH,"first-valid":t.mH,id:t.XC,note:(0,t.Zz)(t.XC),"round-time":t.mH,sender:t.XC,"tx-type":t.XC}).withRest,K=(0,t.Wf)("pay"),V=(0,t.su)({"payment-transaction":(0,t.su)({amount:t.mH,"close-amount":t.mH,receiver:t.XC}),"tx-type":K}),G=(0,t.Wf)("axfer"),J=(0,t.su)({"asset-transfer-transaction":(0,t.su)({amount:t.mH,"asset-id":t.mH}),"tx-type":G}),f=(0,t.su)({"current-round":t.mH,"next-token":(0,t.Zz)(t.XC),transactions:(0,t._2)(Q)}),T=(0,t.su)({flatFee:t.jK,fee:t.mH,firstRound:t.mH,lastRound:t.mH,genesisID:t.XC,genesisHash:t.XC}),I=(0,t.su)({type:t.XC}).withRest,x=(0,t.su)({encodedTx:t.XC,recipient:(0,t.Zz)(t.XC)}),q=(0,t.su)({type:K,to:t.XC,amount:t.mH}).withRest,p=(0,t.Vk)((0,t.su)({fee:(0,t.Zz)(t.XC)}),{fee:void 0}),H=(0,t.Vk)((0,t.su)({contractAddress:F.jD})),ne=F.BQ,E=y=>{const e=(0,t.su)({[`${y}Mnemonic`]:t.XC});return(0,t.W1)(n=>({mnemonic:e(n)[`${y}Mnemonic`]}),n=>({[`${y}Mnemonic`]:n.mnemonic}))},Y=(0,t.su)({id:(0,t._C)(t.XC,t.mH),method:(0,t.Wf)("algo_signTxn"),params:(0,t.vq)((0,t.vq)((0,t.su)({txn:t.XC,message:(0,t.Zz)(t.XC)})))}),N=(0,t.su)({id:t.mH,jsonrpc:(0,t.Wf)("2.0"),method:(0,t.Wf)("algo_signTxn"),params:(0,t.vq)((0,t.vq)((0,t.su)({txn:t.XC,message:(0,t.Zz)(t.XC)})))}).withRest;var $=m(12614),R=m(94935),D=m(35620),W=m(50244),he=m(48764).Buffer,fe=Object.defineProperty,ye=Object.defineProperties,me=Object.getOwnPropertyDescriptors,se=Object.getOwnPropertySymbols,pe=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty,we=Object.prototype.propertyIsEnumerable,Te=Reflect.get,re=(y,e,n)=>e in y?fe(y,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):y[e]=n,L=(y,e)=>{for(var n in e||(e={}))ge.call(e,n)&&re(y,n,e[n]);if(se)for(var n of se(e))we.call(e,n)&&re(y,n,e[n]);return y},Ie=(y,e)=>ye(y,me(e)),ve=(y,e,n)=>Te(pe(y),n,e),h=(y,e,n)=>new Promise((o,l)=>{var s=a=>{try{i(n.next(a))}catch(c){l(c)}},r=a=>{try{i(n.throw(a))}catch(c){l(c)}},i=a=>a.done?o(a.value):Promise.resolve(a.value).then(s,r);i((n=n.apply(y,e)).next())});const{Algodv2:ee,Indexer:Ce}=v.ZP,oe=5e3,ke=3e3;class te extends W.P{constructor(e,n,o,l){super(e,n,o,l),this.getRecipientBalance=s=>h(this,null,function*(){try{return(yield this.fetchAccountInfo(s)).amount.toString()}catch{return this.minimumAddressBalance}}),this.engineGetActivationAssets=s=>h(this,null,function*(){return{assetOptions:[{paymentWalletId:this.walletId,currencyPluginId:this.currencyInfo.pluginId}]}}),this.engineActivateWallet=s=>h(this,[s],function*({activateTokenIds:r,paymentTokenId:i,paymentWallet:a}){var c;if(r==null)throw new Error(`Must specify activateTokenIds for ${this.currencyInfo.currencyCode}`);if(i!=null)throw new Error(`Must activate with ${this.currencyInfo.currencyCode}`);if((a==null?void 0:a.id)!==this.walletId)throw new Error("Must pay with same wallet you are activating token with");const d=this.networkInfo.minimumTxFee.toFixed();let u="0";const g=[];for(const C of r){if(this.allTokensMap[C]==null)throw new Error(`Invalid tokenId to activate ${C}`);const b={currencyCode:this.allTokensMap[C].currencyCode,skipChecks:!0,spendTargets:[{publicAddress:this.walletInfo.keys.publicKey,nativeAmount:"0"}]};try{const k=yield this.makeSpend(b);u=(0,w.add)(u,(c=k.parentNetworkFee)!=null?c:d)}catch{u=(0,w.add)(u,d)}g.push(b)}return{paymentWalletId:this.walletId,fromNativeAmount:"0",networkFee:{nativeAmount:u,currencyPluginId:this.currencyInfo.pluginId},approve:(...C)=>h(this,[...C],function*(b={}){const{metadata:k}=b,A=[];for(const U of g){const M=yield this.makeSpend(U);M.metadata=L({},k);let O=yield a.signTx(M);O=yield a.broadcastTx(O),A.push(O),yield a.saveTx(O)}return{transactions:A}}),close:()=>h(this,null,function*(){})}}),this.networkInfo=e.networkInfo,this.queryTxMutex=(0,S.jT)(),this.suggestedTransactionParams={flatFee:!1,fee:0,firstRound:0,lastRound:0,genesisID:this.networkInfo.genesisID,genesisHash:this.networkInfo.genesisHash},this.minimumAddressBalance=this.networkInfo.minimumAddressBalance,this.totalReserve=this.minimumAddressBalance,this.otherMethods={wcInit:(s,r="Edge")=>h(this,null,function*(){return yield(0,S.Vs)(new Promise((i,a)=>{const c=new $.Z({uri:s.uri,storageId:s.uri,clientMeta:{description:"Edge Wallet",url:"https://www.edge.app",icons:["https://content.edge.app/Edge_logo_Icon.png"],name:r}});c.on("session_request",(d,u)=>{if(d!=null)throw this.error("Wallet connect session_request",d),d;const g=(0,F.ff)(u).params[0],P=Ie(L({},g),{timeConnected:Date.now()/1e3});this.tools.walletConnectors[s.uri]={connector:c,wcProps:s,dApp:P},i(P)}),c.on("call_request",(d,u)=>{try{if(d!=null)throw d;const g=N(u),P=g.params[0][0],C=(0,v.wj)(D.US.parse(P.txn)),b=C.amount!=null?C.amount.toString():"0",k=C.fee.toFixed();let A;if(C.type==="axfer"){const M=C.assetIndex.toString();if(this.allTokensMap[M]==null)throw new Error("Unrecognized token");A=M}const U={uri:s.uri,dApp:this.tools.walletConnectors[s.uri].dApp,payload:g,walletId:this.tools.walletConnectors[s.uri].walletId,nativeAmount:b,networkFee:k,tokenId:A};this.currencyEngineCallbacks.onWcNewContractCall(U)}catch(g){throw this.warn("Wallet connect call_request ",g),g}}),c.on("disconnect",(d,u)=>{if(d!=null)throw d;delete this.tools.walletConnectors[s.uri]})}),5e3)}),wcConnect:(s,r,i)=>{this.tools.walletConnectors[s].connector.approveSession({accounts:[r],chainId:416001}),this.tools.walletConnectors[s].walletId=i},wcDisconnect:s=>{var r;((r=this.tools.walletConnectors[s])==null?void 0:r.connector)!=null&&(this.tools.walletConnectors[s].connector.killSession().catch(()=>{}),delete this.tools.walletConnectors[s])},wcApproveRequest:(s,r,i)=>h(this,null,function*(){this.tools.walletConnectors[s].connector.approveRequest({id:Number(r.id),jsonrpc:"2.0",result:[i]})}),wcRejectRequest:(s,r)=>h(this,null,function*(){this.tools.walletConnectors[s].connector.rejectRequest({id:Number(r.id),jsonrpc:"2.0",error:{message:"rejected"}})}),wcGetConnections:()=>Object.keys(this.tools.walletConnectors).filter(s=>this.tools.walletConnectors[s].walletId===this.walletInfo.id).map(s=>L(L({},this.tools.walletConnectors[s].dApp),this.tools.walletConnectors[s].wcProps))}}setOtherData(e){this.otherData=j(e)}fetchAccountInfo(e){return h(this,null,function*(){return yield(0,S.QJ)(this.networkInfo.algodServers.map(n=>()=>h(this,null,function*(){const l=yield new ee("",n,"").accountInformation(e).do();return z(l)})))})}queryBalance(){return h(this,null,function*(){try{const e=yield this.fetchAccountInfo(this.walletLocalData.publicKey),{assets:n,amount:o,"min-balance":l,round:s}=e;this.totalReserve=l.toString();const r=[];for(const i of this.enabledTokens)if(i===this.currencyInfo.currencyCode)this.updateBalance(this.currencyInfo.currencyCode,o.toString());else{const a=Object.keys(this.allTokensMap).find(d=>this.allTokensMap[d].currencyCode===i);if(a==null){this.updateBalance(i,"0");continue}const c=n.find(d=>d["asset-id"].toFixed()===a);if(c==null){r.push(a),this.updateBalance(i,"0");continue}this.updateBalance(i,c.amount.toString())}s>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=s,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight)),(0,S.dQ)(r,this.walletLocalData.unactivatedTokenIds)||(this.walletLocalData.unactivatedTokenIds=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onUnactivatedTokenIdsChanged(this.walletLocalData.unactivatedTokenIds))}catch(e){this.log.warn("queryBalance Error ",e)}})}queryTransactionParams(){return h(this,null,function*(){try{const e=yield(0,S.QJ)(this.networkInfo.algodServers.map(n=>()=>h(this,null,function*(){const l=yield new ee("",n,"").getTransactionParams().do(),s=T(l);if(s.genesisHash!==this.networkInfo.genesisHash)throw new Error("Server genesisHash mismatch");return s})));this.suggestedTransactionParams=e}catch(e){this.log.warn("queryTransactionParams error:",e)}})}processAlgorandTransaction(e){const{fee:n,"confirmed-round":o,id:l,"round-time":s,sender:r,"tx-type":i}=e;let a,c,d,u,g=!1;const P=[];switch(i){case"pay":{const{amount:b}=V(e)["payment-transaction"];c=b.toString(),d=n.toString(),r===this.walletInfo.keys.publicKey?(c=`-${(0,w.add)(c,d)}`,g=!0):(d="0",P.push(this.walletInfo.keys.publicKey)),a=this.currencyInfo.currencyCode;break}case"axfer":{const{amount:b,"asset-id":k}=J(e)["asset-transfer-transaction"];c=b.toString(),d="0",r===this.walletInfo.keys.publicKey?(c=`-${c}`,u=n.toString(),g=!0):P.push(this.walletInfo.keys.publicKey);const A=this.allTokensMap[k];if(A==null)return;a=A.currencyCode;break}default:return}const C={txid:l,date:s,currencyCode:a,blockHeight:o,nativeAmount:c,isSend:g,networkFee:d,ourReceiveAddresses:P,parentNetworkFee:u,signedTx:"",walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,C)}queryTransactions(){return h(this,null,function*(){return yield this.queryTxMutex(()=>h(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return h(this,null,function*(){const e=this.otherData.latestRound;let n,o=this.otherData.latestRound,l=0,s,r=!0;do{const i=yield(0,S.QJ)(this.networkInfo.indexerServers.map(u=>()=>h(this,null,function*(){const P=yield new Ce({},u,"").lookupAccountTransactions(this.walletLocalData.publicKey).minRound(e).nextToken(s!=null?s:"").do();return f(P)}))),{"next-token":a,transactions:c}=i;if(c.length===0)break;for(const u of c){if(n==null&&(n=u.id,o=u["confirmed-round"]),l=u["confirmed-round"],u.id===this.otherData.latestTxid){r=!1;break}try{this.processAlgorandTransaction(u)}catch(g){this.log.warn("processAlgorandTransaction error:",g)}}o=o!=null?o:this.walletLocalData.blockHeight;const d=(o-l)/(o-e);this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=d,this.updateOnAddressesChecked(),s=a}while(s!=null&&r);n!=null&&this.otherData.latestTxid!==n&&(this.otherData.latestTxid=n,this.otherData.latestRound=o,this.walletLocalDataDirty=!0);for(const i of this.enabledTokens)this.tokenCheckTransactionsStatus[i]=1;this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return h(this,null,function*(){this.engineOn=!0,this.addToLoop("queryBalance",oe).catch(()=>{}),this.addToLoop("queryTransactionParams",oe).catch(()=>{}),this.addToLoop("queryTransactions",ke).catch(()=>{}),yield ve(te.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return h(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}calcFee(e){const n=e.estimateSize();return Math.max(this.suggestedTransactionParams.fee*n,this.networkInfo.minimumTxFee).toString()}getMaxSpendable(e){return h(this,null,function*(){let n=this.getBalance({currencyCode:e.currencyCode});if(e.currencyCode===this.currencyInfo.currencyCode&&(n=(0,w.sub)(n,this.totalReserve)),e.spendTargets[0].publicAddress==null)throw new Error("makeSpend Missing publicAddress");const{customNetworkFee:l}=e;let r=p(l).fee;r==null&&(e.spendTargets[0].nativeAmount="1",r=(yield this.makeSpend(e)).networkFee);const i=(a,c)=>h(this,null,function*(){const d=(0,w.sub)(c,a);if((0,w.lte)(d,"1"))return a;const u=(0,w.add)(a,(0,w.div)(d,"2"));e.spendTargets[0].nativeAmount=u;const g=(0,w.add)(u,r!=null?r:this.networkInfo.minimumTxFee.toString());return(0,w.gt)(g,n)?yield i(a,u):yield i(u,c)});return yield i("0",(0,w.add)(n,"1"))})}makeSpend(e){return h(this,null,function*(){var n,o,l;const{edgeSpendInfo:s,currencyCode:r,nativeBalance:i}=this.makeSpendCheck(e),a=(0,w.sub)(this.getBalance({currencyCode:this.currencyInfo.currencyCode}),this.totalReserve);if(s.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:c,memo:d,publicAddress:u}=s.spendTargets[0];if(u==null)throw new Error("makeSpend Missing publicAddress");if(c==null)throw new R.$D;const{type:g}=(n=(0,t.Vk)(I)(s.otherParams))!=null?n:{type:r===this.currencyInfo.currencyCode?"pay":"axfer"};let P;d!=null&&(P=Uint8Array.from(he.from(d,"ascii")));const{customNetworkFee:C}=s,b=p(C).fee;let k,A=c,U="0",M,O,ce;switch(g){case"pay":{if(k=v.ZP.makePaymentTxnWithSuggestedParamsFromObject({to:u,from:this.walletInfo.keys.publicKey,amount:BigInt(c),note:P,suggestedParams:L({},this.suggestedTransactionParams)}),O=b!=null?b:this.calcFee(k),U=O,A=`-${(0,w.add)(A,U)}`,ce=u,(0,w.gt)((0,w.abs)(A),a))throw new R.C_;break}case"axfer":{const le=Object.keys(this.allTokensMap).find(Se=>this.allTokensMap[Se].currencyCode===r);if(le==null)throw new Error("Unrecognized asset");const ue=H((l=(o=this.allTokensMap)==null?void 0:o[le])==null?void 0:l.networkLocation);if(ue==null)throw new Error("Unrecognized asset");if(k=v.ZP.makeAssetTransferTxnWithSuggestedParamsFromObject({assetIndex:parseInt(ue.contractAddress),to:u,from:this.walletInfo.keys.publicKey,amount:BigInt(c),note:P,suggestedParams:L({},this.suggestedTransactionParams)}),O=b!=null?b:this.calcFee(k),A=`-${A}`,M=O,(0,w.gt)(M,a))throw new R.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:O});if((0,w.gt)((0,w.abs)(A),i))throw new R.C_;break}default:throw new Error("Unrecognized transaction type")}k.flatFee=!0,k.fee=parseInt(O);const Ee={encodedTx:D.YU.stringify((0,v.nJ)(k)),recipient:ce};return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:A,isSend:!0,networkFee:U,ourReceiveAddresses:[],parentNetworkFee:M,signedTx:"",otherParams:Ee,walletId:this.walletId}})}signMessage(e,n){return h(this,null,function*(){const o=E(this.currencyInfo.pluginId)(n),l=(0,v.wj)(D.US.parse(e)),s=v.ZP.mnemonicToSecretKey(o.mnemonic),r=l.signTxn(s.sk);return D.US.stringify(r)})}signTx(e,n){return h(this,null,function*(){const{encodedTx:o,recipient:l}=x((0,S.Xp)(e)),s=(0,v.wj)(Uint8Array.from(D.YU.parse(o)));l!=null&&(yield this.checkRecipientMinimumBalance(this.getRecipientBalance,s.amount.toString(),l));const r=E(this.currencyInfo.pluginId)(n),i=v.ZP.mnemonicToSecretKey(r.mnemonic),a=s.signTxn(i.sk),c=D.YU.stringify(a);return e.signedTx=c,e})}broadcastTx(e){return h(this,null,function*(){const n=Uint8Array.from(D.YU.parse(e.signedTx));try{const{txId:o}=yield(0,S.QJ)(this.networkInfo.algodServers.map(l=>()=>h(this,null,function*(){return yield new ee("",l,"").sendRawTransaction(n).do()})));e.txid=o,e.date=Date.now()/1e3}catch(o){throw this.warn("FAILURE broadcastTx failed: ",o),o}return this.warn(`SUCCESS broadcastTx
2
2
  ${(0,S.oX)(e)}`),e})}getDisplayPrivateSeed(e){return E(this.currencyInfo.pluginId)(e).mnemonic}getDisplayPublicSeed(){var e;return(e=this.walletInfo.keys.publicKey)!=null?e:""}}function Ae(y,e,n,o){return h(this,null,function*(){const l=ne(n),s=new te(y,e,l,o);return yield s.loadEngine(e,l,o),s})}var xe=m(48764).Buffer,B=(y,e,n)=>new Promise((o,l)=>{var s=a=>{try{i(n.next(a))}catch(c){l(c)}},r=a=>{try{i(n.throw(a))}catch(c){l(c)}},i=a=>a.done?o(a.value):Promise.resolve(a.value).then(s,r);i((n=n.apply(y,e)).next())});const{isValidAddress:ae,mnemonicFromSeed:Pe}=v.ZP;class ie{constructor(e){const{builtinTokens:n,currencyInfo:o,io:l}=e;this.io=l,this.currencyInfo=o,this.builtinTokens=n,this.walletConnectors={}}importPrivateKey(e){return B(this,null,function*(){const{pluginId:n}=this.currencyInfo;return v.ZP.mnemonicToSecretKey(e),{[`${n}Mnemonic`]:e}})}createPrivateKey(e){return B(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const n=xe.from(this.io.random(32)),o=Pe(n);return yield this.importPrivateKey(o)})}derivePublicKey(e){return B(this,null,function*(){const{pluginId:n}=this.currencyInfo;if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const o=E(n)(e.keys);return{publicKey:v.ZP.mnemonicToSecretKey(o.mnemonic).addr}})}parseUri(e,n,o){return B(this,null,function*(){const{pluginId:l}=this.currencyInfo,s={[l]:!0,wc:!0},{parsedUri:r,edgeParsedUri:i}=(0,X.k)(this.currencyInfo,e,s,n!=null?n:this.currencyInfo.currencyCode,o);if(r.protocol==="wc"){if(r.query.bridge!=null&&r.query.key!=null)return i.walletConnect={uri:e,topic:r.pathname.split("@")[0],version:r.pathname.split("@")[1],bridge:r.query.bridge,key:r.query.key},i;throw new Error("MissingWcBridgeKey")}let a="";if(i.publicAddress!=null&&(a=i.publicAddress),!ae(a))throw new Error("InvalidPublicAddressError");return i.uniqueIdentifier=r.query.memo,i})}encodeUri(e,n){return B(this,null,function*(){const{pluginId:o}=this.currencyInfo,{nativeAmount:l,currencyCode:s,publicAddress:r}=e;if(!ae(r))throw new Error("InvalidPublicAddressError");let i;if(typeof l=="string"){const c=(0,S.cp)(this.currencyInfo,s!=null?s:this.currencyInfo.currencyCode,n);if(c==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,w.div)(l,c.multiplier,18)}return(0,X.Q)(e,o,i)})}getTokenId(e){return B(this,null,function*(){(0,Z.Rp)(e);const n=H(e.networkLocation);if(n==null)throw new Error("ErrorInvalidContractAddress");return n.contractAddress})}}function be(y){return B(this,null,function*(){return new ie(y)})}},79014:function(de,_,m){"use strict";m.d(_,{Q:function(){return J},k:function(){return G}});var v=m(77591),w=m.n(v),Z=m(24350),X=m(84564),S=m.n(X),t=m(76714),F=Object.defineProperty,j=Object.getOwnPropertySymbols,z=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,K=(f,T,I)=>T in f?F(f,T,{enumerable:!0,configurable:!0,writable:!0,value:I}):f[T]=I,V=(f,T)=>{for(var I in T||(T={}))z.call(T,I)&&K(f,I,T[I]);if(j)for(var I of j(T))Q.call(T,I)&&K(f,I,T[I]);return f};function G(f,T,I,x,q){const p=V({},S()(T,{},!0)),H=T.startsWith(`${f.pluginId}://`);if(p.protocol!=null&&(p.protocol=p.protocol.replace(":","")),p.protocol!=null&&p.protocol!==""&&!I[p.protocol])throw new Error(`Uri protocol '${p.protocol}' is not supported for ${f.pluginId}.`);if(p.host===""&&p.pathname==="")throw new Error("Path and host not found in uri.");const E={publicAddress:p.host!==""?p.host:p.pathname.split("/")[0]},Y=p.query.label,N=p.query.message,$=p.query.category;(Y!=null||N!=null||$!=null||H)&&(E.metadata={},E.metadata.name=Y,E.metadata.notes=N,E.metadata.category=$,E.metadata.gateway=H!=null?H:!1);const R=p.query.amount;if(R!=null&&typeof R=="string"){x==null&&(x=f.currencyCode);const D=(0,t.cp)(f,x!=null?x:"",q);if(D==null)throw new Error("InternalErrorInvalidCurrencyCode");let W=(0,v.mul)(R,D.multiplier);W=(0,v.toFixed)(W,0,0),E.nativeAmount=W,E.currencyCode=x}return{edgeParsedUri:E,parsedUri:p}}function J(f,T,I){if(f.publicAddress==null)throw new Error("InvalidPublicAddressError");if(I==null&&f.label==null&&f.message==null)return f.publicAddress;{let x="";I!=null&&(x+="amount="+I+"&"),(f.label!=null||f.message!=null)&&(typeof f.label=="string"&&(x+="label="+f.label+"&"),typeof f.message=="string"&&(x+="message="+f.message+"&")),x=x.substr(0,x.length-1);const q={scheme:T,path:f.publicAddress,query:x};return(0,Z.qC)(q)}}},55024:function(){}}]);
@@ -6,6 +6,6 @@ Invalid return value ${JSON.stringify(e)}
6
6
  ${(0,f.oX)(s)}`),new Error("Invalid return value on transaction send")}multicastServers(e,...t){return E(this,null,function*(){const{rpcServers:s,blockcypherApiServers:o,evmScanApiServers:i,blockbookServers:l,chainParams:{chainId:a}}=this.ethEngine.networkInfo;let h={result:"",server:"no server"},r,u;switch(e){case"broadcastTx":{const c=[];s.forEach(d=>{const g=U()(d,{},!0);c.push(we(this.broadcastRPC(t[0],a,d),g.hostname))}),i.forEach(d=>{c.push(we(this.broadcastEtherscan(t[0],d),"etherscan"))}),l.forEach(d=>{c.push(we(this.broadcastBlockbook(t[0],d),"blockbook"))}),o.forEach(d=>{c.push(we(this.broadcastBlockCypher(t[0],d),"blockcypher"))}),h=yield(0,f.Wp)(c),this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} multicastServers ${e} ${h.server} won`);break}case"eth_blockNumber":r=i.map(c=>()=>E(this,null,function*(){if(!c.includes("etherscan")&&!c.includes("blockscout"))throw new Error(`Unsupported command eth_blockNumber in ${c}`);let d="?module=proxy&action=eth_blockNumber";c.includes("blockscout")&&(d="?module=block&action=eth_block_number");const g=yield this.fetchGetEtherscan(c,d);if(typeof g.result!="string"){const y=`Invalid return value eth_blockNumber in ${c}`;throw this.ethEngine.error(y),new Error(y)}return{server:c,result:g}})),r.push(...s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_blockNumber",[],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${c} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_blockNumber response object included an error");return{server:U()(c).hostname,result:d}}))),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_estimateGas":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_estimateGas",t[0],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_estimateGas response object from ${c} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_estimateGas response object included an error");return{server:U()(c).hostname,result:d}})),h=yield(0,f.QJ)(r);break;case"eth_getTransactionReceipt":case"rollup_gasPrices":case"eth_getCode":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC(e,t[0],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful ${e} response object from ${c} included an error ${d.error}`),new Error(`Successful ${e} response object included an error`);return{server:U()(c).hostname,result:d}})),h=yield(0,f.QJ)(r);break;case"eth_getTransactionCount":u=`?module=proxy&action=eth_getTransactionCount&address=${t[0]}&tag=latest`,r=i.map(c=>()=>E(this,null,function*(){if(!c.includes("etherscan")&&!c.includes("blockscout"))throw new Error(`Unsupported command eth_getTransactionCount in ${c}`);const d=yield this.fetchGetEtherscan(c,u);if(typeof d.result!="string"){const g=`Invalid return value eth_getTransactionCount in ${c}`;throw this.ethEngine.error(g),new Error(g)}return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_getTransactionCount_RPC":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_getTransactionCount",[t[0],"latest"],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${c} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:U()(c).hostname,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_getBalance":u=`?module=account&action=balance&address=${t[0]}&tag=latest`,r=i.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetEtherscan(c,u);if(!d.result||typeof d.result!="string"){const g=`Invalid return value eth_getBalance in ${c}`;throw this.ethEngine.error(g),new Error(g)}return{server:c,result:d}})),r.push(...s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_getBalance",[t[0],"latest"],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_getBalance response object from ${c} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_getBalance response object included an error");if(!(0,f.vq)(d.result))throw new Error(`eth_getBalance not hex for ${U()(c).hostname}`);return d.result=(0,f.Z8)(d.result),{server:U()(c).hostname,result:d}}))),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"getTokenBalance":u=`?module=account&action=tokenbalance&contractaddress=${t[1]}&address=${t[0]}&tag=latest`,r=i.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetEtherscan(c,u);if(!d.result||typeof d.result!="string"){const g=`Invalid return value getTokenBalance in ${c}`;throw this.ethEngine.error(g),new Error(g)}return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"getTransactions":{const{currencyCode:c,address:d,startBlock:g,page:y,offset:k,contractAddress:w,searchRegularTxs:b}=t[0];let v;c===this.ethEngine.currencyInfo.currencyCode?v=`?action=${b?"txlist":"txlistinternal"}&module=account`:v=`?action=tokentx&contractaddress=${w}&module=account`,u=`${v}&address=${d}&startblock=${g}&endblock=999999999&sort=asc&page=${y}&offset=${k}`,r=i.map(C=>()=>E(this,null,function*(){const x=yield this.fetchGetEtherscan(C,u);if(typeof x.result!="object"||typeof x.result.length!="number"){const $=`Invalid return value getTransactions in ${C}`;throw x.result!=="Max rate limit reached"&&this.ethEngine.error($),new Error($)}return{server:C,result:x}})),r=(0,f.Sy)(r),r.length>0?h=yield(0,f.QJ)(r):h=Be(Ne({},h),{result:{result:[]}});break}case"blockbookBlockHeight":r=l.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetBlockbook(c,t[0]);return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"blockbookAddress":r=l.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetBlockbook(c,t[0]);return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_call":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_call",[t[0],"latest"],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_call response object from ${c} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_call response object included an error");return{server:U()(c).hostname,result:d}})),h=yield(0,f.QJ)(r);break}return h})}getBaseFeePerGas(){return E(this,null,function*(){const{rpcServers:e,chainParams:{chainId:t}}=this.ethEngine.networkInfo,s=e.map(o=>()=>E(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],t,o).then(i=>{if(i.error!=null){const a=`multicast get_baseFeePerGas error response from ${o}: ${JSON.stringify(i.error)}`;throw this.ethEngine.warn(a),new Error(a)}return{baseFeePerGas:i.result.baseFeePerGas}})}));return yield(0,f.QJ)(s)})}checkBlockHeightEthscan(){return E(this,null,function*(){const{result:e,server:t}=yield this.multicastServers("eth_blockNumber");return{blockHeight:tt(e).result,server:t}})}checkBlockHeightBlockbook(){return E(this,null,function*(){try{const{result:e,server:t}=yield this.multicastServers("blockbookBlockHeight","/api/v2");return{blockHeight:gt(e).blockbook.bestHeight,server:t}}catch(e){throw this.ethEngine.log("checkBlockHeightBlockbook blockHeight ",e),new Error("checkBlockHeightBlockbook returned invalid JSON")}})}checkBlockHeightBlockchair(){return E(this,null,function*(){try{const e=yield this.fetchGetBlockchair(`/${this.ethEngine.currencyInfo.pluginId}/stats`,!1);return{blockHeight:parseInt(kt(e).data.blocks,10),server:"blockchair"}}catch(e){throw this.logError(e),new Error("checkBlockHeightBlockchair returned invalid JSON")}})}checkBlockHeightAmberdata(){return E(this,null,function*(){try{const e=yield this.fetchPostAmberdataRpc("eth_blockNumber",[]);return{blockHeight:parseInt(ce(e).result,16),server:"amberdata"}}catch(e){throw this.logError("checkBlockHeightAmberdata",e),new Error("checkTxsAmberdata (regular tx) response is invalid")}})}checkNonceRpc(){return E(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount_RPC",e),o=ce(t);if(/0[xX][0-9a-fA-F]+/.test(o.result))return{newNonce:(0,p.add)("0",o.result),server:s};throw new Error("checkNonceRpc returned invalid JSON")})}checkNonceEthscan(){return E(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount",e);return{newNonce:nt(t).result,server:s}})}checkNonceAmberdata(){return E(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey;try{const t=yield this.fetchPostAmberdataRpc("eth_getTransactionCount",[e,"latest"]);return{newNonce:`${parseInt(ce(t).result,16)}`,server:"amberdata"}}catch(t){throw this.logError("checkNonceAmberdata",t),new Error("Amberdata returned invalid JSON")}})}check(e,...t){return E(this,null,function*(){return yield(0,f.QJ)(this.queryFuncs[e].map(s=>()=>E(this,null,function*(){return yield s(...t)}))).catch(s=>({}))})}getAllTxsEthscan(e,t,s,o){return E(this,null,function*(){const i=this.ethEngine.walletLocalData.publicKey;let l=1;const a=[];let h="";const r=o.contractAddress,u=o.searchRegularTxs;for(;;){const c=Xt,d=yield this.multicastServers("getTransactions",{currencyCode:t,address:i,startBlock:e,page:l,offset:c,contractAddress:r,searchRegularTxs:u});h=d.server;const g=d.result.result;for(let y=0;y<g.length;y++)try{const k=s(g[y]),w=yield this.processEvmScanTransaction(k,t);a.push(w)}catch(k){throw this.ethEngine.error(`getAllTxsEthscan ${s.name}
7
7
  ${(0,f.HY)(k)}
8
8
  ${JSON.stringify(g[y])}`),new Error(`getAllTxsEthscan ${s.name} is invalid`)}if(g.length===0)break;l++}return{allTransactions:a,server:h}})}checkTxsEthscan(e){return E(this,null,function*(){const{startBlock:t,currencyCode:s}=e;let o,i;if(s===this.ethEngine.currencyInfo.currencyCode){const a=yield this.getAllTxsEthscan(t,s,ut,{searchRegularTxs:!0}),h=yield this.getAllTxsEthscan(t,s,dt,{searchRegularTxs:!1});o=a.server||h.server,i=[...a.allTransactions,...h.allTransactions]}else{const a=this.ethEngine.getTokenInfo(s);if(a!=null&&typeof a.contractAddress=="string"){const h=a.contractAddress,r=yield this.getAllTxsEthscan(t,s,ht,{contractAddress:h});o=r.server,i=r.allTransactions}else return{}}const l={blockHeight:t,edgeTransactions:i};return{tokenTxs:{[s]:l},server:o}})}getTokenCurrencyCode(e){const t=this.ethEngine.walletLocalData.publicKey;if(e.toLowerCase()===t.toLowerCase())return this.ethEngine.currencyInfo.currencyCode;for(const s of this.ethEngine.enabledTokens){const o=this.ethEngine.getTokenInfo(s);if(o!=null){const i=o.contractAddress;if(e&&typeof i=="string"&&i.toLowerCase()===e.toLowerCase())return s}}}checkAddressBlockbook(e){return E(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey.toLowerCase(),s={newNonce:"0",tokenBal:{},server:""},o="/api/v2/address/"+t+"?&details=tokenBalances",{result:i,server:l}=yield this.multicastServers("blockbookAddress",o);let a;try{a=pt(i)}catch{throw this.ethEngine.error(`checkTxsBlockbook ${l} error BlockbookAddress ${JSON.stringify(i)}`),new Error(`checkTxsBlockbook ${l} returned invalid JSON for BlockbookAddress`)}const{nonce:h,tokens:r,balance:u}=a;s.newNonce=h,s.tokenBal!=null&&(s.tokenBal[this.ethEngine.currencyInfo.currencyCode]=u),s.server=l;for(const c of r)try{const{symbol:d,balance:g}=Ie(c);s.tokenBal[d]=g}catch{throw this.ethEngine.error(`checkTxsBlockbook ${l} BlockbookTokenBalance ${JSON.stringify(c)}`),new Error(`checkTxsBlockbook ${l} returned invalid JSON for BlockbookTokenBalance`)}return s})}checkTokenBalEthscan(e){return E(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey;let s,o,i,l;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",t),o=s.result,i=s.server;else{const a=this.ethEngine.getTokenInfo(e);if(a!=null&&typeof a.contractAddress=="string"){const h=a.contractAddress,r=yield this.multicastServers("getTokenBalance",t,h);o=r.result,i=r.server}}l=ce(o)}catch(a){throw this.ethEngine.error(`checkTokenBalEthscan token ${e} response ${s||""} `,a),new Error(`checkTokenBalEthscan invalid ${e} response ${JSON.stringify(o)}`)}if(/^\d+$/.test(l.result)){const a=l.result;return{tokenBal:{[e]:a},server:i}}else throw new Error(`checkTokenBalEthscan returned invalid JSON for ${e}`)})}checkTokenBalBlockchair(){return E(this,null,function*(){let e;const t=this.ethEngine.walletLocalData.publicKey,s=`/${this.ethEngine.currencyInfo.pluginId}/dashboards/address/${t}?erc_20=true`;try{const i=yield this.fetchGetBlockchair(s,!1);e=yt(i)}catch(i){throw this.logError("checkTokenBalBlockchair",i),new Error("checkTokenBalBlockchair response is invalid")}const o={[this.ethEngine.currencyInfo.currencyCode]:e.data[t].address.balance};for(const i of e.data[t].layer_2.erc_20)try{const l=mt(i),a=l.balance,h=l.token_address,r=l.token_symbol,u=this.ethEngine.getTokenInfo(r);u!=null&&u.contractAddress===h&&(o[r]=a)}catch(l){throw this.ethEngine.error(`checkTokenBalBlockchair tokenData ${(0,f.HY)(l)}
9
- ${JSON.stringify(i)}`),new Error("checkTokenBalBlockchair tokenData is invalid")}return{tokenBal:o,server:"blockchair"}})}checkTokenBalRpc(e){return E(this,null,function*(){let t,s,o,i;const l=this.ethEngine.walletLocalData.publicKey;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",l),o=s.result,i=s.server;else{const a=this.ethEngine.getTokenInfo(e);if(a!=null&&typeof a.contractAddress=="string"){const h={data:`0x70a08231${(0,f.gc)((0,f.KT)(l),32)}`,to:a.contractAddress},r=yield this.multicastServers("eth_call",h),u=r.result.result;if(!u.startsWith("0x"))throw new Error("Invalid return value. Result not hex");r.result.result=(0,f.Z8)(u),o=r.result,i=r.server}}t=ce(o)}catch(a){throw this.ethEngine.error(`checkTokenBalRpc token ${e} response ${s||""} `,a),new Error(`checkTokenBalRpc invalid ${e} response ${JSON.stringify(o)}`)}return{tokenBal:{[e]:t.result},server:i}})}checkAndUpdate(e=0,t,s,o){return E(this,null,function*(){const i=Date.now();if(i-e>t)try{const l=yield o();this.processEthereumNetworkUpdate(i,l,s)}catch(l){this.ethEngine.error("checkAndUpdate ",l)}})}getQueryHeightWithLookback(e){return e>xe?e-xe:0}getQueryDateWithLookback(e){return e>$e?e-$e:0}needsLoop(){return E(this,null,function*(){for(;this.ethEngine.engineOn;){const e=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,$t,e,()=>E(this,null,function*(){return yield this.check("blockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Rt,e,()=>E(this,null,function*(){return yield this.check("nonce")}));const{currencyCode:t}=this.ethEngine.currencyInfo,s=this.ethEngine.enabledTokens;s.includes(t)||s.push(t);for(const o of s)yield this.checkAndUpdate(this.ethNeeds.tokenBalLastChecked[o],Dt,e,()=>E(this,null,function*(){return yield this.check("tokenBal",o)})),yield this.checkAndUpdate(this.ethNeeds.tokenTxsLastChecked[o],_t,e,()=>E(this,null,function*(){return yield this.check("txs",{startBlock:this.getQueryHeightWithLookback(this.ethEngine.walletLocalData.lastTransactionQueryHeight[o]),startDate:this.getQueryDateWithLookback(this.ethEngine.walletLocalData.lastTransactionDate[o]),currencyCode:o})}));yield(0,f.HB)(1e3)}})}processEthereumNetworkUpdate(e,t,s){if(!!t){if(t.blockHeight){this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate blockHeight ${t.server||"no server"} won`);const o=t.blockHeight;this.ethEngine.log(`Got block height ${o||"no blockheight"}`),typeof o=="number"&&this.ethEngine.walletLocalData.blockHeight!==o&&(this.ethNeeds.blockHeightLastChecked=e,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=o,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}if(t.newNonce&&(this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate nonce ${t.server||"no server"} won`),this.ethNeeds.nonceLastChecked=e,this.ethEngine.otherData.nextNonce=t.newNonce,this.ethEngine.walletLocalDataDirty=!0),t.tokenBal!=null){const o=t.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${t.server||"no server"} won`);for(const i of Object.keys(o))this.ethNeeds.tokenBalLastChecked[i]=e,this.ethEngine.updateBalance(i,o[i])}if(t.tokenTxs!=null){const o=t.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${t.server||"no server"} won`);for(const i of Object.keys(o)){this.ethNeeds.tokenTxsLastChecked[i]=e,this.ethEngine.tokenCheckTransactionsStatus[i]=1;const l=o[i];if(l.edgeTransactions){for(const a of l.edgeTransactions)this.ethEngine.addTransaction(i,a);this.ethEngine.walletLocalData.lastTransactionQueryHeight[i]=s,this.ethEngine.walletLocalData.lastTransactionDate[i]=e}}this.ethEngine.updateOnAddressesChecked()}this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}}buildQueryFuncs(e){const{rpcServers:t,evmScanApiServers:s,blockbookServers:o,blockchairApiServers:i,amberdataRpcServers:l,amberdataApiServers:a}=e,h=[],r=[],u=[],c=[];return s.length>0&&(h.push(this.checkBlockHeightEthscan),r.push(this.checkNonceEthscan),c.push(this.checkTokenBalEthscan)),u.push(this.checkTxsEthscan),o.length>0&&(h.push(this.checkBlockHeightBlockbook),c.push(this.checkAddressBlockbook),r.push(this.checkAddressBlockbook)),i.length>0&&(h.push(this.checkBlockHeightBlockchair),c.push(this.checkTokenBalBlockchair)),l.length>0&&(h.push(this.checkBlockHeightAmberdata),r.push(this.checkNonceAmberdata)),a.length>0,t.length>0&&(r.push(this.checkNonceRpc),c.push(this.checkTokenBalRpc)),{blockheight:h,nonce:r,txs:u,tokenBal:c}}throwError(e,t,s){switch(e.status){case 402:case 429:case 432:throw new Error("rateLimited");default:throw new Error(`${t} The server returned error code ${e.status} for ${s}`)}}logError(e,t){(0,f.HY)(t).includes("rateLimited")?this.ethEngine.log(e,t):this.ethEngine.error(e,t)}}const Kt="low",Gt="standard",jt="high",Re="custom",De="1000000000";function _e(m,e,t,s){var o,i,l,a,h,r,u;let c=!0,d,g;if(m.spendTargets&&m.spendTargets.length>0&&m.spendTargets[0].publicAddress){const{customNetworkFee:y}=m||{};if(m.networkFeeOption===Re&&y!=null){const{gasLimit:T,gasPrice:L}=y;if((isNaN(T)||T==="")&&(isNaN(L)||L==="")){const F=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw F.name="ErrorBelowMinimumFee",F}if(L!=null&&L!==""){const F=(a=(i=(o=e.default)==null?void 0:o.gasPrice)==null?void 0:i.minGasPrice)!=null?a:(l=s.defaultNetworkFees.default.gasPrice)==null?void 0:l.minGasPrice;if(F!=null){const _=(0,p.div)(F,De);if((0,p.lt)(L,_)||/^\s*$/.test(L)){const H=new Error(`Gas Limit: ${T} Gas Price (Gwei): ${L}`);throw H.name="ErrorBelowMinimumFee",H}}g=(0,p.mul)(L,De)}if(T!=null&&T!==""){const F=(u=(r=(h=e.default)==null?void 0:h.gasLimit)==null?void 0:r.minGasLimit)!=null?u:s.defaultNetworkFees.default.gasLimit.minGasLimit;if(F!=null&&(0,p.lt)(T,F)||/^\s*$/.test(T)){const _=new Error(`Gas Limit: ${T} Gas Price (Gwei): ${L}`);throw _.name="ErrorBelowMinimumFee",_}d=T,c=!1}}if(d!=null&&g!=null)return{gasLimit:d,gasPrice:g,useDefaults:!1};const k=(0,f.f0)(m.spendTargets[0].publicAddress);let w=e.default,b=e.default;typeof e[k]<"u"&&(b=e[k],c=!1,typeof b.gasPrice<"u"&&(w=b));let v="regularTransaction";m.currencyCode&&m.currencyCode!==t.currencyCode&&(v="tokenTransaction");let C="standard";typeof m.networkFeeOption=="string"&&m.networkFeeOption!==Re&&(C=m.networkFeeOption);const x=b.gasLimit[v];let $="";if(!m.spendTargets[0].nativeAmount)throw new Error("ErrorInvalidNativeAmount");let X=m.spendTargets[0].nativeAmount;if(v==="tokenTransaction"&&(X=(0,p.div)(X,"10")),w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const B=w.gasPrice;switch(C){case Kt:$=B.lowFee;break;case Gt:{if((0,p.gte)(X,w.gasPrice.standardFeeHighAmount)){$=B.standardFeeHigh;break}if((0,p.lte)(X,B.standardFeeLowAmount)){if(!w.gasPrice)throw new Error("ErrorInvalidGasPrice");$=w.gasPrice.standardFeeLow;break}const T=(0,p.sub)(B.standardFeeHighAmount,B.standardFeeLowAmount),L=(0,p.sub)(B.standardFeeHigh,B.standardFeeLow),F=(0,p.sub)(X,B.standardFeeLowAmount),_=(0,p.mul)(F,L),H=(0,p.div)(_,T);$=(0,p.add)(B.standardFeeLow,H);break}case jt:$=w.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:d!=null?d:x,gasPrice:g!=null?g:$,useDefaults:c}}else throw new Error("ErrorInvalidSpendInfo")}const Mt="1040",Xe=m=>{const{chainParams:e,data:t,dynamicOverhead:s,fixedOverhead:o,gasPriceL1Wei:i,gasLimit:l,nonce:a,to:h,value:r="0x0"}=m,u=J().custom(e),g=A.Transaction.fromTxData({nonce:a!=null?(0,f.X0)(a):void 0,gasPrice:(0,f.X0)(i),gasLimit:(0,f.X0)(l),to:h,value:r,data:t},{common:u}).raw().map(v=>v.toString("hex")).join().match(/(.{1,2})/g);if(g==null)throw new Error("Invalid rawTx string");let y=0;for(let v=0;v<g.length;v++)g[v]==="00"?y+=4:y+=16;const k=(0,p.add)((0,p.add)(y.toString(),o),Mt),w=(0,p.div)(s,"1000000",18);return(0,p.mul)((0,p.mul)(i,k),w)};var Y=P(48764).Buffer,Ut=Object.defineProperty,Jt=Object.defineProperties,Wt=Object.getOwnPropertyDescriptors,He=Object.getOwnPropertySymbols,Zt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty,zt=Object.prototype.propertyIsEnumerable,Qt=Reflect.get,Ke=(m,e,t)=>e in m?Ut(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,V=(m,e)=>{for(var t in e||(e={}))Vt.call(e,t)&&Ke(m,t,e[t]);if(He)for(var t of He(e))zt.call(e,t)&&Ke(m,t,e[t]);return m},ue=(m,e)=>Jt(m,Wt(e)),Ee=(m,e,t)=>Qt(Zt(m),t,e),D=(m,e,t)=>new Promise((s,o)=>{var i=h=>{try{a(t.next(h))}catch(r){o(r)}},l=h=>{try{a(t.throw(h))}catch(r){o(r)}},a=h=>h.done?s(h.value):Promise.resolve(h.value).then(i,l);a((t=t.apply(m,e)).next())});class de extends ye.P{constructor(e,t,s,o,i,l){super(e,t,s,i),this.updateNetworkFeesFromBaseFeePerGas=()=>D(this,null,function*(){var r;const{supportsEIP1559:u=!1}=this.networkInfo;if(!u)return;const{baseFeePerGas:c}=yield this.ethNetwork.getBaseFeePerGas();if(c==null)return;const d=(0,f.Z8)(c),g=this.networkFees;if(g.default==null||g.default.gasPrice==null)return;const y=this.networkInfo.defaultNetworkFees.default,k=g.default.minPriorityFee||y.minPriorityFee,w=(r=g.default.baseFeeMultiplier)!=null?r:y.baseFeeMultiplier;if(k==null||w==null)return;const b={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const v of Object.keys(w)){const C=(0,p.mul)(w[v],d),x=(0,p.add)(C,k);b[v]=(0,p.div)(x,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),ke(this.log,b),b}),this.initOptions=o,this.networkInfo=e.networkInfo,this.ethNetwork=new Ht(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},this.networkInfo.l1RollupParams!=null&&(this.l1RollupParams=this.networkInfo.l1RollupParams),this.networkFees=this.networkInfo.defaultNetworkFees,this.fetchCors=(0,f.zR)(e);const{infoFeeProvider:a,externalFeeProviders:h}=Pt(this.io.fetch,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=a,this.externalFeeProviders=[...h,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:(r,u)=>{if(!(0,f.vq)(r))throw new Error("ErrorInvalidMessage");const c=Y.from(u.privateKey,"hex"),d=(0,f.ah)(r),g=S().hashPersonalMessage(d),{v:y,r:k,s:w}=S().ecsign(g,c);return S().toRpcSig(y,k,w)},signTypedData:(r,u)=>{const c=rt(r),d=Y.from(u.privateKey,"hex"),{types:g}=c;function y(O,T=[]){if(T.includes(O)||g[O]===void 0)return T;T.push(O);for(const L of g[O])for(const F of y(L.type,T))T.includes(F)||T.push(F);return T}function k(O){let T=y(O);T=T.filter(F=>F!==O),T=[O].concat(T.sort());let L="";for(const F of T)L+=`${F}(${g[F].map(({name:_,type:H})=>`${H} ${_}`).join(",")})`;return L}function w(O){return S().keccak256(k(O))}function b(O,T){const L=[],F=[];L.push("bytes32"),F.push(w(O));for(const _ of g[O]){let H=T[_.name];if(_.type==="string"||_.type==="bytes")L.push("bytes32"),H=S().keccak256(H),F.push(H);else if(g[_.type]!==void 0)L.push("bytes32"),H=S().keccak256(b(_.type,H)),F.push(H);else{if(_.type.lastIndexOf("]")===_.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");L.push(_.type),F.push(H)}}return ie().rawEncode(L,F)}function v(O,T){return S().keccak256(b(O,T))}function C(){return S().keccak256(Y.concat([Y.from("1901","hex"),v("EIP712Domain",c.domain),v(c.primaryType,c.message)]))}const x=S().ecsign(C(),d),{v:$,r:X,s:B}=x;return S().bufferToHex(Y.concat([S().setLengthLeft(X,32),S().setLengthLeft(B,32),S().toBuffer($)]))},txRpcParamsToSpendInfo:r=>{const u={otherParams:r};return r.to!=null&&(u.publicAddress=r.to),r.value!=null?u.nativeAmount=(0,f.Z8)(r.value):u.nativeAmount="0",{currencyCode:this.currencyInfo.currencyCode,spendTargets:[u],networkFeeOption:"custom",customNetworkFee:{gasLimit:(0,f.Z8)(r.gas),gasPrice:(0,p.div)((0,f.Z8)(r.gasPrice),Z.toString(),18)},otherParams:r}}},this.otherMethods={txRpcParamsToSpendInfo:r=>D(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(r)}),wcInit:(r,u="Edge")=>D(this,null,function*(){return yield(0,f.Vs)(new Promise((c,d)=>{const g=new N.Z({uri:r.uri,storageId:r.uri,clientMeta:{description:"Edge Wallet",url:"https://www.edge.app",icons:["https://content.edge.app/Edge_logo_Icon.png"],name:u}});g.on("session_request",(y,k)=>{if(y)throw this.error("Wallet connect session_request",y),y;const w=(0,pe.ff)(k).params[0],b=ue(V({},w),{timeConnected:Date.now()/1e3});this.tools.walletConnectors[r.uri]={connector:g,wcProps:r,dApp:b},c(b)}),g.on("call_request",(y,k)=>{try{if(y)throw y;let w="0",b="0";switch(k.method){case"eth_sendTransaction":case"eth_signTransaction":{const C=(0,n.su)({gas:(0,n.Zz)(n.XC),gasPrice:(0,n.Zz)(n.XC),value:(0,n.Zz)(n.XC)})(k.params[0]),{gas:x,gasPrice:$,value:X}=C;X!=null&&(w=(0,f.Z8)(X));let B=this.networkFees.default.gasLimit.tokenTransaction;x==null?k.params[0].gas=(0,f.X0)(B):B=(0,f.Z8)(x);let O=this.networkFees.default.gasPrice.standardFeeHigh;$==null?k.params[0].gasPrice=(0,f.X0)(O):O=(0,f.Z8)($),b=(0,p.mul)(B,O);break}}const v={uri:r.uri,dApp:this.tools.walletConnectors[r.uri].dApp,payload:k,walletId:this.tools.walletConnectors[r.uri].walletId,nativeAmount:w,networkFee:b};this.currencyEngineCallbacks.onWcNewContractCall(v)}catch(w){throw this.warn("Wallet connect call_request ",w),w}}),g.on("disconnect",(y,k)=>{if(y!=null)throw y;delete this.tools.walletConnectors[r.uri]})}),5e3)}),wcConnect:(r,u,c)=>{this.tools.walletConnectors[r].connector.approveSession({accounts:[u],chainId:this.networkInfo.chainParams.chainId}),this.tools.walletConnectors[r].walletId=c},wcDisconnect:r=>{this.tools.walletConnectors[r].connector.killSession().catch(()=>{}),delete this.tools.walletConnectors[r]},wcApproveRequest:(r,u,c)=>D(this,null,function*(){this.tools.walletConnectors[r].connector.approveRequest({id:Number(u.id),jsonrpc:"2.0",result:c})}),wcRejectRequest:(r,u)=>D(this,null,function*(){this.tools.walletConnectors[r].connector.rejectRequest({id:Number(u.id),jsonrpc:"2.0",error:{message:"rejected"}})}),wcGetConnections:()=>Object.keys(this.tools.walletConnectors).filter(r=>this.tools.walletConnectors[r].walletId===this.walletInfo.id).map(r=>V(V({},this.tools.walletConnectors[r].dApp),this.tools.walletConnectors[r].wcProps))}}setOtherData(e){this.otherData=ft(e)}updateNetworkFees(){return D(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const s={};Object.keys(t).forEach(o=>{const i=o;s[i]=(0,f.Y7)(t[i])}),this.networkFees.default.gasPrice!=null&&(this.networkFees.default.gasPrice=V(V({},this.networkFees.default.gasPrice),s));break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}})}updateL1RollupParams(){return D(this,null,function*(){if(this.l1RollupParams!=null){try{const e=yield this.ethNetwork.multicastServers("rollup_gasPrices"),t=Et(e.result.result),{l1GasPrice:s}=t;this.l1RollupParams=ue(V({},this.l1RollupParams),{gasPriceL1Wei:(0,p.ceil)((0,p.mul)((0,f.Z8)(s),this.l1RollupParams.maxGasPriceL1Multiplier),0)})}catch(e){this.log.warn("Failed to update l1GasPrice",e)}try{const e={to:this.l1RollupParams.oracleContractAddress,data:this.l1RollupParams.dynamicOverheadMethod},t=yield this.ethNetwork.multicastServers("eth_call",e),s=ce(t.result);this.l1RollupParams=ue(V({},this.l1RollupParams),{dynamicOverhead:(0,f.Z8)(s.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return D(this,null,function*(){yield Ee(de.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return D(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:ze;this.infoFeeProvider().then(s=>{this.log.warn("infoFeeProvider:",JSON.stringify(s,null,2)),this.networkFees=(0,f.nu)(this.networkFees,s)}).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>D(this,null,function*(){return yield this.addToLoop("updateNetworkFees",t)})),this.addToLoop("updateL1RollupParams",Qe).catch(()=>{}),this.ethNetwork.needsLoop(),Ee(de.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return D(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return D(this,null,function*(){const e=this.walletLocalData.publicKey.toLowerCase(),{publicKey:t}=this.walletLocalData,s=/[A-F]/.test(t)?t:S().toChecksumAddress(t.replace("0x",""));return{legacyAddress:e,publicAddress:s}})}getMaxSpendable(e){return D(this,null,function*(){const t=this.getBalance({currencyCode:e.currencyCode}),s=e.spendTargets[0].publicAddress;if(s==null)throw new Error("makeSpend Missing publicAddress");if(e.currencyCode===this.currencyInfo.currencyCode){const o=(i,l)=>{const a=(0,p.sub)(l,i);if((0,p.lte)(a,"1"))return i;const h=(0,p.add)(i,(0,p.div)(a,"2"));e.spendTargets[0].nativeAmount=h;const{gasPrice:r,gasLimit:u}=_e(e,this.networkFees,this.currencyInfo,this.networkInfo),c=(0,p.mul)(r,u);let d="0";if(this.l1RollupParams!=null){const y={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:u,to:s,value:(0,f.X0)(h),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};d=Xe(y)}const g=(0,p.add)((0,p.add)(h,c),d);return(0,p.gt)(g,t)?o(i,h):o(h,l)};return o("0",(0,p.add)(t,"1"))}else return e.spendTargets[0].nativeAmount=t,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}makeSpend(e){return D(this,null,function*(){var t,s,o,i,l;const{edgeSpendInfo:a,currencyCode:h,skipChecks:r}=this.makeSpendCheck(e),{pendingTxs:u=[]}=a;if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const c=a.spendTargets[0],{publicAddress:d}=c;let{nativeAmount:g}=c;if(d==null)throw new Error("makeSpend Missing publicAddress");if(g==null)throw new I.$D;if(!S().isValidAddress(d))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let y=(s=c.memo)!=null?s:(t=c.otherParams)==null?void 0:t.data;if(y!=null&&y.length>0&&!(0,f.vq)(y))throw new Error("Memo/data field must be of type 'hex'");y===""&&(y=void 0);const k=y!=null;let w;const b=_e(a,this.networkFees,this.currencyInfo,this.networkInfo),v=b.gasPrice;let C=b.gasLimit;const x=b.useDefaults,$=C;let X;if(u.length>0){const z=this.walletLocalData.otherData,re=this.walletLocalData.numUnconfirmedSpendTxs>0?z.unconfirmedNextNonce:z.nextNonce;X=(0,p.add)(re,u.length.toString())}let B,O;if(h===this.currencyInfo.currencyCode)w={from:[this.walletLocalData.publicKey],to:[d],gas:C,gasPrice:v,gasUsed:"0",nonceUsed:X,data:y},O=(0,f.X0)(g);else{if(y)B=d;else{const re=this.getTokenInfo(h);if(re==null||typeof re.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");B=re.contractAddress,O=(0,f.X0)(g);const ve=ie().simpleEncode("transfer(address,uint256):(uint256)",d,O);O="0x0",y="0x"+Y.from(ve).toString("hex")}w={from:[this.walletLocalData.publicKey],to:[B],gas:C,gasPrice:v,gasUsed:"0",tokenRecipientAddress:d,nonceUsed:X,data:y}}if(x&&(this.lastEstimatedGasLimit.publicAddress!==d||this.lastEstimatedGasLimit.contractAddress!==B||this.lastEstimatedGasLimit.gasLimit==="")){const z=[{to:B||d,from:this.walletLocalData.publicKey,gas:"0xffffff",value:O,data:y},"latest"];let re=!1;try{const Ze=(yield this.ethNetwork.multicastServers("eth_getCode",[B||d,"latest"])).result.result!=="0x";try{if(!Ze&&!k)C=this.networkFees.default.gasLimit.regularTransaction;else{const Ve=yield this.ethNetwork.multicastServers("eth_estimateGas",z);C=(0,p.add)(parseInt(Ve.result.result,16).toString(),"0"),Ze&&(C=(0,p.mul)(C,"2"))}re=!0}catch{if(k)throw new Error("Unable to estimate gas limit. Please try again later");this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction!=null&&(C=this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction)}if((0,p.lt)(C,(o=this.networkFees.default.gasLimit.minGasLimit)!=null?o:"21000"))throw C=$,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum");re&&(this.lastEstimatedGasLimit={publicAddress:d,contractAddress:B,gasLimit:C})}catch(ve){this.error("makeSpend Error determining gas limit ",ve)}}else x&&(C=this.lastEstimatedGasLimit.gasLimit);w.gas=C;const T=(i=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?i:"0";let L=(0,p.mul)(v,C),F="0",_=null,H="0";if(this.l1RollupParams!=null){const z={nonce:w.nonceUsed,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:w.gas,to:w.to[0],value:O,data:w.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};H=Xe(z)}if(h===this.currencyInfo.currencyCode){if(L=(0,p.add)(L,H),F=(0,p.add)(L,g),!r&&(0,p.gt)(F,T))throw new I.C_;g=(0,p.mul)(F,"-1")}else{if(_=(0,p.add)(L,H),!r&&(0,p.gt)(L,T))throw new I.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:L});const z=(l=this.walletLocalData.totalBalances[h])!=null?l:"0";if(!r&&(0,p.gt)(g,z))throw new I.C_;L="0",g=(0,p.mul)(g,"-1")}const We={txid:"",date:0,currencyCode:h,blockHeight:0,nativeAmount:g,isSend:g.startsWith("-"),networkFee:L,feeRateUsed:Pe(v,C),ourReceiveAddresses:[],signedTx:"",otherParams:w,walletId:this.walletId};return _&&(We.parentNetworkFee=_),We})}signMessage(e,t,s){return D(this,null,function*(){const o=Ce(this.currencyInfo.pluginId)(t);if(vt(s.otherParams).typedData){const l=JSON.parse(e);try{return this.utils.signTypedData(l,o)}catch{return(0,te.signTypedData_v4)(Y.from(o.privateKey,"hex"),{data:l})}}return this.utils.signMessage(e,o)})}signTx(e,t){return D(this,null,function*(){const s=Ce(this.currencyInfo.pluginId)(t),o=(0,f.Xp)(e),i=(0,f.NC)(o.gas),l=(0,f.NC)(o.gasPrice);let a;if(e.currencyCode===this.currencyInfo.currencyCode){const v=(0,p.add)(e.nativeAmount,e.networkFee);a=(0,p.mul)("-1",v,16)}else a=(0,p.mul)("-1",e.nativeAmount,16);(0,p.lt)(a,"0")&&(a="0x00");let h=o.nonceUsed;if(!h)if(this.walletLocalData.numUnconfirmedSpendTxs&&(0,p.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)){const v=(0,p.sub)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce);if((0,p.lte)(v,"5"))h=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0;else{const C=new Error("Excessive pending spend transactions");throw C.name="ErrorExcessivePendingSpends",C}}else h=this.otherData.nextNonce;const r=(0,f.NC)(h);let u;if(o.data!=null)u=o.data,e.currencyCode!==this.currencyInfo.currencyCode&&(a="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)u="";else{const v=ie().simpleEncode("transfer(address,uint256):(uint256)",o.tokenRecipientAddress,a);u="0x"+Y.from(v).toString("hex"),a="0x00"}const{chainParams:c}=this.networkInfo,d=J().custom(c),g={nonce:r,gasPrice:l,gasLimit:i,to:o.to[0],value:a,data:u},y=Y.from(s.privateKey,"hex"),k=W().fromPrivateKey(y);this.warn(`signTx getAddressString ${k.getAddressString()}`);const b=A.Transaction.fromTxData(g,{common:d}).sign(y);return e.signedTx=(0,f.$9)(b.serialize()),e.txid=(0,f.$9)(b.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=h),this.warn(`signTx
9
+ ${JSON.stringify(i)}`),new Error("checkTokenBalBlockchair tokenData is invalid")}return{tokenBal:o,server:"blockchair"}})}checkTokenBalRpc(e){return E(this,null,function*(){let t,s,o,i;const l=this.ethEngine.walletLocalData.publicKey;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",l),o=s.result,i=s.server;else{const a=this.ethEngine.getTokenInfo(e);if(a!=null&&typeof a.contractAddress=="string"){const h={data:`0x70a08231${(0,f.gc)((0,f.KT)(l),32)}`,to:a.contractAddress},r=yield this.multicastServers("eth_call",h),u=r.result.result;if(!u.startsWith("0x"))throw new Error("Invalid return value. Result not hex");r.result.result=(0,f.Z8)(u),o=r.result,i=r.server}}t=ce(o)}catch(a){throw this.ethEngine.error(`checkTokenBalRpc token ${e} response ${s||""} `,a),new Error(`checkTokenBalRpc invalid ${e} response ${JSON.stringify(o)}`)}return{tokenBal:{[e]:t.result},server:i}})}checkAndUpdate(e=0,t,s,o){return E(this,null,function*(){const i=Date.now();if(i-e>t)try{const l=yield o();this.processEthereumNetworkUpdate(i,l,s)}catch(l){this.ethEngine.error("checkAndUpdate ",l)}})}getQueryHeightWithLookback(e){return e>xe?e-xe:0}getQueryDateWithLookback(e){return e>$e?e-$e:0}needsLoop(){return E(this,null,function*(){for(;this.ethEngine.engineOn;){const e=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,$t,e,()=>E(this,null,function*(){return yield this.check("blockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Rt,e,()=>E(this,null,function*(){return yield this.check("nonce")}));const{currencyCode:t}=this.ethEngine.currencyInfo,s=this.ethEngine.enabledTokens;s.includes(t)||s.push(t);for(const o of s)yield this.checkAndUpdate(this.ethNeeds.tokenBalLastChecked[o],Dt,e,()=>E(this,null,function*(){return yield this.check("tokenBal",o)})),yield this.checkAndUpdate(this.ethNeeds.tokenTxsLastChecked[o],_t,e,()=>E(this,null,function*(){return yield this.check("txs",{startBlock:this.getQueryHeightWithLookback(this.ethEngine.walletLocalData.lastTransactionQueryHeight[o]),startDate:this.getQueryDateWithLookback(this.ethEngine.walletLocalData.lastTransactionDate[o]),currencyCode:o})}));yield(0,f.HB)(1e3)}})}processEthereumNetworkUpdate(e,t,s){if(!!t){if(t.blockHeight){this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate blockHeight ${t.server||"no server"} won`);const o=t.blockHeight;this.ethEngine.log(`Got block height ${o||"no blockheight"}`),typeof o=="number"&&this.ethEngine.walletLocalData.blockHeight!==o&&(this.ethNeeds.blockHeightLastChecked=e,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=o,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}if(t.newNonce&&(this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate nonce ${t.server||"no server"} won`),this.ethNeeds.nonceLastChecked=e,this.ethEngine.otherData.nextNonce=t.newNonce,this.ethEngine.walletLocalDataDirty=!0),t.tokenBal!=null){const o=t.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${t.server||"no server"} won`);for(const i of Object.keys(o))this.ethNeeds.tokenBalLastChecked[i]=e,this.ethEngine.updateBalance(i,o[i])}if(t.tokenTxs!=null){const o=t.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${t.server||"no server"} won`);for(const i of Object.keys(o)){this.ethNeeds.tokenTxsLastChecked[i]=e,this.ethEngine.tokenCheckTransactionsStatus[i]=1;const l=o[i];if(l.edgeTransactions){for(const a of l.edgeTransactions)this.ethEngine.addTransaction(i,a);this.ethEngine.walletLocalData.lastTransactionQueryHeight[i]=s,this.ethEngine.walletLocalData.lastTransactionDate[i]=e}}this.ethEngine.updateOnAddressesChecked()}this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}}buildQueryFuncs(e){const{rpcServers:t,evmScanApiServers:s,blockbookServers:o,blockchairApiServers:i,amberdataRpcServers:l,amberdataApiServers:a}=e,h=[],r=[],u=[],c=[];return s.length>0&&(h.push(this.checkBlockHeightEthscan),r.push(this.checkNonceEthscan),c.push(this.checkTokenBalEthscan)),u.push(this.checkTxsEthscan),o.length>0&&(h.push(this.checkBlockHeightBlockbook),c.push(this.checkAddressBlockbook),r.push(this.checkAddressBlockbook)),i.length>0&&(h.push(this.checkBlockHeightBlockchair),c.push(this.checkTokenBalBlockchair)),l.length>0&&(h.push(this.checkBlockHeightAmberdata),r.push(this.checkNonceAmberdata)),a.length>0,t.length>0&&(r.push(this.checkNonceRpc),c.push(this.checkTokenBalRpc)),{blockheight:h,nonce:r,txs:u,tokenBal:c}}throwError(e,t,s){switch(e.status){case 402:case 429:case 432:throw new Error("rateLimited");default:throw new Error(`${t} The server returned error code ${e.status} for ${s}`)}}logError(e,t){(0,f.HY)(t).includes("rateLimited")?this.ethEngine.log(e,t):this.ethEngine.error(e,t)}}const Kt="low",Gt="standard",jt="high",Re="custom",De="1000000000";function _e(m,e,t,s){var o,i,l,a,h,r,u;let c=!0,d,g;if(m.spendTargets&&m.spendTargets.length>0&&m.spendTargets[0].publicAddress){const{customNetworkFee:y}=m||{};if(m.networkFeeOption===Re&&y!=null){const{gasLimit:T,gasPrice:L}=y;if((isNaN(T)||T==="")&&(isNaN(L)||L==="")){const F=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw F.name="ErrorBelowMinimumFee",F}if(L!=null&&L!==""){const F=(a=(i=(o=e.default)==null?void 0:o.gasPrice)==null?void 0:i.minGasPrice)!=null?a:(l=s.defaultNetworkFees.default.gasPrice)==null?void 0:l.minGasPrice;if(F!=null){const _=(0,p.div)(F,De);if((0,p.lt)(L,_)||/^\s*$/.test(L)){const H=new Error(`Gas Limit: ${T} Gas Price (Gwei): ${L}`);throw H.name="ErrorBelowMinimumFee",H}}g=(0,p.mul)(L,De)}if(T!=null&&T!==""){const F=(u=(r=(h=e.default)==null?void 0:h.gasLimit)==null?void 0:r.minGasLimit)!=null?u:s.defaultNetworkFees.default.gasLimit.minGasLimit;if(F!=null&&(0,p.lt)(T,F)||/^\s*$/.test(T)){const _=new Error(`Gas Limit: ${T} Gas Price (Gwei): ${L}`);throw _.name="ErrorBelowMinimumFee",_}d=T,c=!1}}if(d!=null&&g!=null)return{gasLimit:d,gasPrice:g,useDefaults:!1};const k=(0,f.f0)(m.spendTargets[0].publicAddress);let w=e.default,b=e.default;typeof e[k]<"u"&&(b=e[k],c=!1,typeof b.gasPrice<"u"&&(w=b));let v="regularTransaction";m.currencyCode&&m.currencyCode!==t.currencyCode&&(v="tokenTransaction");let C="standard";typeof m.networkFeeOption=="string"&&m.networkFeeOption!==Re&&(C=m.networkFeeOption);const x=b.gasLimit[v];let $="";if(!m.spendTargets[0].nativeAmount)throw new Error("ErrorInvalidNativeAmount");let X=m.spendTargets[0].nativeAmount;if(v==="tokenTransaction"&&(X=(0,p.div)(X,"10")),w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const B=w.gasPrice;switch(C){case Kt:$=B.lowFee;break;case Gt:{if((0,p.gte)(X,w.gasPrice.standardFeeHighAmount)){$=B.standardFeeHigh;break}if((0,p.lte)(X,B.standardFeeLowAmount)){if(!w.gasPrice)throw new Error("ErrorInvalidGasPrice");$=w.gasPrice.standardFeeLow;break}const T=(0,p.sub)(B.standardFeeHighAmount,B.standardFeeLowAmount),L=(0,p.sub)(B.standardFeeHigh,B.standardFeeLow),F=(0,p.sub)(X,B.standardFeeLowAmount),_=(0,p.mul)(F,L),H=(0,p.div)(_,T);$=(0,p.add)(B.standardFeeLow,H);break}case jt:$=w.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:d!=null?d:x,gasPrice:g!=null?g:$,useDefaults:c}}else throw new Error("ErrorInvalidSpendInfo")}const Mt="1040",Xe=m=>{const{chainParams:e,data:t,dynamicOverhead:s,fixedOverhead:o,gasPriceL1Wei:i,gasLimit:l,nonce:a,to:h,value:r="0x0"}=m,u=J().custom(e),g=A.Transaction.fromTxData({nonce:a!=null?(0,f.X0)(a):void 0,gasPrice:(0,f.X0)(i),gasLimit:(0,f.X0)(l),to:h,value:r,data:t},{common:u}).raw().map(v=>v.toString("hex")).join().match(/(.{1,2})/g);if(g==null)throw new Error("Invalid rawTx string");let y=0;for(let v=0;v<g.length;v++)g[v]==="00"?y+=4:y+=16;const k=(0,p.add)((0,p.add)(y.toString(),o),Mt),w=(0,p.div)(s,"1000000",18);return(0,p.mul)((0,p.mul)(i,k),w)};var Y=P(48764).Buffer,Ut=Object.defineProperty,Jt=Object.defineProperties,Wt=Object.getOwnPropertyDescriptors,He=Object.getOwnPropertySymbols,Zt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty,zt=Object.prototype.propertyIsEnumerable,Qt=Reflect.get,Ke=(m,e,t)=>e in m?Ut(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,V=(m,e)=>{for(var t in e||(e={}))Vt.call(e,t)&&Ke(m,t,e[t]);if(He)for(var t of He(e))zt.call(e,t)&&Ke(m,t,e[t]);return m},ue=(m,e)=>Jt(m,Wt(e)),Ee=(m,e,t)=>Qt(Zt(m),t,e),D=(m,e,t)=>new Promise((s,o)=>{var i=h=>{try{a(t.next(h))}catch(r){o(r)}},l=h=>{try{a(t.throw(h))}catch(r){o(r)}},a=h=>h.done?s(h.value):Promise.resolve(h.value).then(i,l);a((t=t.apply(m,e)).next())});class de extends ye.P{constructor(e,t,s,o,i,l){super(e,t,s,i),this.updateNetworkFeesFromBaseFeePerGas=()=>D(this,null,function*(){var r;const{supportsEIP1559:u=!1}=this.networkInfo;if(!u)return;const{baseFeePerGas:c}=yield this.ethNetwork.getBaseFeePerGas();if(c==null)return;const d=(0,f.Z8)(c),g=this.networkFees;if(g.default==null||g.default.gasPrice==null)return;const y=this.networkInfo.defaultNetworkFees.default,k=g.default.minPriorityFee||y.minPriorityFee,w=(r=g.default.baseFeeMultiplier)!=null?r:y.baseFeeMultiplier;if(k==null||w==null)return;const b={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const v of Object.keys(w)){const C=(0,p.mul)(w[v],d),x=(0,p.add)(C,k);b[v]=(0,p.div)(x,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),ke(this.log,b),b}),this.initOptions=o,this.networkInfo=e.networkInfo,this.ethNetwork=new Ht(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},this.networkInfo.l1RollupParams!=null&&(this.l1RollupParams=this.networkInfo.l1RollupParams),this.networkFees=this.networkInfo.defaultNetworkFees,this.fetchCors=(0,f.zR)(e);const{infoFeeProvider:a,externalFeeProviders:h}=Pt(this.io.fetch,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=a,this.externalFeeProviders=[...h,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:(r,u)=>{if(!(0,f.vq)(r))throw new Error("ErrorInvalidMessage");const c=Y.from(u.privateKey,"hex"),d=(0,f.ah)(r),g=S().hashPersonalMessage(d),{v:y,r:k,s:w}=S().ecsign(g,c);return S().toRpcSig(y,k,w)},signTypedData:(r,u)=>{const c=rt(r),d=Y.from(u.privateKey,"hex"),{types:g}=c;function y(O,T=[]){if(T.includes(O)||g[O]===void 0)return T;T.push(O);for(const L of g[O])for(const F of y(L.type,T))T.includes(F)||T.push(F);return T}function k(O){let T=y(O);T=T.filter(F=>F!==O),T=[O].concat(T.sort());let L="";for(const F of T)L+=`${F}(${g[F].map(({name:_,type:H})=>`${H} ${_}`).join(",")})`;return L}function w(O){return S().keccak256(k(O))}function b(O,T){const L=[],F=[];L.push("bytes32"),F.push(w(O));for(const _ of g[O]){let H=T[_.name];if(_.type==="string"||_.type==="bytes")L.push("bytes32"),H=S().keccak256(H),F.push(H);else if(g[_.type]!==void 0)L.push("bytes32"),H=S().keccak256(b(_.type,H)),F.push(H);else{if(_.type.lastIndexOf("]")===_.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");L.push(_.type),F.push(H)}}return ie().rawEncode(L,F)}function v(O,T){return S().keccak256(b(O,T))}function C(){return S().keccak256(Y.concat([Y.from("1901","hex"),v("EIP712Domain",c.domain),v(c.primaryType,c.message)]))}const x=S().ecsign(C(),d),{v:$,r:X,s:B}=x;return S().bufferToHex(Y.concat([S().setLengthLeft(X,32),S().setLengthLeft(B,32),S().toBuffer($)]))},txRpcParamsToSpendInfo:r=>{const u={otherParams:r};return r.to!=null&&(u.publicAddress=r.to),r.value!=null?u.nativeAmount=(0,f.Z8)(r.value):u.nativeAmount="0",{currencyCode:this.currencyInfo.currencyCode,spendTargets:[u],networkFeeOption:"custom",customNetworkFee:{gasLimit:(0,f.Z8)(r.gas),gasPrice:(0,p.div)((0,f.Z8)(r.gasPrice),Z.toString(),18)},otherParams:r}}},this.otherMethods={txRpcParamsToSpendInfo:r=>D(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(r)}),wcInit:(r,u="Edge")=>D(this,null,function*(){return yield(0,f.Vs)(new Promise((c,d)=>{const g=new N.Z({uri:r.uri,storageId:r.uri,clientMeta:{description:"Edge Wallet",url:"https://www.edge.app",icons:["https://content.edge.app/Edge_logo_Icon.png"],name:u}});g.on("session_request",(y,k)=>{if(y)throw this.error("Wallet connect session_request",y),y;const w=(0,pe.ff)(k).params[0],b=ue(V({},w),{timeConnected:Date.now()/1e3});this.tools.walletConnectors[r.uri]={connector:g,wcProps:r,dApp:b},c(b)}),g.on("call_request",(y,k)=>{try{if(y)throw y;let w="0",b="0";switch(k.method){case"eth_sendTransaction":case"eth_signTransaction":{const C=(0,n.su)({gas:(0,n.Zz)(n.XC),gasPrice:(0,n.Zz)(n.XC),value:(0,n.Zz)(n.XC)})(k.params[0]),{gas:x,gasPrice:$,value:X}=C;X!=null&&(w=(0,f.Z8)(X));let B=this.networkFees.default.gasLimit.tokenTransaction;x==null?k.params[0].gas=(0,f.X0)(B):B=(0,f.Z8)(x);let O=this.networkFees.default.gasPrice.standardFeeHigh;$==null?k.params[0].gasPrice=(0,f.X0)(O):O=(0,f.Z8)($),b=(0,p.mul)(B,O);break}}const v={uri:r.uri,dApp:this.tools.walletConnectors[r.uri].dApp,payload:k,walletId:this.tools.walletConnectors[r.uri].walletId,nativeAmount:w,networkFee:b};this.currencyEngineCallbacks.onWcNewContractCall(v)}catch(w){throw this.warn("Wallet connect call_request ",w),w}}),g.on("disconnect",(y,k)=>{if(y!=null)throw y;delete this.tools.walletConnectors[r.uri]})}),5e3)}),wcConnect:(r,u,c)=>{this.tools.walletConnectors[r].connector.approveSession({accounts:[u],chainId:this.networkInfo.chainParams.chainId}),this.tools.walletConnectors[r].walletId=c},wcDisconnect:r=>{var u;((u=this.tools.walletConnectors[r])==null?void 0:u.connector)!=null&&(this.tools.walletConnectors[r].connector.killSession().catch(()=>{}),delete this.tools.walletConnectors[r])},wcApproveRequest:(r,u,c)=>D(this,null,function*(){this.tools.walletConnectors[r].connector.approveRequest({id:Number(u.id),jsonrpc:"2.0",result:c})}),wcRejectRequest:(r,u)=>D(this,null,function*(){this.tools.walletConnectors[r].connector.rejectRequest({id:Number(u.id),jsonrpc:"2.0",error:{message:"rejected"}})}),wcGetConnections:()=>Object.keys(this.tools.walletConnectors).filter(r=>this.tools.walletConnectors[r].walletId===this.walletInfo.id).map(r=>V(V({},this.tools.walletConnectors[r].dApp),this.tools.walletConnectors[r].wcProps))}}setOtherData(e){this.otherData=ft(e)}updateNetworkFees(){return D(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const s={};Object.keys(t).forEach(o=>{const i=o;s[i]=(0,f.Y7)(t[i])}),this.networkFees.default.gasPrice!=null&&(this.networkFees.default.gasPrice=V(V({},this.networkFees.default.gasPrice),s));break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}})}updateL1RollupParams(){return D(this,null,function*(){if(this.l1RollupParams!=null){try{const e=yield this.ethNetwork.multicastServers("rollup_gasPrices"),t=Et(e.result.result),{l1GasPrice:s}=t;this.l1RollupParams=ue(V({},this.l1RollupParams),{gasPriceL1Wei:(0,p.ceil)((0,p.mul)((0,f.Z8)(s),this.l1RollupParams.maxGasPriceL1Multiplier),0)})}catch(e){this.log.warn("Failed to update l1GasPrice",e)}try{const e={to:this.l1RollupParams.oracleContractAddress,data:this.l1RollupParams.dynamicOverheadMethod},t=yield this.ethNetwork.multicastServers("eth_call",e),s=ce(t.result);this.l1RollupParams=ue(V({},this.l1RollupParams),{dynamicOverhead:(0,f.Z8)(s.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return D(this,null,function*(){yield Ee(de.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return D(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:ze;this.infoFeeProvider().then(s=>{this.log.warn("infoFeeProvider:",JSON.stringify(s,null,2)),this.networkFees=(0,f.nu)(this.networkFees,s)}).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>D(this,null,function*(){return yield this.addToLoop("updateNetworkFees",t)})),this.addToLoop("updateL1RollupParams",Qe).catch(()=>{}),this.ethNetwork.needsLoop(),Ee(de.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return D(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return D(this,null,function*(){const e=this.walletLocalData.publicKey.toLowerCase(),{publicKey:t}=this.walletLocalData,s=/[A-F]/.test(t)?t:S().toChecksumAddress(t.replace("0x",""));return{legacyAddress:e,publicAddress:s}})}getMaxSpendable(e){return D(this,null,function*(){const t=this.getBalance({currencyCode:e.currencyCode}),s=e.spendTargets[0].publicAddress;if(s==null)throw new Error("makeSpend Missing publicAddress");if(e.currencyCode===this.currencyInfo.currencyCode){const o=(i,l)=>{const a=(0,p.sub)(l,i);if((0,p.lte)(a,"1"))return i;const h=(0,p.add)(i,(0,p.div)(a,"2"));e.spendTargets[0].nativeAmount=h;const{gasPrice:r,gasLimit:u}=_e(e,this.networkFees,this.currencyInfo,this.networkInfo),c=(0,p.mul)(r,u);let d="0";if(this.l1RollupParams!=null){const y={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:u,to:s,value:(0,f.X0)(h),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};d=Xe(y)}const g=(0,p.add)((0,p.add)(h,c),d);return(0,p.gt)(g,t)?o(i,h):o(h,l)};return o("0",(0,p.add)(t,"1"))}else return e.spendTargets[0].nativeAmount=t,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}makeSpend(e){return D(this,null,function*(){var t,s,o,i,l;const{edgeSpendInfo:a,currencyCode:h,skipChecks:r}=this.makeSpendCheck(e),{pendingTxs:u=[]}=a;if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const c=a.spendTargets[0],{publicAddress:d}=c;let{nativeAmount:g}=c;if(d==null)throw new Error("makeSpend Missing publicAddress");if(g==null)throw new I.$D;if(!S().isValidAddress(d))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let y=(s=c.memo)!=null?s:(t=c.otherParams)==null?void 0:t.data;if(y!=null&&y.length>0&&!(0,f.vq)(y))throw new Error("Memo/data field must be of type 'hex'");y===""&&(y=void 0);const k=y!=null;let w;const b=_e(a,this.networkFees,this.currencyInfo,this.networkInfo),v=b.gasPrice;let C=b.gasLimit;const x=b.useDefaults,$=C;let X;if(u.length>0){const z=this.walletLocalData.otherData,re=this.walletLocalData.numUnconfirmedSpendTxs>0?z.unconfirmedNextNonce:z.nextNonce;X=(0,p.add)(re,u.length.toString())}let B,O;if(h===this.currencyInfo.currencyCode)w={from:[this.walletLocalData.publicKey],to:[d],gas:C,gasPrice:v,gasUsed:"0",nonceUsed:X,data:y},O=(0,f.X0)(g);else{if(y)B=d;else{const re=this.getTokenInfo(h);if(re==null||typeof re.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");B=re.contractAddress,O=(0,f.X0)(g);const ve=ie().simpleEncode("transfer(address,uint256):(uint256)",d,O);O="0x0",y="0x"+Y.from(ve).toString("hex")}w={from:[this.walletLocalData.publicKey],to:[B],gas:C,gasPrice:v,gasUsed:"0",tokenRecipientAddress:d,nonceUsed:X,data:y}}if(x&&(this.lastEstimatedGasLimit.publicAddress!==d||this.lastEstimatedGasLimit.contractAddress!==B||this.lastEstimatedGasLimit.gasLimit==="")){const z=[{to:B||d,from:this.walletLocalData.publicKey,gas:"0xffffff",value:O,data:y},"latest"];let re=!1;try{const Ze=(yield this.ethNetwork.multicastServers("eth_getCode",[B||d,"latest"])).result.result!=="0x";try{if(!Ze&&!k)C=this.networkFees.default.gasLimit.regularTransaction;else{const Ve=yield this.ethNetwork.multicastServers("eth_estimateGas",z);C=(0,p.add)(parseInt(Ve.result.result,16).toString(),"0"),Ze&&(C=(0,p.mul)(C,"2"))}re=!0}catch{if(k)throw new Error("Unable to estimate gas limit. Please try again later");this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction!=null&&(C=this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction)}if((0,p.lt)(C,(o=this.networkFees.default.gasLimit.minGasLimit)!=null?o:"21000"))throw C=$,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum");re&&(this.lastEstimatedGasLimit={publicAddress:d,contractAddress:B,gasLimit:C})}catch(ve){this.error("makeSpend Error determining gas limit ",ve)}}else x&&(C=this.lastEstimatedGasLimit.gasLimit);w.gas=C;const T=(i=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?i:"0";let L=(0,p.mul)(v,C),F="0",_=null,H="0";if(this.l1RollupParams!=null){const z={nonce:w.nonceUsed,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:w.gas,to:w.to[0],value:O,data:w.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};H=Xe(z)}if(h===this.currencyInfo.currencyCode){if(L=(0,p.add)(L,H),F=(0,p.add)(L,g),!r&&(0,p.gt)(F,T))throw new I.C_;g=(0,p.mul)(F,"-1")}else{if(_=(0,p.add)(L,H),!r&&(0,p.gt)(L,T))throw new I.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:L});const z=(l=this.walletLocalData.totalBalances[h])!=null?l:"0";if(!r&&(0,p.gt)(g,z))throw new I.C_;L="0",g=(0,p.mul)(g,"-1")}const We={txid:"",date:0,currencyCode:h,blockHeight:0,nativeAmount:g,isSend:g.startsWith("-"),networkFee:L,feeRateUsed:Pe(v,C),ourReceiveAddresses:[],signedTx:"",otherParams:w,walletId:this.walletId};return _&&(We.parentNetworkFee=_),We})}signMessage(e,t,s){return D(this,null,function*(){const o=Ce(this.currencyInfo.pluginId)(t);if(vt(s.otherParams).typedData){const l=JSON.parse(e);try{return this.utils.signTypedData(l,o)}catch{return(0,te.signTypedData_v4)(Y.from(o.privateKey,"hex"),{data:l})}}return this.utils.signMessage(e,o)})}signTx(e,t){return D(this,null,function*(){const s=Ce(this.currencyInfo.pluginId)(t),o=(0,f.Xp)(e),i=(0,f.NC)(o.gas),l=(0,f.NC)(o.gasPrice);let a;if(e.currencyCode===this.currencyInfo.currencyCode){const v=(0,p.add)(e.nativeAmount,e.networkFee);a=(0,p.mul)("-1",v,16)}else a=(0,p.mul)("-1",e.nativeAmount,16);(0,p.lt)(a,"0")&&(a="0x00");let h=o.nonceUsed;if(!h)if(this.walletLocalData.numUnconfirmedSpendTxs&&(0,p.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)){const v=(0,p.sub)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce);if((0,p.lte)(v,"5"))h=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0;else{const C=new Error("Excessive pending spend transactions");throw C.name="ErrorExcessivePendingSpends",C}}else h=this.otherData.nextNonce;const r=(0,f.NC)(h);let u;if(o.data!=null)u=o.data,e.currencyCode!==this.currencyInfo.currencyCode&&(a="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)u="";else{const v=ie().simpleEncode("transfer(address,uint256):(uint256)",o.tokenRecipientAddress,a);u="0x"+Y.from(v).toString("hex"),a="0x00"}const{chainParams:c}=this.networkInfo,d=J().custom(c),g={nonce:r,gasPrice:l,gasLimit:i,to:o.to[0],value:a,data:u},y=Y.from(s.privateKey,"hex"),k=W().fromPrivateKey(y);this.warn(`signTx getAddressString ${k.getAddressString()}`);const b=A.Transaction.fromTxData(g,{common:d}).sign(y);return e.signedTx=(0,f.$9)(b.serialize()),e.txid=(0,f.$9)(b.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=h),this.warn(`signTx
10
10
  ${(0,f.oX)(e)}`),e})}broadcastTx(e){return D(this,null,function*(){return yield this.ethNetwork.multicastServers("broadcastTx",e),this.warn(`SUCCESS broadcastTx
11
11
  ${(0,f.oX)(e)}`),e})}accelerate(e){return D(this,null,function*(){var t,s,o;const{currencyCode:i}=e,l=(0,n.Vk)(be)(e.otherParams);let a=e.txid,h=yield this.findTransaction(i,(0,f.f0)(a));if(h===-1&&((l==null?void 0:l.replacedTxid)!=null&&l.replacedTxid!==""&&(a=l.replacedTxid,h=yield this.findTransaction(i,(0,f.f0)(a))),h===-1))return null;const r=this.transactionList[i][h],u=(0,n.Vk)(be)(r.otherParams);if(r==null||r.blockHeight>0||u==null||u.nonceUsed==null||u.data!=null)return null;const c=((t=r.spendTargets)!=null?t:[])[0];if(c==null)return null;const d=(0,p.mul)(u.gasPrice,"2"),g=u.gas,y=ue(V({},u),{gas:g,gasPrice:d,replacedTxid:a});let{nativeAmount:k}=c,w=(0,p.mul)(d,g),b="0",v;const C=(s=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?s:"0";if(i===this.currencyInfo.currencyCode){if(b=(0,p.add)(w,k),(0,p.gt)(b,C))throw new I.C_;k=(0,p.mul)(b,"-1")}else{if(v=w,(0,p.gt)(w,C))throw new I.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:w});const x=(o=this.walletLocalData.totalBalances[i])!=null?o:"0";if((0,p.gt)(k,x))throw new I.C_;w="0",k=(0,p.mul)(k,"-1")}return ue(V({},e),{txid:"",feeRateUsed:Pe(d,g),nativeAmount:k,networkFee:w,otherParams:y,parentNetworkFee:v})})}getDisplayPrivateSeed(e){return Ce(this.currencyInfo.pluginId)(e).privateKey}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}saveTx(e){return D(this,null,function*(){var t;const s=(0,n.Vk)(be)(e.otherParams);if((s==null?void 0:s.replacedTxid)!=null){const{currencyCode:o}=e,i=(0,f.f0)(s.replacedTxid),l=this.findTransaction(o,i);if(l!==-1){const a=this.transactionList[o][l],h=e.metadata,r=ue(V({},a),{metadata:h,blockHeight:-1});this.addTransaction(o,r)}}if(e.blockHeight===0){const o=(t=e.otherParams)==null?void 0:t.nonceUsed;o!=null&&(this.otherData.unconfirmedNextNonce=(0,p.add)(o,"1"))}Ee(de.prototype,this,"saveTx").call(this,e)})}addCustomToken(e){return D(this,null,function*(){const{contractAddress:t}=e;if(!(0,f.vq)(t)||(0,f.KT)(t).length!==40)throw new Error("ErrorInvalidContractAddress");yield Ee(de.prototype,this,"addCustomToken").call(this,e,t.toLowerCase())})}}function Yt(m,e,t,s){return D(this,null,function*(){const{currencyInfo:o,initOptions:i}=m,l=bt(t),a=new de(m,e,l,i,s,o);return yield a.loadEngine(e,l,s),a})}var qt=Object.defineProperty,en=Object.defineProperties,tn=Object.getOwnPropertyDescriptors,Ge=Object.getOwnPropertySymbols,nn=Object.prototype.hasOwnProperty,sn=Object.prototype.propertyIsEnumerable,je=(m,e,t)=>e in m?qt(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,Me=(m,e)=>{for(var t in e||(e={}))nn.call(e,t)&&je(m,t,e[t]);if(Ge)for(var t of Ge(e))sn.call(e,t)&&je(m,t,e[t]);return m},Ue=(m,e)=>en(m,tn(e)),se=(m,e,t)=>new Promise((s,o)=>{var i=h=>{try{a(t.next(h))}catch(r){o(r)}},l=h=>{try{a(t.throw(h))}catch(r){o(r)}},a=h=>h.done?s(h.value):Promise.resolve(h.value).then(i,l);a((t=t.apply(m,e)).next())});class Je{constructor(e){const{builtinTokens:t,currencyInfo:s,io:o,networkInfo:i}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=o,this.networkInfo=i,this.walletConnectors={}}importPrivateKey(e){return se(this,null,function*(){const{pluginId:t}=this.currencyInfo,{pluginMnemonicKeyName:s,pluginRegularKeyName:o}=this.networkInfo;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const i=ee.Buffer.from(e.replace(/^0x/,""),"hex");if(!S().isValidPrivate(i))throw new Error("Invalid private key");const l=i.toString("hex"),a={[o]:l};return this.derivePublicKey({type:`wallet:${t}`,id:"fake",keys:a}),a}else{if(!(0,q.validateMnemonic)(e))throw new Error("Invalid input");const i=yield this._mnemonicToHex(e);return{[s]:e,[o]:i}}})}createPrivateKey(e){return se(this,null,function*(){const{pluginMnemonicKeyName:t,pluginRegularKeyName:s}=this.networkInfo;if(e.replace("wallet:","")!==this.currencyInfo.pluginId)throw new Error("InvalidWalletType");const i=ee.Buffer.from(this.io.random(32)),l=(0,q.entropyToMnemonic)(i),a=yield this._mnemonicToHex(l);return{[t]:l,[s]:a}})}derivePublicKey(e){return se(this,null,function*(){const{pluginId:t}=this.currencyInfo,{hdPathCoinType:s,pluginMnemonicKeyName:o,pluginRegularKeyName:i}=this.networkInfo;if(e.type!==`wallet:${t}`)throw new Error("Invalid wallet type");let l;if(e.keys[o]!=null){const a=(0,q.mnemonicToSeedSync)(e.keys[o]),h=oe().fromMasterSeed(a),r=`m/44'/${s}'/0'/0`,d=h.derivePath(`${r}/0`).getWallet().getPublicKey(),g=S().pubToAddress(d).toString("hex");l=S().toChecksumAddress(g)}else{const a=ee.Buffer.from(e.keys[i].replace(/^0x/,""),"hex");if(!S().isValidPrivate(a))throw new Error("Invalid private key");l=`0x${S().privateToAddress(a).toString("hex")}`}if(!S().isValidAddress(l))throw new Error("Invalid address");return{publicKey:l}})}_mnemonicToHex(e){return se(this,null,function*(){const{hdPathCoinType:t}=this.networkInfo,s=oe().fromMasterSeed((0,q.mnemonicToSeedSync)(e)),o=`m/44'/${t}'/0'/0`;return s.derivePath(`${o}/0`).getWallet().getPrivateKeyString().replace(/^0x/,"")})}parseUri(e,t,s){return se(this,null,function*(){var o,i,l,a,h;const r={wc:!0};this.networkInfo.uriNetworks.forEach(k=>{r[k]=!0});const{parsedUri:u,edgeParsedUri:c}=(0,K.k)(this.currencyInfo,e,r,t||this.currencyInfo.currencyCode,s);if(u.protocol==="wc"){if(u.query.bridge!=null&&u.query.key!=null)return c.walletConnect={uri:e,topic:u.pathname.split("@")[0],version:u.pathname.split("@")[1],bridge:u.query.bridge,key:u.query.key},c;throw new Error("MissingWcBridgeKey")}let d="";c.publicAddress&&(d=c.publicAddress,c.publicAddress=c.publicAddress.toLowerCase());let[g,y]=d.split("-");if(y||(y=g,g="pay"),d=y,/[A-F]/.test(d)&&!S().isValidChecksumAddress(d))throw new Error("InvalidPublicAddressError");if(d=d.toLowerCase(),!S().isValidAddress(d||""))throw new Error("InvalidPublicAddressError");if(g==="token"||g==="token_info"){if(!u.query)throw new Error("InvalidUriError");const k=(o=u.query.symbol)!=null?o:"SYM";if(k.length<2||k.length>5)throw new Error("Wrong Token symbol");const w=(i=u.query.name)!=null?i:k,b=(l=u.query.decimals)!=null?l:"18";let v="1000000000000000000";const C=parseInt(b);if(C<0||C>18)throw new Error("Wrong number of decimals");v="1"+"0".repeat(C);const x=(a=u.query.type)!=null?a:this.networkInfo.ercTokenStandard;return{token:{currencyCode:k,contractAddress:y.toLowerCase(),currencyName:w,multiplier:v,denominations:[{name:k,multiplier:v}],type:x.toUpperCase()}}}if(g==="pay"){const k=d,w=u.pathname.split("/")[1],b=u.query;switch(w){case"transfer":{const v=(h=b.address)!=null?h:"",C=k!=null?k:"",x=b.uint256!=null?(0,f.EE)(b.uint256):c.nativeAmount,$=this.currencyInfo.metaTokens.find(X=>X.contractAddress===C);if(t!=null&&($==null||$.currencyCode!==t))throw new Error("InternalErrorInvalidCurrencyCode");if(!S().isValidAddress(v))throw new Error("InvalidPublicAddressError");if(!S().isValidAddress(C))throw new Error("InvalidContractAddressError");return Ue(Me({},c),{currencyCode:$==null?void 0:$.currencyCode,nativeAmount:x,publicAddress:v})}case void 0:{const v=k,C=b.value!=null?(0,f.EE)(b.value):c.nativeAmount;return Ue(Me({},c),{publicAddress:v,nativeAmount:C})}default:throw new Error("UnsupportedContractFunction")}}throw new Error("InvalidUriError")})}encodeUri(e,t){return se(this,null,function*(){const{publicAddress:s,nativeAmount:o,currencyCode:i}=e;if(!S().isValidAddress(s))throw new Error("InvalidPublicAddressError");let a;if(typeof o=="string"){const r=(0,f.cp)(this.currencyInfo,i||this.currencyInfo.currencyCode,t);if(r==null)throw new Error("InternalErrorInvalidCurrencyCode");a=(0,p.div)(o,r.multiplier,18)}return(0,K.Q)(e,this.currencyInfo.pluginId,a)})}getSplittableTypes(e){return Object.keys(j.j).map(t=>`wallet:${t}`)}getTokenId(e){return se(this,null,function*(){(0,G.Rp)(e);const t=(0,G.Oj)(e.networkLocation);if(t==null||!S().isValidAddress(t.contractAddress))throw new Error("ErrorInvalidContractAddress");return t.contractAddress.toLowerCase().replace(/^0x/,"")})}}function rn(m){return se(this,null,function*(){const e=new Je(m),t=(0,Q.$o)();return t!=null&&t.clear(),e})}},89214:function(){},52361:function(){},94616:function(){},88924:function(){},55024:function(){}}]);
@@ -1,2 +1,2 @@
1
- (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[159],{79014:function(W,D,d){"use strict";d.d(D,{Q:function(){return M},k:function(){return b}});var m=d(77591),T=d.n(m),z=d(24350),B=d(84564),K=d.n(B),h=d(76714),U=Object.defineProperty,O=Object.getOwnPropertySymbols,$=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,N=(l,y,f)=>y in l?U(l,y,{enumerable:!0,configurable:!0,writable:!0,value:f}):l[y]=f,P=(l,y)=>{for(var f in y||(y={}))$.call(y,f)&&N(l,f,y[f]);if(O)for(var f of O(y))H.call(y,f)&&N(l,f,y[f]);return l};function b(l,y,f,g,A){const u=P({},K()(y,{},!0)),C=y.startsWith(`${l.pluginId}://`);if(u.protocol!=null&&(u.protocol=u.protocol.replace(":","")),u.protocol!=null&&u.protocol!==""&&!f[u.protocol])throw new Error(`Uri protocol '${u.protocol}' is not supported for ${l.pluginId}.`);if(u.host===""&&u.pathname==="")throw new Error("Path and host not found in uri.");const w={publicAddress:u.host!==""?u.host:u.pathname.split("/")[0]},p=u.query.label,I=u.query.message,x=u.query.category;(p!=null||I!=null||x!=null||C)&&(w.metadata={},w.metadata.name=p,w.metadata.notes=I,w.metadata.category=x,w.metadata.gateway=C!=null?C:!1);const v=u.query.amount;if(v!=null&&typeof v=="string"){g==null&&(g=l.currencyCode);const E=(0,h.cp)(l,g!=null?g:"",A);if(E==null)throw new Error("InternalErrorInvalidCurrencyCode");let S=(0,m.mul)(v,E.multiplier);S=(0,m.toFixed)(S,0,0),w.nativeAmount=S,w.currencyCode=g}return{edgeParsedUri:w,parsedUri:u}}function M(l,y,f){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&l.label==null&&l.message==null)return l.publicAddress;{let g="";f!=null&&(g+="amount="+f+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(g+="label="+l.label+"&"),typeof l.message=="string"&&(g+="message="+l.message+"&")),g=g.substr(0,g.length-1);const A={scheme:y,path:l.publicAddress,query:g};return(0,z.qC)(A)}}},940:function(W,D,d){"use strict";d.r(D),d.d(D,{ZcashTools:function(){return E},makeCurrencyEngine:function(){return x},makeCurrencyTools:function(){return S}});var m=d(77591),T=d(2153),z=d(48764),B=d(79014),K=d(76714),h=d(82448),U=d(62177);const O=(0,h.su)({first:h.mH,last:h.mH}),$=(0,h.su)({alias:(0,h.Vk)(h.XC),blockRange:(0,h.Vk)(O,{first:0,last:0})}),H=(0,h.su)({birthdayHeight:h.mH,publicKey:h.XC,unifiedViewingKeys:(0,h.su)({extfvk:h.XC,extpub:h.XC})}),N=(0,U.jd)(H),P=s=>{const t=(0,h.su)({[`${s}Mnemonic`]:h.XC,[`${s}SpendKey`]:h.XC,[`${s}BirthdayHeight`]:h.mH});return(0,h.W1)(e=>{const n=t(e);return{mnemonic:n[`${s}Mnemonic`],spendKey:n[`${s}SpendKey`],birthdayHeight:n[`${s}BirthdayHeight`]}},e=>({[`${s}Mnemonic`]:e.mnemonic,[`${s}SpendKey`]:e.spendKey,[`${s}BirthdayHeight`]:e.birthdayHeight}))};var b=d(94935),M=d(50244),l=Object.defineProperty,y=Object.getOwnPropertySymbols,f=Object.getPrototypeOf,g=Object.prototype.hasOwnProperty,A=Object.prototype.propertyIsEnumerable,u=Reflect.get,C=(s,t,e)=>t in s?l(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,L=(s,t)=>{for(var e in t||(t={}))g.call(t,e)&&C(s,e,t[e]);if(y)for(var e of y(t))A.call(t,e)&&C(s,e,t[e]);return s},w=(s,t,e)=>u(f(s),e,t),p=(s,t,e)=>new Promise((n,r)=>{var c=o=>{try{a(e.next(o))}catch(k){r(k)}},i=o=>{try{a(e.throw(o))}catch(k){r(k)}},a=o=>o.done?n(o.value):Promise.resolve(o.value).then(c,i);a((e=e.apply(s,t)).next())});class I extends M.P{constructor(t,e,n,r,c){super(t,e,n,r);const{networkInfo:i}=t;this.pluginId=this.currencyInfo.pluginId,this.networkInfo=i,this.makeSynchronizer=c}setOtherData(t){this.otherData=$(t)}initData(){const{birthdayHeight:t,alias:e}=this.initializer;this.otherData.blockRange.first===0&&(this.otherData.blockRange={first:t,last:t}),this.alias=e,this.initialNumBlocksToDownload=-1,this.synchronizerStatus="DISCONNECTED",this.availableZatoshi="0",this.progressRatio=0}initSubscriptions(){this.synchronizer.on("update",t=>p(this,null,function*(){const{lastDownloadedHeight:e,scanProgress:n,networkBlockHeight:r}=t;this.onUpdateBlockHeight(r),this.onUpdateProgress(e,n,r),yield this.queryAll()})),this.synchronizer.on("statusChanged",t=>p(this,null,function*(){this.synchronizerStatus=t.name,yield this.queryAll()}))}queryAll(){return p(this,null,function*(){yield this.queryBalance(),yield this.queryTransactions(),this.onUpdateTransactions()})}onUpdateBlockHeight(t){this.walletLocalData.blockHeight!==t&&(this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}onUpdateProgress(t,e,n){if(!this.addressesChecked&&!this.isSynced()){this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=e*.99/100;let r=0;if(t>0){const i=n-t;this.initialNumBlocksToDownload<0&&(this.initialNumBlocksToDownload=i),r=i===0||this.initialNumBlocksToDownload===0?1:1-i/this.initialNumBlocksToDownload}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=r*.8;const c=(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]+this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode])/2;c!==this.progressRatio&&(Math.abs(c-this.progressRatio)>.1||c===1)&&(this.progressRatio=c,this.updateOnAddressesChecked())}}startEngine(){return p(this,null,function*(){this.initData(),this.synchronizer=yield this.makeSynchronizer(this.initializer),yield this.synchronizer.start(),this.initSubscriptions(),yield w(I.prototype,this,"startEngine").call(this)})}isSynced(){return this.synchronizerStatus==="SYNCED"}queryBalance(){return p(this,null,function*(){if(!!this.isSynced())try{const t=yield this.synchronizer.getShieldedBalance();if(t.totalZatoshi==="-1")return;this.availableZatoshi=t.availableZatoshi,this.updateBalance(this.currencyInfo.currencyCode,t.totalZatoshi)}catch(t){this.warn("Failed to update balances",t),this.updateBalance(this.currencyInfo.currencyCode,"0")}})}queryTransactions(){return p(this,null,function*(){try{let t=this.otherData.blockRange.first,e=this.otherData.blockRange.last;for(;this.isSynced()&&e<=this.walletLocalData.blockHeight;){if((yield this.synchronizer.getTransactions({first:t,last:e})).forEach(r=>this.processTransaction(r)),e===this.walletLocalData.blockHeight){t=this.walletLocalData.blockHeight,this.walletLocalDataDirty=!0,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked();break}t=e+1,e=e+this.networkInfo.transactionQueryLimit<this.walletLocalData.blockHeight?e+this.networkInfo.transactionQueryLimit:this.walletLocalData.blockHeight,this.otherData.blockRange={first:t,last:e},this.walletLocalDataDirty=!0}}catch(t){this.error(`Error querying ${this.currencyInfo.currencyCode} transactions `,t)}})}processTransaction(t){let e=t.value;const n=[];t.toAddress!=null?e=`-${(0,m.add)(e,this.networkInfo.defaultNetworkFee)}`:n.push(this.walletInfo.keys.publicKey);const r={txid:t.rawTransactionId,date:t.blockTimeInSeconds,currencyCode:this.currencyInfo.currencyCode,blockHeight:t.minedHeight,nativeAmount:e,isSend:e.startsWith("-"),networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:n,signedTx:"",otherParams:{},walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,r)}killEngine(){return p(this,null,function*(){yield this.synchronizer.stop(),yield w(I.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return p(this,null,function*(){yield w(I.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield w(I.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine(),this.synchronizer.rescan(this.walletInfo.keys.birthdayHeight).catch(t=>this.warn("resyncBlockchain failed: ",t))})}getMaxSpendable(){return p(this,null,function*(){const t=(0,m.sub)(this.availableZatoshi,this.networkInfo.defaultNetworkFee);if((0,m.lte)(t,"0"))throw new b.C_;return t})}makeSpend(t){return p(this,null,function*(){var e;if(!this.isSynced())throw new Error("Cannot spend until wallet is synced");const{edgeSpendInfo:n,currencyCode:r}=this.makeSpendCheck(t),c=n.spendTargets[0],{publicAddress:i,nativeAmount:a}=c;if(i==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new b.$D;if((0,m.eq)(a,"0"))throw new b.$D;const o=(0,m.add)(a,this.networkInfo.defaultNetworkFee);if((0,m.gt)(o,(e=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?e:"0"))throw new b.C_;if((0,m.gt)(o,this.availableZatoshi))throw new b.C_("Amount exceeds available balance");const k=n.spendTargets.map(R=>{var V;return{uniqueIdentifier:R.uniqueIdentifier,memo:R.memo,nativeAmount:(V=R.nativeAmount)!=null?V:"0",currencyCode:r,publicAddress:i}});return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:`-${o}`,isSend:a.startsWith("-"),networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:[],signedTx:"",spendTargets:k,walletId:this.walletId}})}signTx(t){return p(this,null,function*(){return t})}broadcastTx(t,e){return p(this,null,function*(){var n,r;const c=P(this.pluginId)(e==null?void 0:e.privateKeys);if(t.spendTargets==null||t.spendTargets.length!==1)throw new Error("Invalid spend targets");const i=t.spendTargets[0],a={zatoshi:(0,m.sub)((0,m.abs)(t.nativeAmount),t.networkFee),toAddress:i.publicAddress,memo:(r=(n=i.memo)!=null?n:i.uniqueIdentifier)!=null?r:"",fromAccountIndex:0,spendingKey:c.spendKey};try{const o=yield this.synchronizer.sendToAddress(a);t.txid=o.txId,t.signedTx=o.raw,t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
- ${(0,K.oX)(t)}`)}catch(o){throw this.warn("FAILURE broadcastTx failed: ",o),o}return t})}getDisplayPrivateSeed(t){return P(this.pluginId)(t).mnemonic}getDisplayPublicSeed(){var t,e;return(e=(t=this.walletInfo.keys.unifiedViewingKeys)==null?void 0:t.extfvk)!=null?e:""}loadEngine(t,e,n){return p(this,null,function*(){yield w(I.prototype,this,"loadEngine").call(this,t,e,n),this.engineOn=!0;const{rpcNode:r}=this.networkInfo;this.initializer=L({fullViewingKey:e.keys.unifiedViewingKeys,birthdayHeight:e.keys.birthdayHeight,alias:e.keys.publicKey},r)})}}function x(s,t,e,n){return p(this,null,function*(){const r=N(e),{makeSynchronizer:c}=s.nativeIo["edge-currency-accountbased"][s.networkInfo.nativeSdk],i=new I(s,t,r,n,c);return yield i.loadEngine(t,r,n),i})}var v=(s,t,e)=>new Promise((n,r)=>{var c=o=>{try{a(e.next(o))}catch(k){r(k)}},i=o=>{try{a(e.throw(o))}catch(k){r(k)}},a=o=>o.done?n(o.value):Promise.resolve(o.value).then(c,i);a((e=e.apply(s,t)).next())});class E{constructor(t){const{builtinTokens:e,currencyInfo:n,io:r,networkInfo:c}=t;this.builtinTokens=e,this.currencyInfo=n,this.io=r,this.networkInfo=c;const i=t.nativeIo["edge-currency-accountbased"];if(i==null)throw new Error("Need opts");const{KeyTool:a,AddressTool:o}=i[this.networkInfo.nativeSdk];this.KeyTool=a,this.AddressTool=o}getNewWalletBirthdayBlockheight(){return v(this,null,function*(){try{return yield this.KeyTool.getBirthdayHeight(this.networkInfo.rpcNode.defaultHost,this.networkInfo.rpcNode.defaultPort)}catch{return this.networkInfo.defaultBirthday}})}isValidAddress(t){return v(this,null,function*(){return(yield this.AddressTool.isValidShieldedAddress(t))||(yield this.AddressTool.isValidTransparentAddress(t))})}importPrivateKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;if(!(0,T.validateMnemonic)(t))throw new Error(`Invalid ${this.currencyInfo.currencyCode} mnemonic`);const c=(yield(0,T.mnemonicToSeed)(t)).toString("hex"),i=yield this.KeyTool.deriveSpendingKey(c,this.networkInfo.rpcNode.networkName);if(typeof i!="string")throw new Error("Invalid spendKey type");const a=yield this.getNewWalletBirthdayBlockheight();return{[`${e}Mnemonic`]:t,[`${e}SpendKey`]:i,[`${e}BirthdayHeight`]:a}})}createPrivateKey(t){return v(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=z.Buffer.from(this.io.random(32)).toString("hex"),n=(0,T.entropyToMnemonic)(e);return yield this.importPrivateKey(n)})}checkPublicKey(t){return v(this,null,function*(){try{return H(t),!0}catch{return!1}})}derivePublicKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo,n=P(e)(t.keys);if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const r=n.mnemonic;if(typeof r!="string")throw new Error("InvalidMnemonic");const i=(yield(0,T.mnemonicToSeed)(r)).toString("hex"),a=yield this.KeyTool.deriveViewingKey(i,this.networkInfo.rpcNode.networkName),o=yield this.AddressTool.deriveShieldedAddress(a.extfvk,this.networkInfo.rpcNode.networkName);return{birthdayHeight:n.birthdayHeight,publicKey:o,unifiedViewingKeys:a}})}parseUri(t,e,n){return v(this,null,function*(){const{pluginId:r}=this.currencyInfo,c={[r]:!0},{edgeParsedUri:i,edgeParsedUri:{publicAddress:a}}=(0,B.k)(this.currencyInfo,t,c,e!=null?e:this.currencyInfo.currencyCode,n);if(a==null||!(yield this.isValidAddress(a)))throw new Error("InvalidPublicAddressError");return i})}encodeUri(t,e){return v(this,null,function*(){const{pluginId:n}=this.currencyInfo,{nativeAmount:r,currencyCode:c,publicAddress:i}=t;if(!(yield this.isValidAddress(i)))throw new Error("InvalidPublicAddressError");let a;if(r!=null){const k=(0,K.cp)(this.currencyInfo,c!=null?c:this.currencyInfo.currencyCode,e);if(k==null)throw new Error("InternalErrorInvalidCurrencyCode");a=(0,m.div)(r,k.multiplier,18)}return(0,B.Q)(t,`${n}`,a)})}}function S(s){return v(this,null,function*(){return new E(s)})}},52361:function(){},94616:function(){}}]);
1
+ (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[159],{79014:function(W,D,d){"use strict";d.d(D,{Q:function(){return $},k:function(){return b}});var m=d(77591),T=d.n(m),M=d(24350),B=d(84564),K=d.n(B),h=d(76714),z=Object.defineProperty,O=Object.getOwnPropertySymbols,U=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,x=(l,y,f)=>y in l?z(l,y,{enumerable:!0,configurable:!0,writable:!0,value:f}):l[y]=f,P=(l,y)=>{for(var f in y||(y={}))U.call(y,f)&&x(l,f,y[f]);if(O)for(var f of O(y))H.call(y,f)&&x(l,f,y[f]);return l};function b(l,y,f,g,A){const u=P({},K()(y,{},!0)),C=y.startsWith(`${l.pluginId}://`);if(u.protocol!=null&&(u.protocol=u.protocol.replace(":","")),u.protocol!=null&&u.protocol!==""&&!f[u.protocol])throw new Error(`Uri protocol '${u.protocol}' is not supported for ${l.pluginId}.`);if(u.host===""&&u.pathname==="")throw new Error("Path and host not found in uri.");const w={publicAddress:u.host!==""?u.host:u.pathname.split("/")[0]},p=u.query.label,I=u.query.message,N=u.query.category;(p!=null||I!=null||N!=null||C)&&(w.metadata={},w.metadata.name=p,w.metadata.notes=I,w.metadata.category=N,w.metadata.gateway=C!=null?C:!1);const v=u.query.amount;if(v!=null&&typeof v=="string"){g==null&&(g=l.currencyCode);const E=(0,h.cp)(l,g!=null?g:"",A);if(E==null)throw new Error("InternalErrorInvalidCurrencyCode");let S=(0,m.mul)(v,E.multiplier);S=(0,m.toFixed)(S,0,0),w.nativeAmount=S,w.currencyCode=g}return{edgeParsedUri:w,parsedUri:u}}function $(l,y,f){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&l.label==null&&l.message==null)return l.publicAddress;{let g="";f!=null&&(g+="amount="+f+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(g+="label="+l.label+"&"),typeof l.message=="string"&&(g+="message="+l.message+"&")),g=g.substr(0,g.length-1);const A={scheme:y,path:l.publicAddress,query:g};return(0,M.qC)(A)}}},940:function(W,D,d){"use strict";d.r(D),d.d(D,{ZcashTools:function(){return E},makeCurrencyEngine:function(){return N},makeCurrencyTools:function(){return S}});var m=d(77591),T=d(2153),M=d(48764),B=d(79014),K=d(76714),h=d(82448),z=d(62177);const O=(0,h.su)({first:h.mH,last:h.mH}),U=(0,h.su)({alias:(0,h.Vk)(h.XC),blockRange:(0,h.Vk)(O,{first:0,last:0})}),H=(0,h.su)({birthdayHeight:h.mH,publicKey:h.XC,unifiedViewingKeys:(0,h.su)({extfvk:h.XC,extpub:h.XC})}),x=(0,z.jd)(H),P=s=>{const t=(0,h.su)({[`${s}Mnemonic`]:h.XC,[`${s}SpendKey`]:h.XC,[`${s}BirthdayHeight`]:h.mH});return(0,h.W1)(e=>{const n=t(e);return{mnemonic:n[`${s}Mnemonic`],spendKey:n[`${s}SpendKey`],birthdayHeight:n[`${s}BirthdayHeight`]}},e=>({[`${s}Mnemonic`]:e.mnemonic,[`${s}SpendKey`]:e.spendKey,[`${s}BirthdayHeight`]:e.birthdayHeight}))};var b=d(94935),$=d(50244),l=Object.defineProperty,y=Object.getOwnPropertySymbols,f=Object.getPrototypeOf,g=Object.prototype.hasOwnProperty,A=Object.prototype.propertyIsEnumerable,u=Reflect.get,C=(s,t,e)=>t in s?l(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,L=(s,t)=>{for(var e in t||(t={}))g.call(t,e)&&C(s,e,t[e]);if(y)for(var e of y(t))A.call(t,e)&&C(s,e,t[e]);return s},w=(s,t,e)=>u(f(s),e,t),p=(s,t,e)=>new Promise((n,r)=>{var c=o=>{try{a(e.next(o))}catch(k){r(k)}},i=o=>{try{a(e.throw(o))}catch(k){r(k)}},a=o=>o.done?n(o.value):Promise.resolve(o.value).then(c,i);a((e=e.apply(s,t)).next())});class I extends $.P{constructor(t,e,n,r,c){super(t,e,n,r);const{networkInfo:i}=t;this.pluginId=this.currencyInfo.pluginId,this.networkInfo=i,this.makeSynchronizer=c,this.queryMutex=!1}setOtherData(t){this.otherData=U(t)}initData(){const{birthdayHeight:t,alias:e}=this.initializer;this.otherData.blockRange.first===0&&(this.otherData.blockRange={first:t,last:t}),this.alias=e,this.initialNumBlocksToDownload=-1,this.synchronizerStatus="DISCONNECTED",this.availableZatoshi="0",this.progressRatio=0}initSubscriptions(){this.synchronizer.on("update",t=>p(this,null,function*(){const{lastDownloadedHeight:e,scanProgress:n,networkBlockHeight:r}=t;this.onUpdateBlockHeight(r),this.onUpdateProgress(e,n,r),yield this.queryAll()})),this.synchronizer.on("statusChanged",t=>p(this,null,function*(){this.synchronizerStatus=t.name,yield this.queryAll()}))}queryAll(){return p(this,null,function*(){if(!this.queryMutex){this.queryMutex=!0;try{yield this.queryBalance(),yield this.queryTransactions(),this.onUpdateTransactions()}catch{}this.queryMutex=!1}})}onUpdateBlockHeight(t){this.walletLocalData.blockHeight!==t&&(this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}onUpdateProgress(t,e,n){if(!this.addressesChecked&&!this.isSynced()){this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=e*.99/100;let r=0;if(t>0){const i=n-t;this.initialNumBlocksToDownload<0&&(this.initialNumBlocksToDownload=i),r=i===0||this.initialNumBlocksToDownload===0?1:1-i/this.initialNumBlocksToDownload}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=r*.8;const c=(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]+this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode])/2;c!==this.progressRatio&&(Math.abs(c-this.progressRatio)>.1||c===1)&&(this.progressRatio=c,this.updateOnAddressesChecked())}}startEngine(){return p(this,null,function*(){this.initData(),this.synchronizer=yield this.makeSynchronizer(this.initializer),yield this.synchronizer.start(),this.initSubscriptions(),yield w(I.prototype,this,"startEngine").call(this)})}isSynced(){return this.synchronizerStatus==="SYNCED"}queryBalance(){return p(this,null,function*(){if(!!this.isSynced())try{const t=yield this.synchronizer.getShieldedBalance();if(t.totalZatoshi==="-1")return;this.availableZatoshi=t.availableZatoshi,this.updateBalance(this.currencyInfo.currencyCode,t.totalZatoshi)}catch(t){this.warn("Failed to update balances",t),this.updateBalance(this.currencyInfo.currencyCode,"0")}})}queryTransactions(){return p(this,null,function*(){try{let t=this.otherData.blockRange.first,e=this.otherData.blockRange.last;for(;this.isSynced()&&e<=this.walletLocalData.blockHeight;){if((yield this.synchronizer.getTransactions({first:t,last:e})).forEach(r=>this.processTransaction(r)),e===this.walletLocalData.blockHeight){t=this.walletLocalData.blockHeight,this.walletLocalDataDirty=!0,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked();break}t=e+1,e=e+this.networkInfo.transactionQueryLimit<this.walletLocalData.blockHeight?e+this.networkInfo.transactionQueryLimit:this.walletLocalData.blockHeight,this.otherData.blockRange={first:t,last:e},this.walletLocalDataDirty=!0}}catch(t){this.error(`Error querying ${this.currencyInfo.currencyCode} transactions `,t)}})}processTransaction(t){let e=t.value;const n=[];t.toAddress!=null?e=`-${(0,m.add)(e,this.networkInfo.defaultNetworkFee)}`:n.push(this.walletInfo.keys.publicKey);const r={txid:t.rawTransactionId,date:t.blockTimeInSeconds,currencyCode:this.currencyInfo.currencyCode,blockHeight:t.minedHeight,nativeAmount:e,isSend:e.startsWith("-"),networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:n,signedTx:"",otherParams:{},walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,r)}killEngine(){return p(this,null,function*(){yield this.synchronizer.stop(),yield w(I.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return p(this,null,function*(){yield w(I.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield w(I.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine(),this.synchronizer.rescan(this.walletInfo.keys.birthdayHeight).catch(t=>this.warn("resyncBlockchain failed: ",t))})}getMaxSpendable(){return p(this,null,function*(){const t=(0,m.sub)(this.availableZatoshi,this.networkInfo.defaultNetworkFee);if((0,m.lte)(t,"0"))throw new b.C_;return t})}makeSpend(t){return p(this,null,function*(){var e;if(!this.isSynced())throw new Error("Cannot spend until wallet is synced");const{edgeSpendInfo:n,currencyCode:r}=this.makeSpendCheck(t),c=n.spendTargets[0],{publicAddress:i,nativeAmount:a}=c;if(i==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new b.$D;if((0,m.eq)(a,"0"))throw new b.$D;const o=(0,m.add)(a,this.networkInfo.defaultNetworkFee);if((0,m.gt)(o,(e=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?e:"0"))throw new b.C_;if((0,m.gt)(o,this.availableZatoshi))throw new b.C_("Amount exceeds available balance");const k=n.spendTargets.map(R=>{var V;return{uniqueIdentifier:R.uniqueIdentifier,memo:R.memo,nativeAmount:(V=R.nativeAmount)!=null?V:"0",currencyCode:r,publicAddress:i}});return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:`-${o}`,isSend:a.startsWith("-"),networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:[],signedTx:"",spendTargets:k,walletId:this.walletId}})}signTx(t){return p(this,null,function*(){return t})}broadcastTx(t,e){return p(this,null,function*(){var n,r;const c=P(this.pluginId)(e==null?void 0:e.privateKeys);if(t.spendTargets==null||t.spendTargets.length!==1)throw new Error("Invalid spend targets");const i=t.spendTargets[0],a={zatoshi:(0,m.sub)((0,m.abs)(t.nativeAmount),t.networkFee),toAddress:i.publicAddress,memo:(r=(n=i.memo)!=null?n:i.uniqueIdentifier)!=null?r:"",fromAccountIndex:0,spendingKey:c.spendKey};try{const o=yield this.synchronizer.sendToAddress(a);t.txid=o.txId,t.signedTx=o.raw,t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
+ ${(0,K.oX)(t)}`)}catch(o){throw this.warn("FAILURE broadcastTx failed: ",o),o}return t})}getDisplayPrivateSeed(t){return P(this.pluginId)(t).mnemonic}getDisplayPublicSeed(){var t,e;return(e=(t=this.walletInfo.keys.unifiedViewingKeys)==null?void 0:t.extfvk)!=null?e:""}loadEngine(t,e,n){return p(this,null,function*(){yield w(I.prototype,this,"loadEngine").call(this,t,e,n),this.engineOn=!0;const{rpcNode:r}=this.networkInfo;this.initializer=L({fullViewingKey:e.keys.unifiedViewingKeys,birthdayHeight:e.keys.birthdayHeight,alias:e.keys.publicKey},r)})}}function N(s,t,e,n){return p(this,null,function*(){const r=x(e),{makeSynchronizer:c}=s.nativeIo["edge-currency-accountbased"][s.networkInfo.nativeSdk],i=new I(s,t,r,n,c);return yield i.loadEngine(t,r,n),i})}var v=(s,t,e)=>new Promise((n,r)=>{var c=o=>{try{a(e.next(o))}catch(k){r(k)}},i=o=>{try{a(e.throw(o))}catch(k){r(k)}},a=o=>o.done?n(o.value):Promise.resolve(o.value).then(c,i);a((e=e.apply(s,t)).next())});class E{constructor(t){const{builtinTokens:e,currencyInfo:n,io:r,networkInfo:c}=t;this.builtinTokens=e,this.currencyInfo=n,this.io=r,this.networkInfo=c;const i=t.nativeIo["edge-currency-accountbased"];if(i==null)throw new Error("Need opts");const{KeyTool:a,AddressTool:o}=i[this.networkInfo.nativeSdk];this.KeyTool=a,this.AddressTool=o}getNewWalletBirthdayBlockheight(){return v(this,null,function*(){try{return yield this.KeyTool.getBirthdayHeight(this.networkInfo.rpcNode.defaultHost,this.networkInfo.rpcNode.defaultPort)}catch{return this.networkInfo.defaultBirthday}})}isValidAddress(t){return v(this,null,function*(){return(yield this.AddressTool.isValidShieldedAddress(t))||(yield this.AddressTool.isValidTransparentAddress(t))})}importPrivateKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;if(!(0,T.validateMnemonic)(t))throw new Error(`Invalid ${this.currencyInfo.currencyCode} mnemonic`);const c=(yield(0,T.mnemonicToSeed)(t)).toString("hex"),i=yield this.KeyTool.deriveSpendingKey(c,this.networkInfo.rpcNode.networkName);if(typeof i!="string")throw new Error("Invalid spendKey type");const a=yield this.getNewWalletBirthdayBlockheight();return{[`${e}Mnemonic`]:t,[`${e}SpendKey`]:i,[`${e}BirthdayHeight`]:a}})}createPrivateKey(t){return v(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=M.Buffer.from(this.io.random(32)).toString("hex"),n=(0,T.entropyToMnemonic)(e);return yield this.importPrivateKey(n)})}checkPublicKey(t){return v(this,null,function*(){try{return H(t),!0}catch{return!1}})}derivePublicKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo,n=P(e)(t.keys);if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const r=n.mnemonic;if(typeof r!="string")throw new Error("InvalidMnemonic");const i=(yield(0,T.mnemonicToSeed)(r)).toString("hex"),a=yield this.KeyTool.deriveViewingKey(i,this.networkInfo.rpcNode.networkName),o=yield this.AddressTool.deriveShieldedAddress(a.extfvk,this.networkInfo.rpcNode.networkName);return{birthdayHeight:n.birthdayHeight,publicKey:o,unifiedViewingKeys:a}})}parseUri(t,e,n){return v(this,null,function*(){const{pluginId:r}=this.currencyInfo,c={[r]:!0},{edgeParsedUri:i,edgeParsedUri:{publicAddress:a}}=(0,B.k)(this.currencyInfo,t,c,e!=null?e:this.currencyInfo.currencyCode,n);if(a==null||!(yield this.isValidAddress(a)))throw new Error("InvalidPublicAddressError");return i})}encodeUri(t,e){return v(this,null,function*(){const{pluginId:n}=this.currencyInfo,{nativeAmount:r,currencyCode:c,publicAddress:i}=t;if(!(yield this.isValidAddress(i)))throw new Error("InvalidPublicAddressError");let a;if(r!=null){const k=(0,K.cp)(this.currencyInfo,c!=null?c:this.currencyInfo.currencyCode,e);if(k==null)throw new Error("InternalErrorInvalidCurrencyCode");a=(0,m.div)(r,k.multiplier,18)}return(0,B.Q)(t,`${n}`,a)})}}function S(s){return v(this,null,function*(){return new E(s)})}},52361:function(){},94616:function(){}}]);
@@ -0,0 +1,7 @@
1
+ {
2
+ "network": "main",
3
+ "height": "2370000",
4
+ "hash": "00000000340a7c9e22b03014f48bf1e23f7fa6926e81b16546456f9c9b1104a9",
5
+ "time": 1682427153,
6
+ "tree": "014ca89b7a5caa4922f9184b63d6b37f8f46cc761e9324b754581b3d410a9ab12d018b6142472e37cad995f6e1468ee3e41c25ceb3645c2837d309d4ac5401d9e953160001aa785c817746f9b28d2a7d10ccda7002579fd28ab4225d6417f2247b45c133700187ab07133a32f683f095b0dd2b99699ec78dd47c6e2b4d7893df9a52b4ccfb6c000123556c528607f1c80526533232a2d1e0cf7afdf69459fc1bcc1ee06150e6335301d3f07248ed05de39c90492c45cf2c44e878aff8509d86f8788ab5dc7428c893301e9caaef6f065bd1603748517e4eb1496511da5f0ea0631496d2e61a37ff91c4a000154bc73adc46b7d5c5cf310f5f3fac498d6cfdfb7820768300489f3e5e08f357301bf8358e8dfb2c65c9c43b4c29c69d31125ba57744c13ce206d0bfc7f479eff1b000134840fe9bedf0ba8febec5b8be59fcceebf6461aa005f04a765417dfa3477d180001c51548cd85f65cbd9e40506b4aee2ae3bc1b86af0d9b0f989b8a717ff18036590001dd905dcb9771a3f6335a20631deebb05b1476ed4e20c44e666d0e4f648c0df1b000160572a707445e6b455ce8424754846cf8ecff73c2c54b1516ac056e6d3f7f46b0142cecf7947fc45e642b8a7037cafa8aea7b0eea399004201661f75bdfcbffe0f00000142380298196ed6f9abece6970296f762f7b2d6a367ca7df2b3e201aa10ed090f"
7
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "network": "main",
3
+ "height": "2070000",
4
+ "hash": "0000000000c650a4302fb497b15c714e8cacdab37df46a2d71b40a5038e1e435",
5
+ "time": 1682880164,
6
+ "tree": "01c13c30e7847528d1c19a75ee2bb8409adf4f2a19243720b40f9d1bc3d0ea6721001a0001bee4854d5be74873435f99b491b9299472cfd0f256e849a730142452ea5cdf1e01f126419bc4ef3d15bed33be951bd4ad1179c5b6fc4107d72076c0817f338670501fd48689ab3ec10ba3041eabf51092ec247d3f88edd6561c195f2877aca52fd0601b97c0935791c0f4d74c472312ad2fb03f1a4aec530cf6d04297ad05578b6aa4f0000013f5b3bf37e29a00d21f8feac49984942c9dd638d47d595bccd646e209b9559680103db5d28818a53603a78f163d3f9f3d042bcd402745e05ab41345c935ee0b34a0001cb145ea16b2135b0ee2ab2047a379ce022c839004a64e6cbda641783d462c33f000154e27fe3da582c13ae9a91c7e8bd55090c02ddda73542f08b4f9c288b4744b2c000000000001e1c882101803f4307fef0296028169358d583e3c2f95e37973aa8078e3f5550a0000011619f99023a69bb647eab2d2aa1a73c3673c74bb033c3c4930eacda19e6fd93b0000000160272b134ca494b602137d89e528c751c06d3ef4a87a45f33af343c15060cc1e"
7
+ }
@@ -211,6 +211,8 @@ const TRANSACTION_POLL_MILLISECONDS = 3000
211
211
  this.tools.walletConnectors[uri].walletId = walletId
212
212
  },
213
213
  wcDisconnect: (uri) => {
214
+ if (_optionalChain([this, 'access', _2 => _2.tools, 'access', _3 => _3.walletConnectors, 'access', _4 => _4[uri], 'optionalAccess', _5 => _5.connector]) == null) return
215
+
214
216
  this.tools.walletConnectors[uri].connector.killSession().catch(() => {})
215
217
  // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
216
218
  delete this.tools.walletConnectors[uri]
@@ -670,7 +672,7 @@ const TRANSACTION_POLL_MILLISECONDS = 3000
670
672
  )
671
673
  if (edgeTokenId == null) throw new Error('Unrecognized asset')
672
674
  const networkLocation = _algorandTypes.asMaybeContractAddressLocation.call(void 0,
673
- _optionalChain([this, 'access', _2 => _2.allTokensMap, 'optionalAccess', _3 => _3[edgeTokenId], 'optionalAccess', _4 => _4.networkLocation])
675
+ _optionalChain([this, 'access', _6 => _6.allTokensMap, 'optionalAccess', _7 => _7[edgeTokenId], 'optionalAccess', _8 => _8.networkLocation])
674
676
  )
675
677
 
676
678
  if (networkLocation == null) throw new Error('Unrecognized asset')
@@ -833,7 +835,7 @@ const TRANSACTION_POLL_MILLISECONDS = 3000
833
835
  )
834
836
  if (paymentTokenId != null)
835
837
  throw new Error(`Must activate with ${this.currencyInfo.currencyCode}`)
836
- if (_optionalChain([paymentWallet, 'optionalAccess', _5 => _5.id]) !== this.walletId)
838
+ if (_optionalChain([paymentWallet, 'optionalAccess', _9 => _9.id]) !== this.walletId)
837
839
  throw new Error('Must pay with same wallet you are activating token with')
838
840
 
839
841
  const minTxFee = this.networkInfo.minimumTxFee.toFixed()
@@ -437,6 +437,8 @@ var _feeProviders = require('./fees/feeProviders');
437
437
  this.tools.walletConnectors[uri].walletId = walletId
438
438
  },
439
439
  wcDisconnect: (uri) => {
440
+ if (_optionalChain([this, 'access', _2 => _2.tools, 'access', _3 => _3.walletConnectors, 'access', _4 => _4[uri], 'optionalAccess', _5 => _5.connector]) == null) return
441
+
440
442
  this.tools.walletConnectors[uri].connector.killSession().catch(() => {})
441
443
  // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
442
444
  delete this.tools.walletConnectors[uri]
@@ -778,7 +780,7 @@ var _feeProviders = require('./fees/feeProviders');
778
780
  throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`)
779
781
  }
780
782
 
781
- let data = _nullishCoalesce(spendTarget.memo, () => ( _optionalChain([spendTarget, 'access', _2 => _2.otherParams, 'optionalAccess', _3 => _3.data])))
783
+ let data = _nullishCoalesce(spendTarget.memo, () => ( _optionalChain([spendTarget, 'access', _6 => _6.otherParams, 'optionalAccess', _7 => _7.data])))
782
784
  if (data != null && data.length > 0 && !_utils.isHex.call(void 0, data)) {
783
785
  throw new Error(`Memo/data field must be of type 'hex'`)
784
786
  }
@@ -1228,7 +1230,7 @@ var _feeProviders = require('./fees/feeProviders');
1228
1230
  )
1229
1231
  if (replacedTxIndex === -1) {
1230
1232
  if (
1231
- _optionalChain([txOtherParams, 'optionalAccess', _4 => _4.replacedTxid]) != null &&
1233
+ _optionalChain([txOtherParams, 'optionalAccess', _8 => _8.replacedTxid]) != null &&
1232
1234
  txOtherParams.replacedTxid !== ''
1233
1235
  ) {
1234
1236
  // If the tx parameter is not found, then perhaps it is a
@@ -1345,7 +1347,7 @@ var _feeProviders = require('./fees/feeProviders');
1345
1347
  )
1346
1348
 
1347
1349
  // We must check if this transaction replaces another transaction
1348
- if (_optionalChain([txOtherParams, 'optionalAccess', _5 => _5.replacedTxid]) != null) {
1350
+ if (_optionalChain([txOtherParams, 'optionalAccess', _9 => _9.replacedTxid]) != null) {
1349
1351
  const { currencyCode } = edgeTransaction
1350
1352
  const txid = _utils.normalizeAddress.call(void 0, txOtherParams.replacedTxid)
1351
1353
  const index = this.findTransaction(currencyCode, txid)
@@ -1372,7 +1374,7 @@ var _feeProviders = require('./fees/feeProviders');
1372
1374
  // Update the unconfirmed nonce if the transaction being saved is not confirmed
1373
1375
  if (edgeTransaction.blockHeight === 0) {
1374
1376
  const nonceUsed =
1375
- _optionalChain([edgeTransaction, 'access', _6 => _6.otherParams, 'optionalAccess', _7 => _7.nonceUsed])
1377
+ _optionalChain([edgeTransaction, 'access', _10 => _10.otherParams, 'optionalAccess', _11 => _11.nonceUsed])
1376
1378
  if (nonceUsed != null) {
1377
1379
  this.otherData.unconfirmedNextNonce = _biggystring.add.call(void 0, nonceUsed, '1')
1378
1380
  }
@@ -45,6 +45,7 @@ var _zecTypes = require('./zecTypes');
45
45
 
46
46
 
47
47
 
48
+
48
49
 
49
50
 
50
51
 
@@ -60,6 +61,7 @@ var _zecTypes = require('./zecTypes');
60
61
  this.pluginId = this.currencyInfo.pluginId
61
62
  this.networkInfo = networkInfo
62
63
  this.makeSynchronizer = makeSynchronizer
64
+ this.queryMutex = false
63
65
  }
64
66
 
65
67
  setOtherData(raw) {
@@ -103,9 +105,14 @@ var _zecTypes = require('./zecTypes');
103
105
  }
104
106
 
105
107
  async queryAll() {
106
- await this.queryBalance()
107
- await this.queryTransactions()
108
- this.onUpdateTransactions()
108
+ if (this.queryMutex) return
109
+ this.queryMutex = true
110
+ try {
111
+ await this.queryBalance()
112
+ await this.queryTransactions()
113
+ this.onUpdateTransactions()
114
+ } catch (e) {}
115
+ this.queryMutex = false
109
116
  }
110
117
 
111
118
  onUpdateBlockHeight(networkBlockHeight) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "edge-currency-accountbased",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Edge currency plugin for account based currencies",
5
5
  "homepage": "https://edge.app/",
6
6
  "repository": {