edge-currency-accountbased 2.4.0 → 2.4.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,12 @@
1
1
  # edge-currency-accountbased
2
2
 
3
+ ## 2.4.1 (2023-09-14)
4
+
5
+ - changed: Update react-native-zcash to v0.4.2
6
+ - fixed: Fixed Zcash transaction memos array handling
7
+ - fixed: Add `0x` prefix to EVM data created outside the engine
8
+ - fixed: Roundup fee nativeAmount returned from L1 so it is an integer
9
+
3
10
  ## 2.4.0 (2023-09-13)
4
11
 
5
12
  changed: Upgrade react-native-zcash to v0.4.1
@@ -1,11 +1,11 @@
1
- (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[513],{86352:function(Se,oe,P){"use strict";P.d(oe,{Vn:function(){return ae},lF:function(){return S},sp:function(){return ee}});var g=P(76714),J=(G,p,X)=>new Promise((n,j)=>{var Z=I=>{try{F(X.next(I))}catch(O){j(O)}},T=I=>{try{F(X.throw(I))}catch(O){j(O)}},F=I=>I.done?n(I.value):Promise.resolve(I.value).then(Z,T);F((X=X.apply(G,p)).next())});const q=["https://info1.edge.app","https://info2.edge.app"];function ie(G,p,X){return J(this,arguments,function*(n,j,Z,T=5e3,F=fetch){const I=n.map(O=>()=>J(this,null,function*(){const Q=yield F(O+"/"+j,Z);if(typeof Q!="object"){const B=`Invalid return value ${j} in ${O}`;throw console.log(B),new Error(B)}return Q}));return yield(0,g.QJ)(I,T)})}function S(G,p,X,n,j=5e3,Z){return J(this,null,function*(){const T=yield ie((0,g.Sy)(p),X,n,j,Z);if(!T.ok){const O=yield T.text();throw console.error(O),new Error(`Error fetching ${X}: ${O}`)}const F=yield T.json();return G(F)})}function le(G,p,X,n=5e3,j){return J(this,null,function*(){return yield ie((0,g.Sy)(G),p,X,n,j)})}const ae=(G,p,X,n)=>J(void 0,null,function*(){return yield le(q,G,p,X,n)}),ee=G=>Object.keys(G).map(p=>{const X=G[p];return X==null?p:`${p}=${encodeURIComponent(X)}`}).join("&")},79014:function(Se,oe,P){"use strict";P.d(oe,{Q:function(){return Z},k:function(){return j}});var g=P(77591),J=P.n(g),q=P(24350),ie=P(84564),S=P.n(ie),le=P(76714),ae=Object.defineProperty,ee=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,p=Object.prototype.propertyIsEnumerable,X=(T,F,I)=>F in T?ae(T,F,{enumerable:!0,configurable:!0,writable:!0,value:I}):T[F]=I,n=(T,F)=>{for(var I in F||(F={}))G.call(F,I)&&X(T,I,F[I]);if(ee)for(var I of ee(F))p.call(F,I)&&X(T,I,F[I]);return T};function j(T,F,I,O,Q=[]){const B=n({},S()(F,{},!0)),he=F.startsWith(`${T.pluginId}://`);if(B.protocol!=null&&(B.protocol=B.protocol.replace(":","")),B.protocol!=null&&B.protocol!==""&&!I[B.protocol])throw new Error(`Uri protocol '${B.protocol}' is not supported for ${T.pluginId}.`);if(B.host===""&&B.pathname==="")throw new Error("Path and host not found in uri.");const W={publicAddress:B.host!==""?B.host:B.pathname.split("/")[0]},ge=B.query.label,ue=B.query.message,be=B.query.category;(ge!=null||ue!=null||be!=null||he)&&(W.metadata={},W.metadata.name=ge,W.metadata.notes=ue,W.metadata.category=be,W.metadata.gateway=he!=null?he:!1);const te=B.query.amount;if(te!=null&&typeof te=="string"){O==null&&(O=T.currencyCode);const pe=(0,le.Qs)(O!=null?O:"",T,Q);if(pe==null)throw new Error("InternalErrorInvalidCurrencyCode");let de=(0,g.mul)(te,pe.multiplier);de=(0,g.toFixed)(de,0,0),W.nativeAmount=de,W.currencyCode=O}return{edgeParsedUri:W,parsedUri:B}}function Z(T,F,I){if(T.publicAddress==null)throw new Error("InvalidPublicAddressError");if(I==null&&T.label==null&&T.message==null)return T.publicAddress;{let O="";I!=null&&(O+="amount="+I+"&"),(T.label!=null||T.message!=null)&&(typeof T.label=="string"&&(O+="label="+T.label+"&"),typeof T.message=="string"&&(O+="message="+T.message+"&")),O=O.substr(0,O.length-1);const Q={scheme:F,path:T.publicAddress,query:O};return(0,q.qC)(Q)}}},55773:function(Se,oe,P){"use strict";P.r(oe),P.d(oe,{EthereumTools:function(){return Qe},makeCurrencyEngine:function(){return zt},makeCurrencyTools:function(){return tn}});var g=P(77591),J=P(2153),q=P(48764),ie=P(21964),S=P.n(ie),le=P(48367),ae=P.n(le),ee=P(20918),G=P(79014),p=P(76714),X=P(74296),n=P(82448),j=P(62177);const Z=(0,n.su)({evmScanApiKey:(0,n.Zz)((0,n._C)(n.XC,(0,n._2)(n.XC))),blockcypherApiKey:(0,n.Zz)(n.XC),infuraProjectId:(0,n.Zz)(n.XC),blockchairApiKey:(0,n.Zz)(n.XC),alethioApiKey:(0,n.Zz)(n.XC),amberdataApiKey:(0,n.Zz)(n.XC),gasStationApiKey:(0,n.Zz)(n.XC),quiknodeApiKey:(0,n.Zz)(n.XC),alchemyApiKey:(0,n.Zz)(n.XC),poktPortalApiKey:(0,n.Zz)(n.XC)});function T(m){return m in Z.shape}const F=m=>{if(typeof m!="string")throw new Error("key must be a string");if(T(m))return m;throw new Error(`${m} not a key of EthereumInitOptions`)},I=(0,n.su)({minGasLimit:(0,n.Zz)(n.XC),regularTransaction:n.XC,tokenTransaction:n.XC}),O=(0,n.su)({highFee:n.XC,lowFee:n.XC,minGasPrice:(0,n.Zz)(n.XC),standardFeeLow:n.XC,standardFeeHigh:n.XC,standardFeeLowAmount:n.XC,standardFeeHighAmount:n.XC}),Q=(0,n.su)({lowFee:n.XC,standardFeeLow:n.XC,standardFeeHigh:n.XC,highFee:n.XC}),B=(0,n.su)({baseFeeMultiplier:(0,n.Zz)(Q),gasLimit:(0,n.Zz)(I),gasPrice:(0,n.Zz)(O),minPriorityFee:(0,n.Zz)(n.XC)}),he=(0,n.su)(B),Ie=(0,n.su)({blockNumber:n.XC,timeStamp:n.XC,hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),to:n.XC,from:n.XC,value:n.XC,nonce:n.XC,gasPrice:n.XC,gas:n.XC,gasUsed:n.XC,confirmations:n.XC,contractAddress:n.XC,tokenName:n.XC,tokenSymbol:n.XC,tokenDecimal:n.XC}),W=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasPrice:n.XC,gasUsed:n.XC,value:n.XC,nonce:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,confirmations:(0,n.Zz)(n.XC)}),ge=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasUsed:n.XC,value:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,contractAddress:(0,n.Zz)(n.XC)}),ue=(0,n.su)({LastBlock:n.XC,SafeGasPrice:n.XC,ProposeGasPrice:n.XC,FastGasPrice:n.XC,suggestBaseFee:(0,n.Vk)(n.XC),gasUsedRatio:(0,n.Vk)((0,n._2)(n.XC))}),be=(0,n.su)({status:n.XC,message:n.XC,result:(0,n._C)(n.XC,(0,n.su)(ue))}),te=(0,n.su)({from:(0,n._2)(n.XC),to:(0,n._2)(n.XC),gas:n.XC,gasPrice:n.XC,gasUsed:n.XC,tokenRecipientAddress:(0,n.Zz)(n.XC),nonceUsed:(0,n.Zz)(n.XC),replacedTxid:(0,n.Zz)(n.XC),data:(0,n.Zz)((0,n._C)(n.XC,n.gu)),isFromMakeSpend:(0,n.Zz)(n.jK,!1)}),pe=(0,n.su)({nextNonce:(0,n.Vk)(n.XC,"0"),unconfirmedNextNonce:(0,n.Vk)(n.XC,"0")}),de=(0,n.su)({blockbook:(0,n.su)({bestHeight:n.mH})}),Le=(0,n.su)({symbol:n.XC,contract:n.XC,balance:n.XC}),Ye=(0,n.su)({balance:n.XC,unconfirmedBalance:n.XC,unconfirmedTxs:n.mH,nonce:n.XC,tokens:(0,n.Vk)((0,n._2)(Le),()=>[])}),qe=(0,n.su)({balance:n.XC,token_address:n.XC,token_symbol:n.XC}),et=(0,n.su)({data:(0,n.su)((0,n.su)({address:(0,n.su)({balance:n.XC}),layer_2:(0,n.su)({erc_20:(0,n._2)((0,n.Zz)(n.XC))})}))}),tt=(0,n.su)({data:(0,n.su)({blocks:n.mH})}),nn=(0,n.su)({hash:n.XC,timestamp:n.XC,blockNumber:n.XC,value:n.XC,fee:n.XC,gasLimit:n.XC,gasPrice:n.XC,gasUsed:n.XC,from:(0,n._2)((0,n.su)({address:n.XC})),to:(0,n._2)((0,n.su)({address:n.XC}))}),Y=(0,n.su)({result:n.XC}),nt=(0,n.su)({l1Fee:n.XC}),sn=(0,n.su)({id:(0,n._C)(n.XC,n.mH),method:(0,n.Wf)("personal_sign","eth_sign","eth_signTypedData","eth_signTypedData_v4","eth_sendTransaction","eth_signTransaction","eth_sendRawTransaction"),params:(0,n._2)(n.JC)}),st=(0,n.Zz)((0,n.su)({typedData:(0,n.Zz)(n.jK,!1)}),{typedData:!1}),Fe=j.BQ,Ce=m=>{const e=m,t=(0,n.su)({[`${e}Mnemonic`]:(0,n.Zz)(n.XC),[`${e}Key`]:n.XC}),s=(0,n.su)({keys:t});return(0,n.W1)(r=>{const i=(0,n.Vk)(s)(r);if(i!=null)return{mnemonic:i.keys[`${e}Mnemonic`],privateKey:i.keys[`${e}Key`]};const h=t(r);return{mnemonic:h[`${e}Mnemonic`],privateKey:h[`${e}Key`]}},r=>({[`${e}Mnemonic`]:r.mnemonic,[`${e}Key`]:r.privateKey}))};var rt=P(2832),Oe=P.n(rt),xe=P(66052),ne=P(94935),ot=P(50144),it=P(68142),Pe=P.n(it),at=P(37217),ct=P.n(at),lt=P(84650),Be=P(72681);const se=1e9,ye=1e8,ke=3e4,ht=.75,ut=60*10*1e3,dt=5*60*1e3;var ft=P(84564),U=P.n(ft);const mt=m=>{const e=(0,n.XC)(m);if(/0[xX][0-9a-fA-F]+/.test(e))return parseInt(e,16);throw new TypeError("Expected a hex number")},gt=m=>{const e=(0,n.XC)(m);if(/0[xX][0-9a-fA-F]+/.test(e))return(0,g.add)(m,"0");throw new TypeError("Expected a hex number")},pt=(0,n.su)({result:mt}),yt=(0,n.su)({result:gt}),kt=(0,n.su)({safeLow:n.mH,average:n.mH,fast:n.mH,fastest:n.mH}),Et=(0,n.su)({types:(0,n.su)((0,n._2)((0,n.su)({name:n.XC,type:n.XC}))),primaryType:n.XC,domain:n.JC,message:n.JC});var wt=P(86352),ce=(m,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},h=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,h);c((t=t.apply(m,e)).next())});const Ee=(m,e)=>{const t=Object.keys(e);for(const s of t){const r=e[s];typeof r=="string"&&m(` ${s}: ${(0,g.div)(r,"1000000000",18)} gwei`)}},vt=(m,e,t,s,r)=>({infoFeeProvider:()=>ce(void 0,null,function*(){return yield Tt(m,e)}),externalFeeProviders:[Ct,Pt,bt].map(h=>()=>ce(void 0,null,function*(){return yield h(m,e,t,s,r)}))}),bt=(m,e,t,s,r)=>ce(void 0,null,function*(){const{rpcServers:i,supportsEIP1559:h=!1}=r;if(h)return;const c=(0,p.sD)(i,1)[0],l={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify({method:"eth_gasPrice",params:[],id:1,jsonrpc:"2.0"})},o=yield m(c,l);if(!o.ok){const k=yield o.text();throw new Error(`fetchFeesFromRpc fetch error: ${k}`)}const d=yield o.json(),a=(0,n.Vk)(Y)(d);if(a==null)throw new Error(`fetchFeesFromRpc ${c} returned invalid json: ${d}`);const{result:u}=a,f=(0,p.Z8)(u),y={lowFee:(0,g.mul)(f,"1"),standardFeeLow:(0,g.mul)(f,"1.06"),standardFeeHigh:(0,g.mul)(f,"1.12"),highFee:(0,g.mul)(f,"1.25")};return s(`fetchFeesFromRpc: ${e.currencyCode}`),Ee(s,y),y}),Ct=(m,e,t,s,r)=>ce(void 0,null,function*(){const i=r.evmScanApiServers,h=Ne(t,e,s);if(i==null||h==null)return;const c=`&apikey=${Array.isArray(h)?(0,p.sD)(h,1)[0]:h!=null?h:""}`,l=`${(0,p.sD)(i,1)[0]}/api?module=gastracker&action=gasoracle${c}`,o=yield m(l);if(!o.ok)throw new Error(`EvmScan fetch error: ${JSON.stringify(o)}`);const d=yield o.json(),a=d.message.includes("NOTOK");if(!(d!=null&&!a))throw new Error(`fetchFeesFromEvmScan unrecognized response message: ${d.message}`);const{SafeGasPrice:f,ProposeGasPrice:y,FastGasPrice:k}=ue(d.result),C=parseInt(f);let v=parseInt(y),E=parseInt(k);v<=C&&(v=C+1),E<=v&&(E=v+1);const b=`${C*se}`,L=`${(C+v)/2*se}`,D=`${E*se}`,K=`${E*se/ht}`,M={lowFee:b,standardFeeLow:L,standardFeeHigh:D,highFee:K};return s(`fetchFeesFromEvmScan: ${e.currencyCode}`),Ee(s,M),M}),Pt=(m,e,t,s,r)=>ce(void 0,null,function*(){const{ethGasStationUrl:i}=r,h=At(t,e,s);if(i==null||h==null)return;const c=h?`?api-key=${h||""}`:"",o=yield(yield m(`${i}${c}`)).json(),d=kt(o);if(e.currencyCode==="MATIC"&&(d.safeLow*=10,d.average=(o.fast+o.safeLow)/2*10,d.fast=o.standard*10,d.fastest*=10),d.safeLow<=0||d.safeLow>ke)throw new Error("Invalid safeLow value from Gas Station");if(d.average<1||d.average>ke)throw new Error("Invalid average value from Gas Station");if(d.fast<1||d.fast>ke)throw new Error("Invalid fastest value from Gas Station");if(d.fastest<1||d.fastest>ke)throw new Error("Invalid fastest value from Gas Station");d.average<=d.safeLow&&(d.average=d.safeLow+1),d.fast<=d.average&&(d.fast=d.average+1),d.fastest<=d.fast&&(d.fastest=d.fast+1);let a=d.safeLow,u=d.fast,f=((d.fast+d.fastest)*.5+d.fastest)*.5,y=f>d.fastest?f:d.fastest;a=Math.round(a)*ye,u=Math.round(u)*ye,f=Math.round(f)*ye,y=Math.round(y)*ye;const k={lowFee:a.toString(),standardFeeLow:u.toString(),standardFeeHigh:f.toString(),highFee:y.toString()};return s(`fetchFeesFromEvmGasStation: ${e.currencyCode}`),Ee(s,k),k}),Tt=(m,e)=>ce(void 0,[m,e],function*(t,{pluginId:s}){const i=yield(yield(0,wt.Vn)(`v1/networkFees/${s}`,void 0,void 0,t)).json();return he(i)}),Ne=(m,e,t)=>{const{evmScanApiKey:s,etherscanApiKey:r,ftmscanApiKey:i,bscscanApiKey:h,polygonscanApiKey:c}=m;if(s!=null)return s;const{currencyCode:l}=e;if(l==="ETH"&&r!=null)return t.warn("INIT OPTION 'etherscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),r;if(l==="FTM"&&i!=null)return t.warn("INIT OPTION 'ftmscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),i;if(l==="BNB"&&h!=null)return t.warn("INIT OPTION 'bscscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),h;if(l==="MATIC"&&c!=null)return t.warn("INIT OPTION 'polygonscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),c},At=(m,e,t)=>{const{gasStationApiKey:s,ethGasStationApiKey:r}=m;if(s!=null)return s;const{currencyCode:i}=e;if(i==="ETH"&&r!=null)return t.warn("INIT OPTION 'ethGasStationApiKey' IS DEPRECATED. USE 'gasStationApiKey' INSTEAD"),r};var St=Object.defineProperty,It=Object.defineProperties,Lt=Object.getOwnPropertyDescriptors,$e=Object.getOwnPropertySymbols,Ft=Object.prototype.hasOwnProperty,Ot=Object.prototype.propertyIsEnumerable,Re=(m,e,t)=>e in m?St(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,De=(m,e)=>{for(var t in e||(e={}))Ft.call(e,t)&&Re(m,t,e[t]);if($e)for(var t of $e(e))Ot.call(e,t)&&Re(m,t,e[t]);return m},_e=(m,e)=>It(m,Lt(e)),w=(m,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},h=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,h);c((t=t.apply(m,e)).next())});const xt=2e4,Bt=2e4,Nt=2e4,$t=2e4,Xe=4*2,Ke=2*60,Rt=50;function we(m,e){return w(this,null,function*(){return{result:yield m,server:e}})}const Te=(m,e,t)=>{let s={};try{s=_e(De({gasPrice:(0,g.div)(m,se.toString(),se.toString().length-1)},t!==void 0?{gasUsed:t}:{}),{gasLimit:e})}catch(r){console.log(`Failed to construct feeRateUssed: ${r}`)}return s};class Dt{constructor(e){this.ethEngine=e,this.ethNeeds={blockHeightLastChecked:0,nonceLastChecked:0,tokenBalLastChecked:{},tokenTxsLastChecked:{}},this.fetchGetEtherscan=this.fetchGetEtherscan.bind(this),this.multicastServers=this.multicastServers.bind(this),this.checkAddressBlockbook=this.checkAddressBlockbook.bind(this),this.checkBlockHeightEthscan=this.checkBlockHeightEthscan.bind(this),this.checkBlockHeightBlockchair=this.checkBlockHeightBlockchair.bind(this),this.checkBlockHeightAmberdata=this.checkBlockHeightAmberdata.bind(this),this.checkBlockHeightBlockbook=this.checkBlockHeightBlockbook.bind(this),this.checkNonceRpc=this.checkNonceRpc.bind(this),this.checkNonceEthscan=this.checkNonceEthscan.bind(this),this.checkNonceAmberdata=this.checkNonceAmberdata.bind(this),this.checkTokenBalEthscan=this.checkTokenBalEthscan.bind(this),this.checkTokenBalBlockchair=this.checkTokenBalBlockchair.bind(this),this.checkTokenBalRpc=this.checkTokenBalRpc.bind(this),this.checkTxsEthscan=this.checkTxsEthscan.bind(this),this.processEthereumNetworkUpdate=this.processEthereumNetworkUpdate.bind(this),this.queryFuncs=this.buildQueryFuncs(this.ethEngine.networkInfo),this.walletId=e.walletInfo.id}processEvmScanTransaction(e,t){return w(this,null,function*(){var s;const r=[],i=(s=e.hash)!=null?s:e.transactionHash;if(i==null)throw new Error("Invalid transaction result format");const h=e.from.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),c=t!==this.ethEngine.currencyInfo.currencyCode,l="gasPrice"in e?e.gasPrice:void 0,o=l!=null?(0,g.mul)(l,e.gasUsed):"0";let d="0";if(h&&this.ethEngine.networkInfo.l1RollupParams!=null){const v=yield this.multicastServers("eth_getTransactionReceipt",[i]),E=nt(v.result.result);d=(0,g.add)(d,(0,p.X0)(E.l1Fee))}let a,u,f;h?c?(a=(0,g.sub)("0",e.value),u="0",f=(0,g.add)(o,d)):e.from.toLowerCase()===e.to.toLowerCase()?(a=(0,g.sub)((0,g.sub)("0",o),d),u=(0,g.add)(o,d)):(a=(0,g.sub)((0,g.sub)((0,g.sub)("0",e.value),o),d),u=(0,g.add)(o,d)):(a=e.value,u="0",r.push(this.ethEngine.walletLocalData.publicKey));const y={from:[e.from],to:[e.to],gas:e.gas,gasPrice:l!=null?l:"",gasUsed:e.gasUsed,isFromMakeSpend:!1};let k=parseInt(e.blockNumber);return k<0&&(k=0),{blockHeight:k,currencyCode:t,date:parseInt(e.timeStamp),feeRateUsed:l!=null?Te(l,e.gas,e.gasUsed):void 0,isSend:a.startsWith("-"),memos:[],nativeAmount:a,networkFee:u,otherParams:y,ourReceiveAddresses:r,parentNetworkFee:f,signedTx:"",txid:i,walletId:this.walletId}})}processAlethioTransaction(e,t){let s;const r=[];let i;const h=t!==this.ethEngine.currencyInfo.currencyCode,c=e.attributes.value,l=e.attributes.fee?e.attributes.fee:"0",o=e.relationships.from.data.id,d=e.relationships.to.data.id;t===this.ethEngine.currencyInfo.currencyCode?i=l:i="0";const a=o.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase();if(a)o.toLowerCase()===d.toLowerCase()?s=(0,g.mul)(i,"-1"):(s=(0,g.sub)("0",c),h||(s=(0,g.sub)(s,i)));else if(d.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase())s=c,r.push(this.ethEngine.walletLocalData.publicKey.toLowerCase());else return null;const u={from:[o],to:[d],gas:"0",gasPrice:"0",gasUsed:"0",isFromMakeSpend:!1};let f=e.attributes.globalRank[0];f<0&&(f=0);let y,k="0";return h&&a?y=i:k=i,{blockHeight:f,currencyCode:t,date:e.attributes.blockCreationTime,isSend:s.startsWith("-"),memos:[],nativeAmount:s,networkFee:k,otherParams:u,ourReceiveAddresses:r,parentNetworkFee:y,signedTx:"",txid:e.relationships.transaction.data.id,walletId:this.walletId}}fetchGetEtherscan(e,t){return w(this,null,function*(){const s=Ne(this.ethEngine.initOptions,this.ethEngine.currencyInfo,this.ethEngine.log);e.indexOf("cors-http")===0&&(e=e.replace(/^cors-http/,"http"));const i=Array.isArray(s)?(0,p.sD)(s,1)[0]:s!=null?s:"",h=i!==""?`&apikey=${i}`:"",c=`${e}/api${t}`,l=yield this.ethEngine.fetchCors(`${c}${h}`);return l.ok||this.throwError(l,"fetchGetEtherscan",c),yield l.json()})}fetchGetBlockbook(e,t){return w(this,null,function*(){const s=e+t;return yield(e.includes("trezor")?yield this.ethEngine.fetchCors(s,{headers:{"User-Agent":"http.agent"}}):yield this.ethEngine.fetchCors(s)).json()})}fetchPostRPC(e,t,s,r){return w(this,null,function*(){const i={id:s,jsonrpc:"2.0",method:e,params:t},c=/{{(.*?)}}/g.exec(r);if(c!=null){const d=c[1],a=F(d),u=this.ethEngine.initOptions[a];if(typeof u=="string")r=r.replace(c[0],u);else throw u==null?new Error(`Missing ${a} in 'initOptions' for ${this.ethEngine.currencyInfo.pluginId}`):new Error("Incorrect apikey type for RPC")}const l=yield this.ethEngine.fetchCors(r,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(i)}),o=U()(r,{},!0);return l.ok||this.throwError(l,"fetchPostRPC",o.hostname),yield l.json()})}fetchPostBlockcypher(e,t,s){return w(this,null,function*(){const{blockcypherApiKey:r}=this.ethEngine.initOptions;let i="";r&&r.length>5&&(i="&token="+r);const h=`${s}/${e}${i}`,c=yield this.ethEngine.fetchCors(h,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(t)}),l=U()(h,{},!0);return c.ok||this.throwError(c,"fetchPostBlockcypher",l.hostname),yield c.json()})}fetchGetBlockchair(e,t=!1){return w(this,null,function*(){const{blockchairApiKey:s}=this.ethEngine.initOptions,{blockchairApiServers:r}=this.ethEngine.networkInfo,i=t&&s?`&key=${s}`:"",h=`${r[0]}${e}`,c=yield this.ethEngine.fetchCors(`${h}${i}`);return c.ok||this.throwError(c,"fetchGetBlockchair",h),yield c.json()})}fetchPostAmberdataRpc(e){return w(this,arguments,function*(t,s=[]){const{amberdataApiKey:r=""}=this.ethEngine.initOptions,{amberdataRpcServers:i}=this.ethEngine.networkInfo,h=`${i[0]}`,c={jsonrpc:"2.0",method:t,params:s,id:1},l=yield this.ethEngine.fetchCors(h,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":r,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(c)}),o=U()(h,{},!0);return l.ok||this.throwError(l,"fetchPostAmberdataRpc",o),yield l.json()})}fetchGetAmberdataApi(e){return w(this,null,function*(){const{amberdataApiKey:t=""}=this.ethEngine.initOptions,{amberdataApiServers:s}=this.ethEngine.networkInfo,r=`${s[0]}${e}`,i=yield this.ethEngine.fetchCors(r,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":t}});return i.ok||this.throwError(i,"fetchGetAmberdata",r),yield i.json()})}fetchGetAlethio(e,t=!0,s){return w(this,null,function*(){const{alethioApiKey:r=""}=this.ethEngine.initOptions,{alethioApiServers:i}=this.ethEngine.networkInfo,h=t?`${i[0]}${e}`:e,c=yield this.ethEngine.fetchCors(h,r?{headers:{Authorization:`Bearer ${r}`}}:void 0);return c.ok||this.throwError(c,"fetchGetAlethio",h),yield c.json()})}broadcastEtherscan(e,t){return w(this,null,function*(){const s=`?module=proxy&action=eth_sendRawTransaction&hex=${e.signedTx}`,r=yield this.fetchGetEtherscan(t,s);return this.broadcastResponseHandler(r,t,e)})}broadcastRPC(e,t,s){return w(this,null,function*(){const r="eth_sendRawTransaction",i=[e.signedTx],h=yield this.fetchPostRPC(r,i,t,s),c=U()(s,{},!0);return this.broadcastResponseHandler(h,c,e)})}broadcastBlockCypher(e,t){return w(this,null,function*(){const s=`v1/${this.ethEngine.currencyInfo.currencyCode.toLowerCase()}/main/txs/push`,r=e.signedTx.replace("0x",""),i=yield this.fetchPostBlockcypher(s,{tx:r},t);return this.broadcastResponseHandler(i,t,e)})}broadcastBlockbook(e,t){return w(this,null,function*(){const s=yield this.fetchGetBlockbook(t,`/api/v2/sendtx/${e.signedTx}`);return this.broadcastResponseHandler(s,t,e)})}broadcastResponseHandler(e,t,s){if(typeof e.error<"u")throw this.ethEngine.error(`FAILURE ${t}
1
+ (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[513],{86352:function(Se,oe,P){"use strict";P.d(oe,{Vn:function(){return ae},lF:function(){return S},sp:function(){return ee}});var m=P(76714),J=(G,p,X)=>new Promise((n,j)=>{var Z=I=>{try{F(X.next(I))}catch(O){j(O)}},T=I=>{try{F(X.throw(I))}catch(O){j(O)}},F=I=>I.done?n(I.value):Promise.resolve(I.value).then(Z,T);F((X=X.apply(G,p)).next())});const q=["https://info1.edge.app","https://info2.edge.app"];function ie(G,p,X){return J(this,arguments,function*(n,j,Z,T=5e3,F=fetch){const I=n.map(O=>()=>J(this,null,function*(){const Q=yield F(O+"/"+j,Z);if(typeof Q!="object"){const B=`Invalid return value ${j} in ${O}`;throw console.log(B),new Error(B)}return Q}));return yield(0,m.QJ)(I,T)})}function S(G,p,X,n,j=5e3,Z){return J(this,null,function*(){const T=yield ie((0,m.Sy)(p),X,n,j,Z);if(!T.ok){const O=yield T.text();throw console.error(O),new Error(`Error fetching ${X}: ${O}`)}const F=yield T.json();return G(F)})}function le(G,p,X,n=5e3,j){return J(this,null,function*(){return yield ie((0,m.Sy)(G),p,X,n,j)})}const ae=(G,p,X,n)=>J(void 0,null,function*(){return yield le(q,G,p,X,n)}),ee=G=>Object.keys(G).map(p=>{const X=G[p];return X==null?p:`${p}=${encodeURIComponent(X)}`}).join("&")},79014:function(Se,oe,P){"use strict";P.d(oe,{Q:function(){return Z},k:function(){return j}});var m=P(77591),J=P.n(m),q=P(24350),ie=P(84564),S=P.n(ie),le=P(76714),ae=Object.defineProperty,ee=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,p=Object.prototype.propertyIsEnumerable,X=(T,F,I)=>F in T?ae(T,F,{enumerable:!0,configurable:!0,writable:!0,value:I}):T[F]=I,n=(T,F)=>{for(var I in F||(F={}))G.call(F,I)&&X(T,I,F[I]);if(ee)for(var I of ee(F))p.call(F,I)&&X(T,I,F[I]);return T};function j(T,F,I,O,Q=[]){const B=n({},S()(F,{},!0)),he=F.startsWith(`${T.pluginId}://`);if(B.protocol!=null&&(B.protocol=B.protocol.replace(":","")),B.protocol!=null&&B.protocol!==""&&!I[B.protocol])throw new Error(`Uri protocol '${B.protocol}' is not supported for ${T.pluginId}.`);if(B.host===""&&B.pathname==="")throw new Error("Path and host not found in uri.");const W={publicAddress:B.host!==""?B.host:B.pathname.split("/")[0]},ge=B.query.label,ue=B.query.message,be=B.query.category;(ge!=null||ue!=null||be!=null||he)&&(W.metadata={},W.metadata.name=ge,W.metadata.notes=ue,W.metadata.category=be,W.metadata.gateway=he!=null?he:!1);const te=B.query.amount;if(te!=null&&typeof te=="string"){O==null&&(O=T.currencyCode);const pe=(0,le.Qs)(O!=null?O:"",T,Q);if(pe==null)throw new Error("InternalErrorInvalidCurrencyCode");let de=(0,m.mul)(te,pe.multiplier);de=(0,m.toFixed)(de,0,0),W.nativeAmount=de,W.currencyCode=O}return{edgeParsedUri:W,parsedUri:B}}function Z(T,F,I){if(T.publicAddress==null)throw new Error("InvalidPublicAddressError");if(I==null&&T.label==null&&T.message==null)return T.publicAddress;{let O="";I!=null&&(O+="amount="+I+"&"),(T.label!=null||T.message!=null)&&(typeof T.label=="string"&&(O+="label="+T.label+"&"),typeof T.message=="string"&&(O+="message="+T.message+"&")),O=O.substr(0,O.length-1);const Q={scheme:F,path:T.publicAddress,query:O};return(0,q.qC)(Q)}}},55773:function(Se,oe,P){"use strict";P.r(oe),P.d(oe,{EthereumTools:function(){return Qe},makeCurrencyEngine:function(){return zt},makeCurrencyTools:function(){return tn}});var m=P(77591),J=P(2153),q=P(48764),ie=P(21964),S=P.n(ie),le=P(48367),ae=P.n(le),ee=P(20918),G=P(79014),p=P(76714),X=P(74296),n=P(82448),j=P(62177);const Z=(0,n.su)({evmScanApiKey:(0,n.Zz)((0,n._C)(n.XC,(0,n._2)(n.XC))),blockcypherApiKey:(0,n.Zz)(n.XC),infuraProjectId:(0,n.Zz)(n.XC),blockchairApiKey:(0,n.Zz)(n.XC),alethioApiKey:(0,n.Zz)(n.XC),amberdataApiKey:(0,n.Zz)(n.XC),gasStationApiKey:(0,n.Zz)(n.XC),quiknodeApiKey:(0,n.Zz)(n.XC),alchemyApiKey:(0,n.Zz)(n.XC),poktPortalApiKey:(0,n.Zz)(n.XC)});function T(g){return g in Z.shape}const F=g=>{if(typeof g!="string")throw new Error("key must be a string");if(T(g))return g;throw new Error(`${g} not a key of EthereumInitOptions`)},I=(0,n.su)({minGasLimit:(0,n.Zz)(n.XC),regularTransaction:n.XC,tokenTransaction:n.XC}),O=(0,n.su)({highFee:n.XC,lowFee:n.XC,minGasPrice:(0,n.Zz)(n.XC),standardFeeLow:n.XC,standardFeeHigh:n.XC,standardFeeLowAmount:n.XC,standardFeeHighAmount:n.XC}),Q=(0,n.su)({lowFee:n.XC,standardFeeLow:n.XC,standardFeeHigh:n.XC,highFee:n.XC}),B=(0,n.su)({baseFeeMultiplier:(0,n.Zz)(Q),gasLimit:(0,n.Zz)(I),gasPrice:(0,n.Zz)(O),minPriorityFee:(0,n.Zz)(n.XC)}),he=(0,n.su)(B),Ie=(0,n.su)({blockNumber:n.XC,timeStamp:n.XC,hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),to:n.XC,from:n.XC,value:n.XC,nonce:n.XC,gasPrice:n.XC,gas:n.XC,gasUsed:n.XC,confirmations:n.XC,contractAddress:n.XC,tokenName:n.XC,tokenSymbol:n.XC,tokenDecimal:n.XC}),W=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasPrice:n.XC,gasUsed:n.XC,value:n.XC,nonce:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,confirmations:(0,n.Zz)(n.XC)}),ge=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasUsed:n.XC,value:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,contractAddress:(0,n.Zz)(n.XC)}),ue=(0,n.su)({LastBlock:n.XC,SafeGasPrice:n.XC,ProposeGasPrice:n.XC,FastGasPrice:n.XC,suggestBaseFee:(0,n.Vk)(n.XC),gasUsedRatio:(0,n.Vk)((0,n._2)(n.XC))}),be=(0,n.su)({status:n.XC,message:n.XC,result:(0,n._C)(n.XC,(0,n.su)(ue))}),te=(0,n.su)({from:(0,n._2)(n.XC),to:(0,n._2)(n.XC),gas:n.XC,gasPrice:n.XC,gasUsed:n.XC,tokenRecipientAddress:(0,n.Zz)(n.XC),nonceUsed:(0,n.Zz)(n.XC),replacedTxid:(0,n.Zz)(n.XC),data:(0,n.Zz)((0,n._C)(n.XC,n.gu)),isFromMakeSpend:(0,n.Zz)(n.jK,!1)}),pe=(0,n.su)({nextNonce:(0,n.Vk)(n.XC,"0"),unconfirmedNextNonce:(0,n.Vk)(n.XC,"0")}),de=(0,n.su)({blockbook:(0,n.su)({bestHeight:n.mH})}),Le=(0,n.su)({symbol:n.XC,contract:n.XC,balance:n.XC}),Ye=(0,n.su)({balance:n.XC,unconfirmedBalance:n.XC,unconfirmedTxs:n.mH,nonce:n.XC,tokens:(0,n.Vk)((0,n._2)(Le),()=>[])}),qe=(0,n.su)({balance:n.XC,token_address:n.XC,token_symbol:n.XC}),et=(0,n.su)({data:(0,n.su)((0,n.su)({address:(0,n.su)({balance:n.XC}),layer_2:(0,n.su)({erc_20:(0,n._2)((0,n.Zz)(n.XC))})}))}),tt=(0,n.su)({data:(0,n.su)({blocks:n.mH})}),nn=(0,n.su)({hash:n.XC,timestamp:n.XC,blockNumber:n.XC,value:n.XC,fee:n.XC,gasLimit:n.XC,gasPrice:n.XC,gasUsed:n.XC,from:(0,n._2)((0,n.su)({address:n.XC})),to:(0,n._2)((0,n.su)({address:n.XC}))}),Y=(0,n.su)({result:n.XC}),nt=(0,n.su)({l1Fee:n.XC}),sn=(0,n.su)({id:(0,n._C)(n.XC,n.mH),method:(0,n.Wf)("personal_sign","eth_sign","eth_signTypedData","eth_signTypedData_v4","eth_sendTransaction","eth_signTransaction","eth_sendRawTransaction"),params:(0,n._2)(n.JC)}),st=(0,n.Zz)((0,n.su)({typedData:(0,n.Zz)(n.jK,!1)}),{typedData:!1}),Fe=j.BQ,Ce=g=>{const e=g,t=(0,n.su)({[`${e}Mnemonic`]:(0,n.Zz)(n.XC),[`${e}Key`]:n.XC}),s=(0,n.su)({keys:t});return(0,n.W1)(r=>{const i=(0,n.Vk)(s)(r);if(i!=null)return{mnemonic:i.keys[`${e}Mnemonic`],privateKey:i.keys[`${e}Key`]};const u=t(r);return{mnemonic:u[`${e}Mnemonic`],privateKey:u[`${e}Key`]}},r=>({[`${e}Mnemonic`]:r.mnemonic,[`${e}Key`]:r.privateKey}))};var rt=P(2832),Oe=P.n(rt),xe=P(66052),ne=P(94935),ot=P(50144),it=P(68142),Pe=P.n(it),at=P(37217),ct=P.n(at),lt=P(84650),Be=P(72681);const se=1e9,ye=1e8,ke=3e4,ht=.75,ut=60*10*1e3,dt=5*60*1e3;var ft=P(84564),U=P.n(ft);const mt=g=>{const e=(0,n.XC)(g);if(/0[xX][0-9a-fA-F]+/.test(e))return parseInt(e,16);throw new TypeError("Expected a hex number")},gt=g=>{const e=(0,n.XC)(g);if(/0[xX][0-9a-fA-F]+/.test(e))return(0,m.add)(g,"0");throw new TypeError("Expected a hex number")},pt=(0,n.su)({result:mt}),yt=(0,n.su)({result:gt}),kt=(0,n.su)({safeLow:n.mH,average:n.mH,fast:n.mH,fastest:n.mH}),Et=(0,n.su)({types:(0,n.su)((0,n._2)((0,n.su)({name:n.XC,type:n.XC}))),primaryType:n.XC,domain:n.JC,message:n.JC});var wt=P(86352),ce=(g,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},u=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,u);c((t=t.apply(g,e)).next())});const Ee=(g,e)=>{const t=Object.keys(e);for(const s of t){const r=e[s];typeof r=="string"&&g(` ${s}: ${(0,m.div)(r,"1000000000",18)} gwei`)}},vt=(g,e,t,s,r)=>({infoFeeProvider:()=>ce(void 0,null,function*(){return yield Tt(g,e)}),externalFeeProviders:[Ct,Pt,bt].map(u=>()=>ce(void 0,null,function*(){return yield u(g,e,t,s,r)}))}),bt=(g,e,t,s,r)=>ce(void 0,null,function*(){const{rpcServers:i,supportsEIP1559:u=!1}=r;if(u)return;const c=(0,p.sD)(i,1)[0],l={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify({method:"eth_gasPrice",params:[],id:1,jsonrpc:"2.0"})},o=yield g(c,l);if(!o.ok){const k=yield o.text();throw new Error(`fetchFeesFromRpc fetch error: ${k}`)}const h=yield o.json(),a=(0,n.Vk)(Y)(h);if(a==null)throw new Error(`fetchFeesFromRpc ${c} returned invalid json: ${h}`);const{result:d}=a,f=(0,p.Z8)(d),y={lowFee:(0,m.mul)(f,"1"),standardFeeLow:(0,m.mul)(f,"1.06"),standardFeeHigh:(0,m.mul)(f,"1.12"),highFee:(0,m.mul)(f,"1.25")};return s(`fetchFeesFromRpc: ${e.currencyCode}`),Ee(s,y),y}),Ct=(g,e,t,s,r)=>ce(void 0,null,function*(){const i=r.evmScanApiServers,u=Ne(t,e,s);if(i==null||u==null)return;const c=`&apikey=${Array.isArray(u)?(0,p.sD)(u,1)[0]:u!=null?u:""}`,l=`${(0,p.sD)(i,1)[0]}/api?module=gastracker&action=gasoracle${c}`,o=yield g(l);if(!o.ok)throw new Error(`EvmScan fetch error: ${JSON.stringify(o)}`);const h=yield o.json(),a=h.message.includes("NOTOK");if(!(h!=null&&!a))throw new Error(`fetchFeesFromEvmScan unrecognized response message: ${h.message}`);const{SafeGasPrice:f,ProposeGasPrice:y,FastGasPrice:k}=ue(h.result),C=parseInt(f);let v=parseInt(y),E=parseInt(k);v<=C&&(v=C+1),E<=v&&(E=v+1);const b=`${C*se}`,L=`${(C+v)/2*se}`,D=`${E*se}`,K=`${E*se/ht}`,M={lowFee:b,standardFeeLow:L,standardFeeHigh:D,highFee:K};return s(`fetchFeesFromEvmScan: ${e.currencyCode}`),Ee(s,M),M}),Pt=(g,e,t,s,r)=>ce(void 0,null,function*(){const{ethGasStationUrl:i}=r,u=At(t,e,s);if(i==null||u==null)return;const c=u?`?api-key=${u||""}`:"",o=yield(yield g(`${i}${c}`)).json(),h=kt(o);if(e.currencyCode==="MATIC"&&(h.safeLow*=10,h.average=(o.fast+o.safeLow)/2*10,h.fast=o.standard*10,h.fastest*=10),h.safeLow<=0||h.safeLow>ke)throw new Error("Invalid safeLow value from Gas Station");if(h.average<1||h.average>ke)throw new Error("Invalid average value from Gas Station");if(h.fast<1||h.fast>ke)throw new Error("Invalid fastest value from Gas Station");if(h.fastest<1||h.fastest>ke)throw new Error("Invalid fastest value from Gas Station");h.average<=h.safeLow&&(h.average=h.safeLow+1),h.fast<=h.average&&(h.fast=h.average+1),h.fastest<=h.fast&&(h.fastest=h.fast+1);let a=h.safeLow,d=h.fast,f=((h.fast+h.fastest)*.5+h.fastest)*.5,y=f>h.fastest?f:h.fastest;a=Math.round(a)*ye,d=Math.round(d)*ye,f=Math.round(f)*ye,y=Math.round(y)*ye;const k={lowFee:a.toString(),standardFeeLow:d.toString(),standardFeeHigh:f.toString(),highFee:y.toString()};return s(`fetchFeesFromEvmGasStation: ${e.currencyCode}`),Ee(s,k),k}),Tt=(g,e)=>ce(void 0,[g,e],function*(t,{pluginId:s}){const i=yield(yield(0,wt.Vn)(`v1/networkFees/${s}`,void 0,void 0,t)).json();return he(i)}),Ne=(g,e,t)=>{const{evmScanApiKey:s,etherscanApiKey:r,ftmscanApiKey:i,bscscanApiKey:u,polygonscanApiKey:c}=g;if(s!=null)return s;const{currencyCode:l}=e;if(l==="ETH"&&r!=null)return t.warn("INIT OPTION 'etherscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),r;if(l==="FTM"&&i!=null)return t.warn("INIT OPTION 'ftmscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),i;if(l==="BNB"&&u!=null)return t.warn("INIT OPTION 'bscscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),u;if(l==="MATIC"&&c!=null)return t.warn("INIT OPTION 'polygonscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),c},At=(g,e,t)=>{const{gasStationApiKey:s,ethGasStationApiKey:r}=g;if(s!=null)return s;const{currencyCode:i}=e;if(i==="ETH"&&r!=null)return t.warn("INIT OPTION 'ethGasStationApiKey' IS DEPRECATED. USE 'gasStationApiKey' INSTEAD"),r};var St=Object.defineProperty,It=Object.defineProperties,Lt=Object.getOwnPropertyDescriptors,$e=Object.getOwnPropertySymbols,Ft=Object.prototype.hasOwnProperty,Ot=Object.prototype.propertyIsEnumerable,Re=(g,e,t)=>e in g?St(g,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):g[e]=t,De=(g,e)=>{for(var t in e||(e={}))Ft.call(e,t)&&Re(g,t,e[t]);if($e)for(var t of $e(e))Ot.call(e,t)&&Re(g,t,e[t]);return g},_e=(g,e)=>It(g,Lt(e)),w=(g,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},u=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,u);c((t=t.apply(g,e)).next())});const xt=2e4,Bt=2e4,Nt=2e4,$t=2e4,Xe=4*2,Ke=2*60,Rt=50;function we(g,e){return w(this,null,function*(){return{result:yield g,server:e}})}const Te=(g,e,t)=>{let s={};try{s=_e(De({gasPrice:(0,m.div)(g,se.toString(),se.toString().length-1)},t!==void 0?{gasUsed:t}:{}),{gasLimit:e})}catch(r){console.log(`Failed to construct feeRateUssed: ${r}`)}return s};class Dt{constructor(e){this.ethEngine=e,this.ethNeeds={blockHeightLastChecked:0,nonceLastChecked:0,tokenBalLastChecked:{},tokenTxsLastChecked:{}},this.fetchGetEtherscan=this.fetchGetEtherscan.bind(this),this.multicastServers=this.multicastServers.bind(this),this.checkAddressBlockbook=this.checkAddressBlockbook.bind(this),this.checkBlockHeightEthscan=this.checkBlockHeightEthscan.bind(this),this.checkBlockHeightBlockchair=this.checkBlockHeightBlockchair.bind(this),this.checkBlockHeightAmberdata=this.checkBlockHeightAmberdata.bind(this),this.checkBlockHeightBlockbook=this.checkBlockHeightBlockbook.bind(this),this.checkNonceRpc=this.checkNonceRpc.bind(this),this.checkNonceEthscan=this.checkNonceEthscan.bind(this),this.checkNonceAmberdata=this.checkNonceAmberdata.bind(this),this.checkTokenBalEthscan=this.checkTokenBalEthscan.bind(this),this.checkTokenBalBlockchair=this.checkTokenBalBlockchair.bind(this),this.checkTokenBalRpc=this.checkTokenBalRpc.bind(this),this.checkTxsEthscan=this.checkTxsEthscan.bind(this),this.processEthereumNetworkUpdate=this.processEthereumNetworkUpdate.bind(this),this.queryFuncs=this.buildQueryFuncs(this.ethEngine.networkInfo),this.walletId=e.walletInfo.id}processEvmScanTransaction(e,t){return w(this,null,function*(){var s;const r=[],i=(s=e.hash)!=null?s:e.transactionHash;if(i==null)throw new Error("Invalid transaction result format");const u=e.from.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),c=t!==this.ethEngine.currencyInfo.currencyCode,l="gasPrice"in e?e.gasPrice:void 0,o=l!=null?(0,m.mul)(l,e.gasUsed):"0";let h="0";if(u&&this.ethEngine.networkInfo.l1RollupParams!=null){const v=yield this.multicastServers("eth_getTransactionReceipt",[i]),E=nt(v.result.result);h=(0,m.add)(h,(0,p.X0)(E.l1Fee))}let a,d,f;u?c?(a=(0,m.sub)("0",e.value),d="0",f=(0,m.add)(o,h)):e.from.toLowerCase()===e.to.toLowerCase()?(a=(0,m.sub)((0,m.sub)("0",o),h),d=(0,m.add)(o,h)):(a=(0,m.sub)((0,m.sub)((0,m.sub)("0",e.value),o),h),d=(0,m.add)(o,h)):(a=e.value,d="0",r.push(this.ethEngine.walletLocalData.publicKey));const y={from:[e.from],to:[e.to],gas:e.gas,gasPrice:l!=null?l:"",gasUsed:e.gasUsed,isFromMakeSpend:!1};let k=parseInt(e.blockNumber);return k<0&&(k=0),{blockHeight:k,currencyCode:t,date:parseInt(e.timeStamp),feeRateUsed:l!=null?Te(l,e.gas,e.gasUsed):void 0,isSend:a.startsWith("-"),memos:[],nativeAmount:a,networkFee:d,otherParams:y,ourReceiveAddresses:r,parentNetworkFee:f,signedTx:"",txid:i,walletId:this.walletId}})}processAlethioTransaction(e,t){let s;const r=[];let i;const u=t!==this.ethEngine.currencyInfo.currencyCode,c=e.attributes.value,l=e.attributes.fee?e.attributes.fee:"0",o=e.relationships.from.data.id,h=e.relationships.to.data.id;t===this.ethEngine.currencyInfo.currencyCode?i=l:i="0";const a=o.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase();if(a)o.toLowerCase()===h.toLowerCase()?s=(0,m.mul)(i,"-1"):(s=(0,m.sub)("0",c),u||(s=(0,m.sub)(s,i)));else if(h.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase())s=c,r.push(this.ethEngine.walletLocalData.publicKey.toLowerCase());else return null;const d={from:[o],to:[h],gas:"0",gasPrice:"0",gasUsed:"0",isFromMakeSpend:!1};let f=e.attributes.globalRank[0];f<0&&(f=0);let y,k="0";return u&&a?y=i:k=i,{blockHeight:f,currencyCode:t,date:e.attributes.blockCreationTime,isSend:s.startsWith("-"),memos:[],nativeAmount:s,networkFee:k,otherParams:d,ourReceiveAddresses:r,parentNetworkFee:y,signedTx:"",txid:e.relationships.transaction.data.id,walletId:this.walletId}}fetchGetEtherscan(e,t){return w(this,null,function*(){const s=Ne(this.ethEngine.initOptions,this.ethEngine.currencyInfo,this.ethEngine.log);e.indexOf("cors-http")===0&&(e=e.replace(/^cors-http/,"http"));const i=Array.isArray(s)?(0,p.sD)(s,1)[0]:s!=null?s:"",u=i!==""?`&apikey=${i}`:"",c=`${e}/api${t}`,l=yield this.ethEngine.fetchCors(`${c}${u}`);return l.ok||this.throwError(l,"fetchGetEtherscan",c),yield l.json()})}fetchGetBlockbook(e,t){return w(this,null,function*(){const s=e+t;return yield(e.includes("trezor")?yield this.ethEngine.fetchCors(s,{headers:{"User-Agent":"http.agent"}}):yield this.ethEngine.fetchCors(s)).json()})}fetchPostRPC(e,t,s,r){return w(this,null,function*(){const i={id:s,jsonrpc:"2.0",method:e,params:t},c=/{{(.*?)}}/g.exec(r);if(c!=null){const h=c[1],a=F(h),d=this.ethEngine.initOptions[a];if(typeof d=="string")r=r.replace(c[0],d);else throw d==null?new Error(`Missing ${a} in 'initOptions' for ${this.ethEngine.currencyInfo.pluginId}`):new Error("Incorrect apikey type for RPC")}const l=yield this.ethEngine.fetchCors(r,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(i)}),o=U()(r,{},!0);return l.ok||this.throwError(l,"fetchPostRPC",o.hostname),yield l.json()})}fetchPostBlockcypher(e,t,s){return w(this,null,function*(){const{blockcypherApiKey:r}=this.ethEngine.initOptions;let i="";r&&r.length>5&&(i="&token="+r);const u=`${s}/${e}${i}`,c=yield this.ethEngine.fetchCors(u,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(t)}),l=U()(u,{},!0);return c.ok||this.throwError(c,"fetchPostBlockcypher",l.hostname),yield c.json()})}fetchGetBlockchair(e,t=!1){return w(this,null,function*(){const{blockchairApiKey:s}=this.ethEngine.initOptions,{blockchairApiServers:r}=this.ethEngine.networkInfo,i=t&&s?`&key=${s}`:"",u=`${r[0]}${e}`,c=yield this.ethEngine.fetchCors(`${u}${i}`);return c.ok||this.throwError(c,"fetchGetBlockchair",u),yield c.json()})}fetchPostAmberdataRpc(e){return w(this,arguments,function*(t,s=[]){const{amberdataApiKey:r=""}=this.ethEngine.initOptions,{amberdataRpcServers:i}=this.ethEngine.networkInfo,u=`${i[0]}`,c={jsonrpc:"2.0",method:t,params:s,id:1},l=yield this.ethEngine.fetchCors(u,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":r,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(c)}),o=U()(u,{},!0);return l.ok||this.throwError(l,"fetchPostAmberdataRpc",o),yield l.json()})}fetchGetAmberdataApi(e){return w(this,null,function*(){const{amberdataApiKey:t=""}=this.ethEngine.initOptions,{amberdataApiServers:s}=this.ethEngine.networkInfo,r=`${s[0]}${e}`,i=yield this.ethEngine.fetchCors(r,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":t}});return i.ok||this.throwError(i,"fetchGetAmberdata",r),yield i.json()})}fetchGetAlethio(e,t=!0,s){return w(this,null,function*(){const{alethioApiKey:r=""}=this.ethEngine.initOptions,{alethioApiServers:i}=this.ethEngine.networkInfo,u=t?`${i[0]}${e}`:e,c=yield this.ethEngine.fetchCors(u,r?{headers:{Authorization:`Bearer ${r}`}}:void 0);return c.ok||this.throwError(c,"fetchGetAlethio",u),yield c.json()})}broadcastEtherscan(e,t){return w(this,null,function*(){const s=`?module=proxy&action=eth_sendRawTransaction&hex=${e.signedTx}`,r=yield this.fetchGetEtherscan(t,s);return this.broadcastResponseHandler(r,t,e)})}broadcastRPC(e,t,s){return w(this,null,function*(){const r="eth_sendRawTransaction",i=[e.signedTx],u=yield this.fetchPostRPC(r,i,t,s),c=U()(s,{},!0);return this.broadcastResponseHandler(u,c,e)})}broadcastBlockCypher(e,t){return w(this,null,function*(){const s=`v1/${this.ethEngine.currencyInfo.currencyCode.toLowerCase()}/main/txs/push`,r=e.signedTx.replace("0x",""),i=yield this.fetchPostBlockcypher(s,{tx:r},t);return this.broadcastResponseHandler(i,t,e)})}broadcastBlockbook(e,t){return w(this,null,function*(){const s=yield this.fetchGetBlockbook(t,`/api/v2/sendtx/${e.signedTx}`);return this.broadcastResponseHandler(s,t,e)})}broadcastResponseHandler(e,t,s){if(typeof e.error<"u")throw this.ethEngine.error(`FAILURE ${t}
2
2
  ${JSON.stringify(e.error)}
3
3
  ${(0,p.oX)(s)}`),e.error;if(typeof e.result=="string")return this.ethEngine.warn(`SUCCESS ${t}
4
4
  ${(0,p.oX)(s)}`),e;throw this.ethEngine.error(`FAILURE ${t}
5
5
  Invalid return value ${JSON.stringify(e)}
6
- ${(0,p.oX)(s)}`),new Error("Invalid return value on transaction send")}multicastServers(e,...t){return w(this,null,function*(){const{rpcServers:s,blockcypherApiServers:r,evmScanApiServers:i,blockbookServers:h,chainParams:{chainId:c}}=this.ethEngine.networkInfo;let l={result:"",server:"no server"},o,d;switch(e){case"broadcastTx":{const a=[];s.forEach(u=>{const f=U()(u,{},!0);a.push(we(this.broadcastRPC(t[0],c,u),f.hostname))}),i.forEach(u=>{a.push(we(this.broadcastEtherscan(t[0],u),"etherscan"))}),h.forEach(u=>{a.push(we(this.broadcastBlockbook(t[0],u),"blockbook"))}),r.forEach(u=>{a.push(we(this.broadcastBlockCypher(t[0],u),"blockcypher"))}),l=yield(0,p.Wp)(a),this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} multicastServers ${e} ${l.server} won`);break}case"eth_blockNumber":o=i.map(a=>()=>w(this,null,function*(){if(!a.includes("etherscan")&&!a.includes("blockscout"))throw new Error(`Unsupported command eth_blockNumber in ${a}`);let u="?module=proxy&action=eth_blockNumber";a.includes("blockscout")&&(u="?module=block&action=eth_block_number");const f=yield this.fetchGetEtherscan(a,u);if(typeof f.result!="string"){const y=`Invalid return value eth_blockNumber in ${a}`;throw this.ethEngine.error(y),new Error(y)}return{server:a,result:f}})),o.push(...s.map(a=>()=>w(this,null,function*(){const u=yield this.fetchPostRPC("eth_blockNumber",[],c,a);if(u.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${a} included an error ${JSON.stringify(u.error)}`),new Error("Successful eth_blockNumber response object included an error");return{server:U()(a).hostname,result:u}}))),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_estimateGas":o=s.map(a=>()=>w(this,null,function*(){const u=yield this.fetchPostRPC("eth_estimateGas",t[0],c,a);if(u.error!=null)throw this.ethEngine.error(`Successful eth_estimateGas response object from ${a} included an error ${JSON.stringify(u.error)}`),new Error("Successful eth_estimateGas response object included an error");return{server:U()(a).hostname,result:u}})),l=yield(0,p.QJ)(o);break;case"eth_getTransactionReceipt":case"eth_getCode":o=s.map(a=>()=>w(this,null,function*(){const u=yield this.fetchPostRPC(e,t[0],c,a);if(u.error!=null)throw this.ethEngine.error(`Successful ${e} response object from ${a} included an error ${u.error}`),new Error(`Successful ${e} response object included an error`);return{server:U()(a).hostname,result:u}})),l=yield(0,p.QJ)(o);break;case"eth_getTransactionCount":d=`?module=proxy&action=eth_getTransactionCount&address=${t[0]}&tag=latest`,o=i.map(a=>()=>w(this,null,function*(){if(!a.includes("etherscan")&&!a.includes("blockscout"))throw new Error(`Unsupported command eth_getTransactionCount in ${a}`);const u=yield this.fetchGetEtherscan(a,d);if(typeof u.result!="string"){const f=`Invalid return value eth_getTransactionCount in ${a}`;throw this.ethEngine.error(f),new Error(f)}return{server:a,result:u}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_getTransactionCount_RPC":o=s.map(a=>()=>w(this,null,function*(){const u=yield this.fetchPostRPC("eth_getTransactionCount",[t[0],"latest"],c,a);if(u.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${a} included an error ${JSON.stringify(u.error)}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:U()(a).hostname,result:u}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_getBalance":d=`?module=account&action=balance&address=${t[0]}&tag=latest`,o=i.map(a=>()=>w(this,null,function*(){const u=yield this.fetchGetEtherscan(a,d);if(!u.result||typeof u.result!="string"){const f=`Invalid return value eth_getBalance in ${a}`;throw this.ethEngine.error(f),new Error(f)}return{server:a,result:u}})),o.push(...s.map(a=>()=>w(this,null,function*(){const u=yield this.fetchPostRPC("eth_getBalance",[t[0],"latest"],c,a);if(u.error!=null)throw this.ethEngine.error(`Successful eth_getBalance response object from ${a} included an error ${JSON.stringify(u.error)}`),new Error("Successful eth_getBalance response object included an error");if(!(0,p.vq)(u.result))throw new Error(`eth_getBalance not hex for ${U()(a).hostname}`);return u.result=(0,p.Z8)(u.result),{server:U()(a).hostname,result:u}}))),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"getTokenBalance":d=`?module=account&action=tokenbalance&contractaddress=${t[1]}&address=${t[0]}&tag=latest`,o=i.map(a=>()=>w(this,null,function*(){const u=yield this.fetchGetEtherscan(a,d);if(!u.result||typeof u.result!="string"){const f=`Invalid return value getTokenBalance in ${a}`;throw this.ethEngine.error(f),new Error(f)}return{server:a,result:u}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"getTransactions":{const{currencyCode:a,address:u,startBlock:f,page:y,offset:k,contractAddress:C,searchRegularTxs:v}=t[0];let E;a===this.ethEngine.currencyInfo.currencyCode?E=`?action=${v?"txlist":"txlistinternal"}&module=account`:E=`?action=tokentx&contractaddress=${C}&module=account`,d=`${E}&address=${u}&startblock=${f}&endblock=999999999&sort=asc&page=${y}&offset=${k}`,o=i.map(b=>()=>w(this,null,function*(){const L=yield this.fetchGetEtherscan(b,d);if(typeof L.result!="object"||typeof L.result.length!="number"){const D=`Invalid return value getTransactions in ${b}`;throw L.result!=="Max rate limit reached"&&this.ethEngine.error(D),new Error(D)}return{server:b,result:L}})),o=(0,p.Sy)(o),o.length>0?l=yield(0,p.QJ)(o):l=_e(De({},l),{result:{result:[]}});break}case"blockbookBlockHeight":o=h.map(a=>()=>w(this,null,function*(){const u=yield this.fetchGetBlockbook(a,t[0]);return{server:a,result:u}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"blockbookAddress":o=h.map(a=>()=>w(this,null,function*(){const u=yield this.fetchGetBlockbook(a,t[0]);return{server:a,result:u}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_call":o=s.map(a=>()=>w(this,null,function*(){const u=yield this.fetchPostRPC("eth_call",[t[0],"latest"],c,a);if(u.error!=null)throw this.ethEngine.error(`Successful eth_call response object from ${a} included an error ${JSON.stringify(u.error)}`),new Error("Successful eth_call response object included an error");return{server:U()(a).hostname,result:u}})),l=yield(0,p.QJ)(o);break}return l})}getBaseFeePerGas(){return w(this,null,function*(){const{rpcServers:e,chainParams:{chainId:t}}=this.ethEngine.networkInfo,s=e.map(r=>()=>w(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],t,r).then(i=>{if(i.error!=null){const c=`multicast get_baseFeePerGas error response from ${r}: ${JSON.stringify(i.error)}`;throw this.ethEngine.warn(c),new Error(c)}return{baseFeePerGas:i.result.baseFeePerGas}})}));return yield(0,p.QJ)(s)})}checkBlockHeightEthscan(){return w(this,null,function*(){const{result:e,server:t}=yield this.multicastServers("eth_blockNumber");return{blockHeight:pt(e).result,server:t}})}checkBlockHeightBlockbook(){return w(this,null,function*(){try{const{result:e,server:t}=yield this.multicastServers("blockbookBlockHeight","/api/v2");return{blockHeight:de(e).blockbook.bestHeight,server:t}}catch(e){throw this.ethEngine.log("checkBlockHeightBlockbook blockHeight ",e),new Error("checkBlockHeightBlockbook returned invalid JSON")}})}checkBlockHeightBlockchair(){return w(this,null,function*(){try{const e=yield this.fetchGetBlockchair(`/${this.ethEngine.currencyInfo.pluginId}/stats`,!1);return{blockHeight:parseInt(tt(e).data.blocks,10),server:"blockchair"}}catch(e){throw this.logError(e),new Error("checkBlockHeightBlockchair returned invalid JSON")}})}checkBlockHeightAmberdata(){return w(this,null,function*(){try{const e=yield this.fetchPostAmberdataRpc("eth_blockNumber",[]);return{blockHeight:parseInt(Y(e).result,16),server:"amberdata"}}catch(e){throw this.logError("checkBlockHeightAmberdata",e),new Error("checkTxsAmberdata (regular tx) response is invalid")}})}checkNonceRpc(){return w(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount_RPC",e),r=Y(t);if(/0[xX][0-9a-fA-F]+/.test(r.result))return{newNonce:(0,g.add)("0",r.result),server:s};throw new Error("checkNonceRpc returned invalid JSON")})}checkNonceEthscan(){return w(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount",e);return{newNonce:yt(t).result,server:s}})}checkNonceAmberdata(){return w(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey;try{const t=yield this.fetchPostAmberdataRpc("eth_getTransactionCount",[e,"latest"]);return{newNonce:`${parseInt(Y(t).result,16)}`,server:"amberdata"}}catch(t){throw this.logError("checkNonceAmberdata",t),new Error("Amberdata returned invalid JSON")}})}check(e,...t){return w(this,null,function*(){return yield(0,p.QJ)(this.queryFuncs[e].map(s=>()=>w(this,null,function*(){return yield s(...t)}))).catch(s=>({}))})}getAllTxsEthscan(e,t,s,r){return w(this,null,function*(){const i=this.ethEngine.walletLocalData.publicKey;let h=1;const c=[];let l="";const o=r.contractAddress,d=r.searchRegularTxs;for(;;){const a=Rt,u=yield this.multicastServers("getTransactions",{currencyCode:t,address:i,startBlock:e,page:h,offset:a,contractAddress:o,searchRegularTxs:d});l=u.server;const f=u.result.result;for(let y=0;y<f.length;y++)try{const k=s(f[y]),C=yield this.processEvmScanTransaction(k,t);c.push(C)}catch(k){throw this.ethEngine.error(`getAllTxsEthscan ${s.name}
6
+ ${(0,p.oX)(s)}`),new Error("Invalid return value on transaction send")}multicastServers(e,...t){return w(this,null,function*(){const{rpcServers:s,blockcypherApiServers:r,evmScanApiServers:i,blockbookServers:u,chainParams:{chainId:c}}=this.ethEngine.networkInfo;let l={result:"",server:"no server"},o,h;switch(e){case"broadcastTx":{const a=[];s.forEach(d=>{const f=U()(d,{},!0);a.push(we(this.broadcastRPC(t[0],c,d),f.hostname))}),i.forEach(d=>{a.push(we(this.broadcastEtherscan(t[0],d),"etherscan"))}),u.forEach(d=>{a.push(we(this.broadcastBlockbook(t[0],d),"blockbook"))}),r.forEach(d=>{a.push(we(this.broadcastBlockCypher(t[0],d),"blockcypher"))}),l=yield(0,p.Wp)(a),this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} multicastServers ${e} ${l.server} won`);break}case"eth_blockNumber":o=i.map(a=>()=>w(this,null,function*(){if(!a.includes("etherscan")&&!a.includes("blockscout"))throw new Error(`Unsupported command eth_blockNumber in ${a}`);let d="?module=proxy&action=eth_blockNumber";a.includes("blockscout")&&(d="?module=block&action=eth_block_number");const f=yield this.fetchGetEtherscan(a,d);if(typeof f.result!="string"){const y=`Invalid return value eth_blockNumber in ${a}`;throw this.ethEngine.error(y),new Error(y)}return{server:a,result:f}})),o.push(...s.map(a=>()=>w(this,null,function*(){const d=yield this.fetchPostRPC("eth_blockNumber",[],c,a);if(d.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${a} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_blockNumber response object included an error");return{server:U()(a).hostname,result:d}}))),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_estimateGas":o=s.map(a=>()=>w(this,null,function*(){const d=yield this.fetchPostRPC("eth_estimateGas",t[0],c,a);if(d.error!=null)throw this.ethEngine.error(`Successful eth_estimateGas response object from ${a} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_estimateGas response object included an error");return{server:U()(a).hostname,result:d}})),l=yield(0,p.QJ)(o);break;case"eth_getTransactionReceipt":case"eth_getCode":o=s.map(a=>()=>w(this,null,function*(){const d=yield this.fetchPostRPC(e,t[0],c,a);if(d.error!=null)throw this.ethEngine.error(`Successful ${e} response object from ${a} included an error ${d.error}`),new Error(`Successful ${e} response object included an error`);return{server:U()(a).hostname,result:d}})),l=yield(0,p.QJ)(o);break;case"eth_getTransactionCount":h=`?module=proxy&action=eth_getTransactionCount&address=${t[0]}&tag=latest`,o=i.map(a=>()=>w(this,null,function*(){if(!a.includes("etherscan")&&!a.includes("blockscout"))throw new Error(`Unsupported command eth_getTransactionCount in ${a}`);const d=yield this.fetchGetEtherscan(a,h);if(typeof d.result!="string"){const f=`Invalid return value eth_getTransactionCount in ${a}`;throw this.ethEngine.error(f),new Error(f)}return{server:a,result:d}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_getTransactionCount_RPC":o=s.map(a=>()=>w(this,null,function*(){const d=yield this.fetchPostRPC("eth_getTransactionCount",[t[0],"latest"],c,a);if(d.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${a} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:U()(a).hostname,result:d}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_getBalance":h=`?module=account&action=balance&address=${t[0]}&tag=latest`,o=i.map(a=>()=>w(this,null,function*(){const d=yield this.fetchGetEtherscan(a,h);if(!d.result||typeof d.result!="string"){const f=`Invalid return value eth_getBalance in ${a}`;throw this.ethEngine.error(f),new Error(f)}return{server:a,result:d}})),o.push(...s.map(a=>()=>w(this,null,function*(){const d=yield this.fetchPostRPC("eth_getBalance",[t[0],"latest"],c,a);if(d.error!=null)throw this.ethEngine.error(`Successful eth_getBalance response object from ${a} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_getBalance response object included an error");if(!(0,p.vq)(d.result))throw new Error(`eth_getBalance not hex for ${U()(a).hostname}`);return d.result=(0,p.Z8)(d.result),{server:U()(a).hostname,result:d}}))),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"getTokenBalance":h=`?module=account&action=tokenbalance&contractaddress=${t[1]}&address=${t[0]}&tag=latest`,o=i.map(a=>()=>w(this,null,function*(){const d=yield this.fetchGetEtherscan(a,h);if(!d.result||typeof d.result!="string"){const f=`Invalid return value getTokenBalance in ${a}`;throw this.ethEngine.error(f),new Error(f)}return{server:a,result:d}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"getTransactions":{const{currencyCode:a,address:d,startBlock:f,page:y,offset:k,contractAddress:C,searchRegularTxs:v}=t[0];let E;a===this.ethEngine.currencyInfo.currencyCode?E=`?action=${v?"txlist":"txlistinternal"}&module=account`:E=`?action=tokentx&contractaddress=${C}&module=account`,h=`${E}&address=${d}&startblock=${f}&endblock=999999999&sort=asc&page=${y}&offset=${k}`,o=i.map(b=>()=>w(this,null,function*(){const L=yield this.fetchGetEtherscan(b,h);if(typeof L.result!="object"||typeof L.result.length!="number"){const D=`Invalid return value getTransactions in ${b}`;throw L.result!=="Max rate limit reached"&&this.ethEngine.error(D),new Error(D)}return{server:b,result:L}})),o=(0,p.Sy)(o),o.length>0?l=yield(0,p.QJ)(o):l=_e(De({},l),{result:{result:[]}});break}case"blockbookBlockHeight":o=u.map(a=>()=>w(this,null,function*(){const d=yield this.fetchGetBlockbook(a,t[0]);return{server:a,result:d}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"blockbookAddress":o=u.map(a=>()=>w(this,null,function*(){const d=yield this.fetchGetBlockbook(a,t[0]);return{server:a,result:d}})),o=(0,p.Sy)(o),l=yield(0,p.QJ)(o);break;case"eth_call":o=s.map(a=>()=>w(this,null,function*(){const d=yield this.fetchPostRPC("eth_call",[t[0],"latest"],c,a);if(d.error!=null)throw this.ethEngine.error(`Successful eth_call response object from ${a} included an error ${JSON.stringify(d.error)}`),new Error("Successful eth_call response object included an error");return{server:U()(a).hostname,result:d}})),l=yield(0,p.QJ)(o);break}return l})}getBaseFeePerGas(){return w(this,null,function*(){const{rpcServers:e,chainParams:{chainId:t}}=this.ethEngine.networkInfo,s=e.map(r=>()=>w(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],t,r).then(i=>{if(i.error!=null){const c=`multicast get_baseFeePerGas error response from ${r}: ${JSON.stringify(i.error)}`;throw this.ethEngine.warn(c),new Error(c)}return{baseFeePerGas:i.result.baseFeePerGas}})}));return yield(0,p.QJ)(s)})}checkBlockHeightEthscan(){return w(this,null,function*(){const{result:e,server:t}=yield this.multicastServers("eth_blockNumber");return{blockHeight:pt(e).result,server:t}})}checkBlockHeightBlockbook(){return w(this,null,function*(){try{const{result:e,server:t}=yield this.multicastServers("blockbookBlockHeight","/api/v2");return{blockHeight:de(e).blockbook.bestHeight,server:t}}catch(e){throw this.ethEngine.log("checkBlockHeightBlockbook blockHeight ",e),new Error("checkBlockHeightBlockbook returned invalid JSON")}})}checkBlockHeightBlockchair(){return w(this,null,function*(){try{const e=yield this.fetchGetBlockchair(`/${this.ethEngine.currencyInfo.pluginId}/stats`,!1);return{blockHeight:parseInt(tt(e).data.blocks,10),server:"blockchair"}}catch(e){throw this.logError(e),new Error("checkBlockHeightBlockchair returned invalid JSON")}})}checkBlockHeightAmberdata(){return w(this,null,function*(){try{const e=yield this.fetchPostAmberdataRpc("eth_blockNumber",[]);return{blockHeight:parseInt(Y(e).result,16),server:"amberdata"}}catch(e){throw this.logError("checkBlockHeightAmberdata",e),new Error("checkTxsAmberdata (regular tx) response is invalid")}})}checkNonceRpc(){return w(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount_RPC",e),r=Y(t);if(/0[xX][0-9a-fA-F]+/.test(r.result))return{newNonce:(0,m.add)("0",r.result),server:s};throw new Error("checkNonceRpc returned invalid JSON")})}checkNonceEthscan(){return w(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount",e);return{newNonce:yt(t).result,server:s}})}checkNonceAmberdata(){return w(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey;try{const t=yield this.fetchPostAmberdataRpc("eth_getTransactionCount",[e,"latest"]);return{newNonce:`${parseInt(Y(t).result,16)}`,server:"amberdata"}}catch(t){throw this.logError("checkNonceAmberdata",t),new Error("Amberdata returned invalid JSON")}})}check(e,...t){return w(this,null,function*(){return yield(0,p.QJ)(this.queryFuncs[e].map(s=>()=>w(this,null,function*(){return yield s(...t)}))).catch(s=>({}))})}getAllTxsEthscan(e,t,s,r){return w(this,null,function*(){const i=this.ethEngine.walletLocalData.publicKey;let u=1;const c=[];let l="";const o=r.contractAddress,h=r.searchRegularTxs;for(;;){const a=Rt,d=yield this.multicastServers("getTransactions",{currencyCode:t,address:i,startBlock:e,page:u,offset:a,contractAddress:o,searchRegularTxs:h});l=d.server;const f=d.result.result;for(let y=0;y<f.length;y++)try{const k=s(f[y]),C=yield this.processEvmScanTransaction(k,t);c.push(C)}catch(k){throw this.ethEngine.error(`getAllTxsEthscan ${s.name}
7
7
  ${(0,p.HY)(k)}
8
- ${JSON.stringify(f[y])}`),new Error(`getAllTxsEthscan ${s.name} is invalid`)}if(f.length===0)break;h++}return{allTransactions:c,server:l}})}checkTxsEthscan(e){return w(this,null,function*(){const{startBlock:t,currencyCode:s}=e;let r,i;if(s===this.ethEngine.currencyInfo.currencyCode){const c=yield this.getAllTxsEthscan(t,s,W,{searchRegularTxs:!0}),l=yield this.getAllTxsEthscan(t,s,ge,{searchRegularTxs:!1});r=c.server||l.server,i=[...c.allTransactions,...l.allTransactions]}else{const c=this.ethEngine.getTokenInfo(s);if(c!=null&&typeof c.contractAddress=="string"){const l=c.contractAddress,o=yield this.getAllTxsEthscan(t,s,Ie,{contractAddress:l});r=o.server,i=o.allTransactions}else return{}}const h={blockHeight:t,edgeTransactions:i};return{tokenTxs:{[s]:h},server:r}})}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 r=this.ethEngine.getTokenInfo(s);if(r!=null){const i=r.contractAddress;if(e&&typeof i=="string"&&i.toLowerCase()===e.toLowerCase())return s}}}checkAddressBlockbook(e){return w(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey.toLowerCase(),s={newNonce:"0",tokenBal:{},server:""},r="/api/v2/address/"+t+"?&details=tokenBalances",{result:i,server:h}=yield this.multicastServers("blockbookAddress",r);let c;try{c=Ye(i)}catch{throw this.ethEngine.error(`checkTxsBlockbook ${h} error BlockbookAddress ${JSON.stringify(i)}`),new Error(`checkTxsBlockbook ${h} returned invalid JSON for BlockbookAddress`)}const{nonce:l,tokens:o,balance:d}=c;s.newNonce=l,s.tokenBal!=null&&(s.tokenBal[this.ethEngine.currencyInfo.currencyCode]=d),s.server=h;for(const a of o)try{const{symbol:u,balance:f}=Le(a);s.tokenBal[u]=f}catch{throw this.ethEngine.error(`checkTxsBlockbook ${h} BlockbookTokenBalance ${JSON.stringify(a)}`),new Error(`checkTxsBlockbook ${h} returned invalid JSON for BlockbookTokenBalance`)}return s})}checkTokenBalEthscan(e){return w(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey;let s,r,i,h;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",t),r=s.result,i=s.server;else{const c=this.ethEngine.getTokenInfo(e);if(c!=null&&typeof c.contractAddress=="string"){const l=c.contractAddress,o=yield this.multicastServers("getTokenBalance",t,l);r=o.result,i=o.server}}h=Y(r)}catch(c){throw this.ethEngine.error(`checkTokenBalEthscan token ${e} response ${s||""} `,c),new Error(`checkTokenBalEthscan invalid ${e} response ${JSON.stringify(r)}`)}if(/^\d+$/.test(h.result)){const c=h.result;return{tokenBal:{[e]:c},server:i}}else throw new Error(`checkTokenBalEthscan returned invalid JSON for ${e}`)})}checkTokenBalBlockchair(){return w(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=et(i)}catch(i){throw this.logError("checkTokenBalBlockchair",i),new Error("checkTokenBalBlockchair response is invalid")}const r={[this.ethEngine.currencyInfo.currencyCode]:e.data[t].address.balance};for(const i of e.data[t].layer_2.erc_20)try{const h=qe(i),c=h.balance,l=h.token_address,o=h.token_symbol,d=this.ethEngine.getTokenInfo(o);d!=null&&d.contractAddress===l&&(r[o]=c)}catch(h){throw this.ethEngine.error(`checkTokenBalBlockchair tokenData ${(0,p.HY)(h)}
9
- ${JSON.stringify(i)}`),new Error("checkTokenBalBlockchair tokenData is invalid")}return{tokenBal:r,server:"blockchair"}})}checkTokenBalRpc(e){return w(this,null,function*(){let t,s,r,i;const h=this.ethEngine.walletLocalData.publicKey;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",h),r=s.result,i=s.server;else{const c=this.ethEngine.getTokenInfo(e);if(c!=null&&typeof c.contractAddress=="string"){const l={data:`0x70a08231${(0,p.gc)((0,p.KT)(h),32)}`,to:c.contractAddress},o=yield this.multicastServers("eth_call",l),d=o.result.result;if(!d.startsWith("0x"))throw new Error("Invalid return value. Result not hex");o.result.result=(0,p.Z8)(d),r=o.result,i=o.server}}t=Y(r)}catch(c){throw this.ethEngine.error(`checkTokenBalRpc token ${e} response ${s||""} `,c),new Error(`checkTokenBalRpc invalid ${e} response ${JSON.stringify(r)}`)}return{tokenBal:{[e]:t.result},server:i}})}checkAndUpdate(e=0,t,s,r){return w(this,null,function*(){const i=Date.now();if(i-e>t)try{const h=yield r();this.processEthereumNetworkUpdate(i,h,s)}catch(h){this.ethEngine.error("checkAndUpdate ",h)}})}getQueryHeightWithLookback(e){return e>Xe?e-Xe:0}getQueryDateWithLookback(e){return e>Ke?e-Ke:0}needsLoop(){return w(this,null,function*(){for(;this.ethEngine.engineOn;){const e=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,xt,e,()=>w(this,null,function*(){return yield this.check("blockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Bt,e,()=>w(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 r of s)yield this.checkAndUpdate(this.ethNeeds.tokenBalLastChecked[r],Nt,e,()=>w(this,null,function*(){return yield this.check("tokenBal",r)})),yield this.checkAndUpdate(this.ethNeeds.tokenTxsLastChecked[r],$t,e,()=>w(this,null,function*(){return yield this.check("txs",{startBlock:this.getQueryHeightWithLookback(this.ethEngine.walletLocalData.lastTransactionQueryHeight[r]),startDate:this.getQueryDateWithLookback(this.ethEngine.walletLocalData.lastTransactionDate[r]),currencyCode:r})}));yield(0,p.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 r=t.blockHeight;this.ethEngine.log(`Got block height ${r||"no blockheight"}`),typeof r=="number"&&this.ethEngine.walletLocalData.blockHeight!==r&&(this.ethNeeds.blockHeightLastChecked=e,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=r,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 r=t.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${t.server||"no server"} won`);for(const i of Object.keys(r))this.ethNeeds.tokenBalLastChecked[i]=e,this.ethEngine.updateBalance(i,r[i])}if(t.tokenTxs!=null){const r=t.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${t.server||"no server"} won`);for(const i of Object.keys(r)){this.ethNeeds.tokenTxsLastChecked[i]=e,this.ethEngine.tokenCheckTransactionsStatus[i]=1;const h=r[i];if(h.edgeTransactions){for(const c of h.edgeTransactions)this.ethEngine.addTransaction(i,c);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:r,blockchairApiServers:i,amberdataRpcServers:h,amberdataApiServers:c}=e,l=[],o=[],d=[],a=[];return s.length>0&&(l.push(this.checkBlockHeightEthscan),o.push(this.checkNonceEthscan),a.push(this.checkTokenBalEthscan)),d.push(this.checkTxsEthscan),r.length>0&&(l.push(this.checkBlockHeightBlockbook),a.push(this.checkAddressBlockbook),o.push(this.checkAddressBlockbook)),i.length>0&&(l.push(this.checkBlockHeightBlockchair),a.push(this.checkTokenBalBlockchair)),h.length>0&&(l.push(this.checkBlockHeightAmberdata),o.push(this.checkNonceAmberdata)),c.length>0,t.length>0&&(o.push(this.checkNonceRpc),a.push(this.checkTokenBalRpc)),{blockheight:l,nonce:o,txs:d,tokenBal:a}}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,p.HY)(t).includes("rateLimited")?this.ethEngine.log(e,t):this.ethEngine.error(e,t)}}const _t="low",Xt="standard",Kt="high",He="custom",Ge="1000000000";function je(m,e,t,s){var r,i,h,c,l,o,d,a,u;let f=!0,y,k;const{customNetworkFee:C}=m!=null?m:{};if(m.networkFeeOption===He&&C!=null){const{gasLimit:x,gasPrice:N}=C;if((isNaN(x)||x==="")&&(isNaN(N)||N==="")){const $=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw $.name="ErrorBelowMinimumFee",$}if(N!=null&&N!==""){const $=(c=(i=(r=e.default)==null?void 0:r.gasPrice)==null?void 0:i.minGasPrice)!=null?c:(h=s.defaultNetworkFees.default.gasPrice)==null?void 0:h.minGasPrice;if($!=null){const H=(0,g.mul)(N,Ge);if((0,g.lt)(H,$)||/^\s*$/.test(N)){const ve=new Error(`Gas price ${H} wei below minimum ${$} wei`);throw ve.name="ErrorBelowMinimumFee",ve}}k=(0,g.mul)(N,Ge)}if(x!=null&&x!==""){const $=(a=(o=(l=e.default)==null?void 0:l.gasLimit)==null?void 0:o.minGasLimit)!=null?a:(d=s.defaultNetworkFees.default.gasLimit)==null?void 0:d.minGasLimit;if($!=null&&(0,g.lt)(x,$)||/^\s*$/.test(x)){const H=new Error(`Gas limit ${x} below minimum ${$}`);throw H.name="ErrorBelowMinimumFee",H}y=x,f=!1}}if(y!=null&&k!=null)return{gasLimit:y,gasPrice:k,useEstimatedGasLimit:!1};let v=e.default,E=e.default;if(typeof((u=m.spendTargets[0])==null?void 0:u.publicAddress)=="string"){const x=(0,p.f0)(m.spendTargets[0].publicAddress);typeof e[x]<"u"&&(E=e[x],f=!1,typeof E.gasPrice<"u"&&(v=E))}let b="regularTransaction";m.currencyCode!=null&&m.currencyCode!==t.currencyCode&&(b="tokenTransaction");let L="standard";typeof m.networkFeeOption=="string"&&m.networkFeeOption!==He&&(L=m.networkFeeOption);const D=E.gasLimit!=null?E.gasLimit[b]:"21000";let K="";if(m.spendTargets[0].nativeAmount==null)throw new Error("ErrorInvalidNativeAmount");let M=m.spendTargets[0].nativeAmount;if(b==="tokenTransaction"&&(M=(0,g.div)(M,"10")),v.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const A=v.gasPrice;switch(L){case _t:K=A.lowFee;break;case Xt:{if((0,g.gte)(M,v.gasPrice.standardFeeHighAmount)){K=A.standardFeeHigh;break}if((0,g.lte)(M,A.standardFeeLowAmount)){if(v.gasPrice==null)throw new Error("ErrorInvalidGasPrice");K=v.gasPrice.standardFeeLow;break}const x=(0,g.sub)(A.standardFeeHighAmount,A.standardFeeLowAmount),N=(0,g.sub)(A.standardFeeHigh,A.standardFeeLow),$=(0,g.sub)(M,A.standardFeeLowAmount),H=(0,g.mul)($,N),ve=(0,g.div)(H,x);K=(0,g.add)(A.standardFeeLow,ve);break}case Kt:K=v.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:y!=null?y:D,gasPrice:k!=null?k:K,useEstimatedGasLimit:f}}const Ht="1040",Me=m=>{const{chainParams:e,data:t,dynamicOverhead:s,fixedOverhead:r,gasPriceL1Wei:i,gasLimit:h,nonce:c,to:l,value:o="0x0"}=m,d=Oe().custom(e),f=xe.Transaction.fromTxData({nonce:c!=null?(0,p.X0)(c):void 0,gasPrice:(0,p.X0)(i),gasLimit:(0,p.X0)(h),to:l,value:o,data:t},{common:d}).raw().map(E=>E.toString("hex")).join().match(/(.{1,2})/g);if(f==null)throw new Error("Invalid rawTx string");let y=0;for(let E=0;E<f.length;E++)f[E]==="00"?y+=4:y+=16;const k=(0,g.add)((0,g.add)(y.toString(),r),Ht),C=(0,g.div)(s,"1000000",18);return(0,g.mul)((0,g.mul)(i,k),C)};var V=P(48764).Buffer,Gt=Object.defineProperty,jt=Object.defineProperties,Mt=Object.getOwnPropertyDescriptors,Ue=Object.getOwnPropertySymbols,Ut=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty,Zt=Object.prototype.propertyIsEnumerable,Wt=Reflect.get,Je=(m,e,t)=>e in m?Gt(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,re=(m,e)=>{for(var t in e||(e={}))Jt.call(e,t)&&Je(m,t,e[t]);if(Ue)for(var t of Ue(e))Zt.call(e,t)&&Je(m,t,e[t]);return m},fe=(m,e)=>jt(m,Mt(e)),Ae=(m,e,t)=>Wt(Ut(m),t,e),R=(m,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},h=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,h);c((t=t.apply(m,e)).next())});class me extends lt.P{constructor(e,t,s,r,i,h){super(e,t,s,i),this.updateNetworkFeesFromBaseFeePerGas=()=>R(this,null,function*(){var o;const{supportsEIP1559:d=!1}=this.networkInfo;if(!d)return;const{baseFeePerGas:a}=yield this.ethNetwork.getBaseFeePerGas();if(a==null)return;const u=(0,p.Z8)(a),f=this.networkFees;if(f.default==null||f.default.gasPrice==null)return;const y=this.networkInfo.defaultNetworkFees.default,k=f.default.minPriorityFee||y.minPriorityFee,C=(o=f.default.baseFeeMultiplier)!=null?o:y.baseFeeMultiplier;if(k==null||C==null)return;const v={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const E of Object.keys(C)){const b=(0,g.mul)(C[E],u),L=(0,g.add)(b,k);v[E]=(0,g.div)(L,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),Ee(this.log,v),v}),this.initOptions=r,this.networkInfo=e.networkInfo,this.ethNetwork=new Dt(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},this.networkInfo.l1RollupParams!=null&&(this.l1RollupParams=this.networkInfo.l1RollupParams),this.networkFees=this.networkInfo.defaultNetworkFees,this.fetchCors=(0,p.zR)(e.io);const{infoFeeProvider:c,externalFeeProviders:l}=vt(this.fetchCors,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=c,this.externalFeeProviders=[...l,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:(o,d)=>{if(!(0,p.vq)(o))throw new Error("ErrorInvalidMessage");const a=V.from(d.privateKey,"hex"),u=(0,p.ah)(o),f=S().hashPersonalMessage(u),{v:y,r:k,s:C}=S().ecsign(f,a);return S().toRpcSig(y,k,C)},signTypedData:(o,d)=>{const a=Et(o),u=V.from(d.privateKey,"hex"),{types:f}=a;function y(A,_=[]){if(_.includes(A)||f[A]===void 0)return _;_.push(A);for(const x of f[A])for(const N of y(x.type,_))_.includes(N)||_.push(N);return _}function k(A){let _=y(A);_=_.filter(N=>N!==A),_=[A].concat(_.sort());let x="";for(const N of _)x+=`${N}(${f[N].map(({name:$,type:H})=>`${H} ${$}`).join(",")})`;return x}function C(A){return S().keccak256(k(A))}function v(A,_){const x=[],N=[];x.push("bytes32"),N.push(C(A));for(const $ of f[A]){let H=_[$.name];if($.type==="string"||$.type==="bytes")x.push("bytes32"),H=S().keccak256(H),N.push(H);else if(f[$.type]!==void 0)x.push("bytes32"),H=S().keccak256(v($.type,H)),N.push(H);else{if($.type.lastIndexOf("]")===$.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");x.push($.type),N.push(H)}}return Pe().rawEncode(x,N)}function E(A,_){return S().keccak256(v(A,_))}function b(){return S().keccak256(V.concat([V.from("1901","hex"),E("EIP712Domain",a.domain),E(a.primaryType,a.message)]))}const L=S().ecsign(b(),u),{v:D,r:K,s:M}=L;return S().bufferToHex(V.concat([S().setLengthLeft(K,32),S().setLengthLeft(M,32),S().toBuffer(D)]))},txRpcParamsToSpendInfo:o=>{const d={otherParams:o};o.to!=null&&(d.publicAddress=o.to),o.value!=null?d.nativeAmount=(0,p.Z8)(o.value):d.nativeAmount="0";let a,u,f;return o.gas!=null&&(u=(0,p.Z8)(o.gas),a="custom"),o.gasPrice!=null&&(f=(0,g.div)((0,p.Z8)(o.gasPrice),se.toString(),18),a="custom"),{currencyCode:this.currencyInfo.currencyCode,spendTargets:[d],networkFeeOption:a,customNetworkFee:{gasLimit:u,gasPrice:f},otherParams:o}}},this.otherMethods={parseWalletConnectV2Payload:o=>R(this,null,function*(){var d,a;try{let u="0",f="0";switch(o.method){case"eth_sendTransaction":case"eth_signTransaction":{const y=(0,n.su)({from:n.XC,to:(0,n.Zz)(n.XC),data:n.XC,gas:(0,n.Zz)(n.XC),gasPrice:(0,n.Zz)(n.XC),value:(0,n.Zz)(n.XC)})(o.params[0]),{gas:k,gasPrice:C,value:v}=y,E=b=>{var L,D;k==null?y.gas=(0,p.X0)(b):b=(0,p.Z8)(k);let K=(D=(L=this.networkFees.default.gasPrice)==null?void 0:L.standardFeeHigh)!=null?D:"0";C==null?y.gasPrice=(0,p.X0)(K):K=(0,p.Z8)(C),f=(0,g.mul)(b,K)};v!=null&&(u=(0,p.Z8)(v)),((d=this.networkFees.default.gasLimit)==null?void 0:d.tokenTransaction)==null?this.ethNetwork.multicastServers("eth_estimateGas",y).then(b=>{const L=(0,g.add)(parseInt(b.result.result,16).toString(),"0");E(L)}).catch(b=>{this.warn("Wallet connect call_request failed to get gas limit",b)}):E((a=this.networkFees.default.gasLimit)==null?void 0:a.tokenTransaction);break}}return{nativeAmount:u,networkFee:f}}catch(u){throw this.warn("Wallet connect call_request ",u),u}}),txRpcParamsToSpendInfo:o=>R(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(o)})}}estimateGasLimit(e){return R(this,null,function*(){var t,s;const{contractAddress:r,estimateGasParams:i,miningFees:h,publicAddress:c}=e,l=i[0].data!=null;if(this.lastEstimatedGasLimit.gasLimit!==""&&this.lastEstimatedGasLimit.publicAddress===c&&this.lastEstimatedGasLimit.contractAddress===r)return this.lastEstimatedGasLimit.gasLimit;let o=h.gasLimit;try{const a=(yield this.ethNetwork.multicastServers("eth_getCode",[i[0].to,"latest"])).result.result!=="0x",u=(f=0)=>R(this,null,function*(){const y=this.networkInfo.defaultNetworkFees.default.gasLimit;try{if(y!=null&&!a&&!l)o=y.regularTransaction;else{const k=yield this.ethNetwork.multicastServers("eth_estimateGas",i);o=(0,g.add)(parseInt(k.result.result,16).toString(),"0"),a&&(o=(0,g.mul)(o,"2"))}this.lastEstimatedGasLimit={publicAddress:c,contractAddress:r,gasLimit:o}}catch{if(y==null){if(f>5)throw new Error("Unable to estimate gas limit after 5 tries. Please try again later");return yield u(f+1)}if(l)throw new Error("Unable to estimate gas limit. Please try again later");y.tokenTransaction!=null&&(o=y.tokenTransaction)}});if(yield u(),(0,g.lt)(o,(s=(t=this.networkFees.default.gasLimit)==null?void 0:t.minGasLimit)!=null?s:"21000"))throw o=h.gasLimit,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum")}catch(d){this.error("makeSpend Error determining gas limit ",d)}return o})}setOtherData(e){this.otherData=pe(e)}updateNetworkFees(){return R(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const s={};Object.keys(t).forEach(r=>{const i=r;s[i]=(0,p.Y7)(t[i])}),this.networkFees.default.gasPrice!=null&&(this.networkFees.default.gasPrice=re(re({},this.networkFees.default.gasPrice),s));break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}})}updateL1RollupParams(){return R(this,null,function*(){if(this.l1RollupParams!=null){try{const e={to:this.l1RollupParams.oracleContractAddress,data:this.l1RollupParams.gasPricel1BaseFeeMethod},t=yield this.ethNetwork.multicastServers("eth_call",e),s=Y(t.result);this.l1RollupParams=fe(re({},this.l1RollupParams),{gasPriceL1Wei:(0,g.ceil)((0,g.mul)((0,p.Z8)(s.result),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=Y(t.result);this.l1RollupParams=fe(re({},this.l1RollupParams),{dynamicOverhead:(0,p.Z8)(s.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return R(this,null,function*(){yield Ae(me.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return R(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:ut;this.infoFeeProvider().then(s=>{this.log.warn("infoFeeProvider:",JSON.stringify(s,null,2)),this.networkFees=(0,p.nu)(this.networkFees,s)}).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>R(this,null,function*(){return yield this.addToLoop("updateNetworkFees",t)})),this.addToLoop("updateL1RollupParams",dt).catch(()=>{}),this.ethNetwork.needsLoop(),Ae(me.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return R(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return R(this,null,function*(){const{publicKey:e}=this.walletLocalData;return{publicAddress:/[A-F]/.test(e)?e:S().toChecksumAddress(e.replace("0x",""))}})}getMaxSpendable(e){return R(this,null,function*(){e=(0,Be.s)(e,this.currencyInfo);const{edgeSpendInfo:t,currencyCode:s}=this.makeSpendCheck(e),r=this.getBalance({currencyCode:e.currencyCode}),h=e.spendTargets[0].publicAddress;if(h==null)throw new Error("makeSpend Missing publicAddress");const{contractAddress:c,data:l,value:o}=this.getTxParameterInformation(t,s,this.currencyInfo);if(e.currencyCode===this.currencyInfo.currencyCode){const d=(a,u)=>R(this,null,function*(){const f=(0,g.sub)(u,a);if((0,g.lte)(f,"1"))return a;const y=(0,g.add)(a,(0,g.div)(f,"2"));e.spendTargets[0].nativeAmount=y;const k=je(e,this.networkFees,this.currencyInfo,this.networkInfo);k.useEstimatedGasLimit&&(k.gasLimit=yield this.estimateGasLimit({contractAddress:c,estimateGasParams:[{to:c!=null?c:h,from:this.walletLocalData.publicKey,gas:"0xffffff",value:o,data:l},"latest"],miningFees:k,publicAddress:h}));const C=(0,g.mul)(k.gasPrice,k.gasLimit);let v="0";if(this.l1RollupParams!=null){const b={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:k.gasLimit,to:h,value:(0,p.X0)(y),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};v=Me(b)}const E=(0,g.add)((0,g.add)(y,C),v);return(0,g.gt)(E,r)?yield d(a,y):yield d(y,u)});return yield d("0",(0,g.add)(r,"1"))}else return e.spendTargets[0].nativeAmount=r,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}getTxParameterInformation(e,t,s){var r;const{memos:i=[]}=e,{spendTargets:h}=e,c=h[0],{publicAddress:l,nativeAmount:o}=c;let d=((r=i[0])==null?void 0:r.type)==="hex"?i[0].value:void 0,a;if(t===s.currencyCode)return a=o==null?void 0:(0,p.X0)(o),{data:d,value:a};{let u;if(d!=null)u=l;else{const f=this.getTokenInfo(t);if(f==null||typeof f.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");u=f.contractAddress;const y=Pe().simpleEncode("transfer(address,uint256):(uint256)",l,(0,p.X0)(o!=null?o:"0"));a="0x0",d="0x"+V.from(y).toString("hex")}return{contractAddress:u,data:d,value:a}}}makeSpend(e){return R(this,null,function*(){var t,s;e=(0,Be.s)(e,this.currencyInfo);const{edgeSpendInfo:r,currencyCode:i,skipChecks:h}=this.makeSpendCheck(e),{memos:c=[]}=r,{pendingTxs:l=[]}=r;if(r.spendTargets.length!==1)throw new Error("Error: only one output allowed");const o=r.spendTargets[0],{publicAddress:d}=o;let{nativeAmount:a}=o;if(d==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new ne.$D;if(!S().isValidAddress(d))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let u;const f=je(r,this.networkFees,this.currencyInfo,this.networkInfo);let y;if(l.length>0){const A=this.walletLocalData.otherData,_=this.walletLocalData.numUnconfirmedSpendTxs>0?A.unconfirmedNextNonce:A.nextNonce;y=(0,g.add)(_,l.length.toString())}const{contractAddress:k,data:C,value:v}=this.getTxParameterInformation(r,i,this.currencyInfo);k==null?u={from:[this.walletLocalData.publicKey],to:[d],gas:f.gasLimit,gasPrice:f.gasPrice,gasUsed:"0",nonceUsed:y,data:C,isFromMakeSpend:!0}:u={from:[this.walletLocalData.publicKey],to:[k],gas:f.gasLimit,gasPrice:f.gasPrice,gasUsed:"0",tokenRecipientAddress:d,nonceUsed:y,data:C,isFromMakeSpend:!0},f.useEstimatedGasLimit&&(u.gas=yield this.estimateGasLimit({contractAddress:k,estimateGasParams:[{to:k!=null?k:d,from:this.walletLocalData.publicKey,gas:"0xffffff",value:v,data:C},"latest"],miningFees:f,publicAddress:d}));const E=(t=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?t:"0";let b=(0,g.mul)(f.gasPrice,u.gas),L="0",D=null,K="0";if(this.l1RollupParams!=null){const A={nonce:u.nonceUsed,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:u.gas,to:u.to[0],value:v,data:u.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};K=Me(A)}if(i===this.currencyInfo.currencyCode){if(b=(0,g.add)(b,K),L=(0,g.add)(b,a),!h&&(0,g.gt)(L,E))throw new ne.C_;a=(0,g.mul)(L,"-1")}else{if(D=(0,g.add)(b,K),!h&&(0,g.gt)(b,E))throw new ne.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:b});const A=(s=this.walletLocalData.totalBalances[i])!=null?s:"0";if(!h&&(0,g.gt)(a,A))throw new ne.C_;b="0",a=(0,g.mul)(a,"-1")}const M={blockHeight:0,currencyCode:i,date:0,feeRateUsed:Te(f.gasPrice,u.gas),isSend:a.startsWith("-"),memos:c,nativeAmount:a,networkFee:b,otherParams:u,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return D&&(M.parentNetworkFee=D),M})}signMessage(e,t,s){return R(this,null,function*(){const r=Ce(this.currencyInfo.pluginId)(t);if(st(s.otherParams).typedData){const h=JSON.parse(e);try{return this.utils.signTypedData(h,r)}catch{return(0,ot.signTypedData_v4)(V.from(r.privateKey,"hex"),{data:h})}}return this.utils.signMessage(e,r)})}signTx(e,t){return R(this,null,function*(){const s=Ce(this.currencyInfo.pluginId)(t),r=(0,p.Xp)(e),i=(0,p.NC)(r.gas),h=(0,p.NC)(r.gasPrice);let c;if(e.currencyCode===this.currencyInfo.currencyCode){const E=(0,g.add)(e.nativeAmount,e.networkFee);c=(0,g.mul)("-1",E,16)}else c=(0,g.mul)("-1",e.nativeAmount,16);(0,g.lt)(c,"0")&&(c="0x00");let l=r.nonceUsed;if(!l)if(this.walletLocalData.numUnconfirmedSpendTxs&&(0,g.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)){const E=(0,g.sub)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce);if((0,g.lte)(E,"5"))l=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0;else{const b=new Error("Excessive pending spend transactions");throw b.name="ErrorExcessivePendingSpends",b}}else l=this.otherData.nextNonce;const o=(0,p.NC)(l);let d;if(r.data!=null)d=r.data,e.currencyCode!==this.currencyInfo.currencyCode&&(c="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)d="";else{const E=Pe().simpleEncode("transfer(address,uint256):(uint256)",r.tokenRecipientAddress,c);d="0x"+V.from(E).toString("hex"),c="0x00"}const{chainParams:a}=this.networkInfo,u=Oe().custom(a),f={nonce:o,gasPrice:h,gasLimit:i,to:r.to[0],value:c,data:d},y=V.from(s.privateKey,"hex"),k=ct().fromPrivateKey(y);this.warn(`signTx getAddressString ${k.getAddressString()}`);const v=xe.Transaction.fromTxData(f,{common:u}).sign(y);return e.signedTx=(0,p.$9)(v.serialize()),e.txid=(0,p.$9)(v.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=l),this.warn(`signTx
8
+ ${JSON.stringify(f[y])}`),new Error(`getAllTxsEthscan ${s.name} is invalid`)}if(f.length===0)break;u++}return{allTransactions:c,server:l}})}checkTxsEthscan(e){return w(this,null,function*(){const{startBlock:t,currencyCode:s}=e;let r,i;if(s===this.ethEngine.currencyInfo.currencyCode){const c=yield this.getAllTxsEthscan(t,s,W,{searchRegularTxs:!0}),l=yield this.getAllTxsEthscan(t,s,ge,{searchRegularTxs:!1});r=c.server||l.server,i=[...c.allTransactions,...l.allTransactions]}else{const c=this.ethEngine.getTokenInfo(s);if(c!=null&&typeof c.contractAddress=="string"){const l=c.contractAddress,o=yield this.getAllTxsEthscan(t,s,Ie,{contractAddress:l});r=o.server,i=o.allTransactions}else return{}}const u={blockHeight:t,edgeTransactions:i};return{tokenTxs:{[s]:u},server:r}})}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 r=this.ethEngine.getTokenInfo(s);if(r!=null){const i=r.contractAddress;if(e&&typeof i=="string"&&i.toLowerCase()===e.toLowerCase())return s}}}checkAddressBlockbook(e){return w(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey.toLowerCase(),s={newNonce:"0",tokenBal:{},server:""},r="/api/v2/address/"+t+"?&details=tokenBalances",{result:i,server:u}=yield this.multicastServers("blockbookAddress",r);let c;try{c=Ye(i)}catch{throw this.ethEngine.error(`checkTxsBlockbook ${u} error BlockbookAddress ${JSON.stringify(i)}`),new Error(`checkTxsBlockbook ${u} returned invalid JSON for BlockbookAddress`)}const{nonce:l,tokens:o,balance:h}=c;s.newNonce=l,s.tokenBal!=null&&(s.tokenBal[this.ethEngine.currencyInfo.currencyCode]=h),s.server=u;for(const a of o)try{const{symbol:d,balance:f}=Le(a);s.tokenBal[d]=f}catch{throw this.ethEngine.error(`checkTxsBlockbook ${u} BlockbookTokenBalance ${JSON.stringify(a)}`),new Error(`checkTxsBlockbook ${u} returned invalid JSON for BlockbookTokenBalance`)}return s})}checkTokenBalEthscan(e){return w(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey;let s,r,i,u;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",t),r=s.result,i=s.server;else{const c=this.ethEngine.getTokenInfo(e);if(c!=null&&typeof c.contractAddress=="string"){const l=c.contractAddress,o=yield this.multicastServers("getTokenBalance",t,l);r=o.result,i=o.server}}u=Y(r)}catch(c){throw this.ethEngine.error(`checkTokenBalEthscan token ${e} response ${s||""} `,c),new Error(`checkTokenBalEthscan invalid ${e} response ${JSON.stringify(r)}`)}if(/^\d+$/.test(u.result)){const c=u.result;return{tokenBal:{[e]:c},server:i}}else throw new Error(`checkTokenBalEthscan returned invalid JSON for ${e}`)})}checkTokenBalBlockchair(){return w(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=et(i)}catch(i){throw this.logError("checkTokenBalBlockchair",i),new Error("checkTokenBalBlockchair response is invalid")}const r={[this.ethEngine.currencyInfo.currencyCode]:e.data[t].address.balance};for(const i of e.data[t].layer_2.erc_20)try{const u=qe(i),c=u.balance,l=u.token_address,o=u.token_symbol,h=this.ethEngine.getTokenInfo(o);h!=null&&h.contractAddress===l&&(r[o]=c)}catch(u){throw this.ethEngine.error(`checkTokenBalBlockchair tokenData ${(0,p.HY)(u)}
9
+ ${JSON.stringify(i)}`),new Error("checkTokenBalBlockchair tokenData is invalid")}return{tokenBal:r,server:"blockchair"}})}checkTokenBalRpc(e){return w(this,null,function*(){let t,s,r,i;const u=this.ethEngine.walletLocalData.publicKey;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",u),r=s.result,i=s.server;else{const c=this.ethEngine.getTokenInfo(e);if(c!=null&&typeof c.contractAddress=="string"){const l={data:`0x70a08231${(0,p.gc)((0,p.KT)(u),32)}`,to:c.contractAddress},o=yield this.multicastServers("eth_call",l),h=o.result.result;if(!h.startsWith("0x"))throw new Error("Invalid return value. Result not hex");o.result.result=(0,p.Z8)(h),r=o.result,i=o.server}}t=Y(r)}catch(c){throw this.ethEngine.error(`checkTokenBalRpc token ${e} response ${s||""} `,c),new Error(`checkTokenBalRpc invalid ${e} response ${JSON.stringify(r)}`)}return{tokenBal:{[e]:t.result},server:i}})}checkAndUpdate(e=0,t,s,r){return w(this,null,function*(){const i=Date.now();if(i-e>t)try{const u=yield r();this.processEthereumNetworkUpdate(i,u,s)}catch(u){this.ethEngine.error("checkAndUpdate ",u)}})}getQueryHeightWithLookback(e){return e>Xe?e-Xe:0}getQueryDateWithLookback(e){return e>Ke?e-Ke:0}needsLoop(){return w(this,null,function*(){for(;this.ethEngine.engineOn;){const e=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,xt,e,()=>w(this,null,function*(){return yield this.check("blockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Bt,e,()=>w(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 r of s)yield this.checkAndUpdate(this.ethNeeds.tokenBalLastChecked[r],Nt,e,()=>w(this,null,function*(){return yield this.check("tokenBal",r)})),yield this.checkAndUpdate(this.ethNeeds.tokenTxsLastChecked[r],$t,e,()=>w(this,null,function*(){return yield this.check("txs",{startBlock:this.getQueryHeightWithLookback(this.ethEngine.walletLocalData.lastTransactionQueryHeight[r]),startDate:this.getQueryDateWithLookback(this.ethEngine.walletLocalData.lastTransactionDate[r]),currencyCode:r})}));yield(0,p.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 r=t.blockHeight;this.ethEngine.log(`Got block height ${r||"no blockheight"}`),typeof r=="number"&&this.ethEngine.walletLocalData.blockHeight!==r&&(this.ethNeeds.blockHeightLastChecked=e,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=r,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 r=t.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${t.server||"no server"} won`);for(const i of Object.keys(r))this.ethNeeds.tokenBalLastChecked[i]=e,this.ethEngine.updateBalance(i,r[i])}if(t.tokenTxs!=null){const r=t.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${t.server||"no server"} won`);for(const i of Object.keys(r)){this.ethNeeds.tokenTxsLastChecked[i]=e,this.ethEngine.tokenCheckTransactionsStatus[i]=1;const u=r[i];if(u.edgeTransactions){for(const c of u.edgeTransactions)this.ethEngine.addTransaction(i,c);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:r,blockchairApiServers:i,amberdataRpcServers:u,amberdataApiServers:c}=e,l=[],o=[],h=[],a=[];return s.length>0&&(l.push(this.checkBlockHeightEthscan),o.push(this.checkNonceEthscan),a.push(this.checkTokenBalEthscan)),h.push(this.checkTxsEthscan),r.length>0&&(l.push(this.checkBlockHeightBlockbook),a.push(this.checkAddressBlockbook),o.push(this.checkAddressBlockbook)),i.length>0&&(l.push(this.checkBlockHeightBlockchair),a.push(this.checkTokenBalBlockchair)),u.length>0&&(l.push(this.checkBlockHeightAmberdata),o.push(this.checkNonceAmberdata)),c.length>0,t.length>0&&(o.push(this.checkNonceRpc),a.push(this.checkTokenBalRpc)),{blockheight:l,nonce:o,txs:h,tokenBal:a}}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,p.HY)(t).includes("rateLimited")?this.ethEngine.log(e,t):this.ethEngine.error(e,t)}}const _t="low",Xt="standard",Kt="high",He="custom",Ge="1000000000";function je(g,e,t,s){var r,i,u,c,l,o,h,a,d;let f=!0,y,k;const{customNetworkFee:C}=g!=null?g:{};if(g.networkFeeOption===He&&C!=null){const{gasLimit:x,gasPrice:N}=C;if((isNaN(x)||x==="")&&(isNaN(N)||N==="")){const $=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw $.name="ErrorBelowMinimumFee",$}if(N!=null&&N!==""){const $=(c=(i=(r=e.default)==null?void 0:r.gasPrice)==null?void 0:i.minGasPrice)!=null?c:(u=s.defaultNetworkFees.default.gasPrice)==null?void 0:u.minGasPrice;if($!=null){const H=(0,m.mul)(N,Ge);if((0,m.lt)(H,$)||/^\s*$/.test(N)){const ve=new Error(`Gas price ${H} wei below minimum ${$} wei`);throw ve.name="ErrorBelowMinimumFee",ve}}k=(0,m.mul)(N,Ge)}if(x!=null&&x!==""){const $=(a=(o=(l=e.default)==null?void 0:l.gasLimit)==null?void 0:o.minGasLimit)!=null?a:(h=s.defaultNetworkFees.default.gasLimit)==null?void 0:h.minGasLimit;if($!=null&&(0,m.lt)(x,$)||/^\s*$/.test(x)){const H=new Error(`Gas limit ${x} below minimum ${$}`);throw H.name="ErrorBelowMinimumFee",H}y=x,f=!1}}if(y!=null&&k!=null)return{gasLimit:y,gasPrice:k,useEstimatedGasLimit:!1};let v=e.default,E=e.default;if(typeof((d=g.spendTargets[0])==null?void 0:d.publicAddress)=="string"){const x=(0,p.f0)(g.spendTargets[0].publicAddress);typeof e[x]<"u"&&(E=e[x],f=!1,typeof E.gasPrice<"u"&&(v=E))}let b="regularTransaction";g.currencyCode!=null&&g.currencyCode!==t.currencyCode&&(b="tokenTransaction");let L="standard";typeof g.networkFeeOption=="string"&&g.networkFeeOption!==He&&(L=g.networkFeeOption);const D=E.gasLimit!=null?E.gasLimit[b]:"21000";let K="";if(g.spendTargets[0].nativeAmount==null)throw new Error("ErrorInvalidNativeAmount");let M=g.spendTargets[0].nativeAmount;if(b==="tokenTransaction"&&(M=(0,m.div)(M,"10")),v.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const A=v.gasPrice;switch(L){case _t:K=A.lowFee;break;case Xt:{if((0,m.gte)(M,v.gasPrice.standardFeeHighAmount)){K=A.standardFeeHigh;break}if((0,m.lte)(M,A.standardFeeLowAmount)){if(v.gasPrice==null)throw new Error("ErrorInvalidGasPrice");K=v.gasPrice.standardFeeLow;break}const x=(0,m.sub)(A.standardFeeHighAmount,A.standardFeeLowAmount),N=(0,m.sub)(A.standardFeeHigh,A.standardFeeLow),$=(0,m.sub)(M,A.standardFeeLowAmount),H=(0,m.mul)($,N),ve=(0,m.div)(H,x);K=(0,m.add)(A.standardFeeLow,ve);break}case Kt:K=v.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:y!=null?y:D,gasPrice:k!=null?k:K,useEstimatedGasLimit:f}}const Ht="1040",Me=g=>{const{chainParams:e,data:t,dynamicOverhead:s,fixedOverhead:r,gasPriceL1Wei:i,gasLimit:u,nonce:c,to:l,value:o="0x0"}=g,h=Oe().custom(e),f=xe.Transaction.fromTxData({nonce:c!=null?(0,p.X0)(c):void 0,gasPrice:(0,p.X0)(i),gasLimit:(0,p.X0)(u),to:l,value:o,data:t},{common:h}).raw().map(E=>E.toString("hex")).join().match(/(.{1,2})/g);if(f==null)throw new Error("Invalid rawTx string");let y=0;for(let E=0;E<f.length;E++)f[E]==="00"?y+=4:y+=16;const k=(0,m.add)((0,m.add)(y.toString(),r),Ht),C=(0,m.div)(s,"1000000",18);return(0,m.ceil)((0,m.mul)((0,m.mul)(i,k),C),0)};var V=P(48764).Buffer,Gt=Object.defineProperty,jt=Object.defineProperties,Mt=Object.getOwnPropertyDescriptors,Ue=Object.getOwnPropertySymbols,Ut=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty,Zt=Object.prototype.propertyIsEnumerable,Wt=Reflect.get,Je=(g,e,t)=>e in g?Gt(g,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):g[e]=t,re=(g,e)=>{for(var t in e||(e={}))Jt.call(e,t)&&Je(g,t,e[t]);if(Ue)for(var t of Ue(e))Zt.call(e,t)&&Je(g,t,e[t]);return g},fe=(g,e)=>jt(g,Mt(e)),Ae=(g,e,t)=>Wt(Ut(g),t,e),R=(g,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},u=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,u);c((t=t.apply(g,e)).next())});class me extends lt.P{constructor(e,t,s,r,i,u){super(e,t,s,i),this.updateNetworkFeesFromBaseFeePerGas=()=>R(this,null,function*(){var o;const{supportsEIP1559:h=!1}=this.networkInfo;if(!h)return;const{baseFeePerGas:a}=yield this.ethNetwork.getBaseFeePerGas();if(a==null)return;const d=(0,p.Z8)(a),f=this.networkFees;if(f.default==null||f.default.gasPrice==null)return;const y=this.networkInfo.defaultNetworkFees.default,k=f.default.minPriorityFee||y.minPriorityFee,C=(o=f.default.baseFeeMultiplier)!=null?o:y.baseFeeMultiplier;if(k==null||C==null)return;const v={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const E of Object.keys(C)){const b=(0,m.mul)(C[E],d),L=(0,m.add)(b,k);v[E]=(0,m.div)(L,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),Ee(this.log,v),v}),this.initOptions=r,this.networkInfo=e.networkInfo,this.ethNetwork=new Dt(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},this.networkInfo.l1RollupParams!=null&&(this.l1RollupParams=this.networkInfo.l1RollupParams),this.networkFees=this.networkInfo.defaultNetworkFees,this.fetchCors=(0,p.zR)(e.io);const{infoFeeProvider:c,externalFeeProviders:l}=vt(this.fetchCors,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=c,this.externalFeeProviders=[...l,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:(o,h)=>{if(!(0,p.vq)(o))throw new Error("ErrorInvalidMessage");const a=V.from(h.privateKey,"hex"),d=(0,p.ah)(o),f=S().hashPersonalMessage(d),{v:y,r:k,s:C}=S().ecsign(f,a);return S().toRpcSig(y,k,C)},signTypedData:(o,h)=>{const a=Et(o),d=V.from(h.privateKey,"hex"),{types:f}=a;function y(A,_=[]){if(_.includes(A)||f[A]===void 0)return _;_.push(A);for(const x of f[A])for(const N of y(x.type,_))_.includes(N)||_.push(N);return _}function k(A){let _=y(A);_=_.filter(N=>N!==A),_=[A].concat(_.sort());let x="";for(const N of _)x+=`${N}(${f[N].map(({name:$,type:H})=>`${H} ${$}`).join(",")})`;return x}function C(A){return S().keccak256(k(A))}function v(A,_){const x=[],N=[];x.push("bytes32"),N.push(C(A));for(const $ of f[A]){let H=_[$.name];if($.type==="string"||$.type==="bytes")x.push("bytes32"),H=S().keccak256(H),N.push(H);else if(f[$.type]!==void 0)x.push("bytes32"),H=S().keccak256(v($.type,H)),N.push(H);else{if($.type.lastIndexOf("]")===$.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");x.push($.type),N.push(H)}}return Pe().rawEncode(x,N)}function E(A,_){return S().keccak256(v(A,_))}function b(){return S().keccak256(V.concat([V.from("1901","hex"),E("EIP712Domain",a.domain),E(a.primaryType,a.message)]))}const L=S().ecsign(b(),d),{v:D,r:K,s:M}=L;return S().bufferToHex(V.concat([S().setLengthLeft(K,32),S().setLengthLeft(M,32),S().toBuffer(D)]))},txRpcParamsToSpendInfo:o=>{const h={otherParams:o};o.to!=null&&(h.publicAddress=o.to),o.value!=null?h.nativeAmount=(0,p.Z8)(o.value):h.nativeAmount="0";let a,d,f;return o.gas!=null&&(d=(0,p.Z8)(o.gas),a="custom"),o.gasPrice!=null&&(f=(0,m.div)((0,p.Z8)(o.gasPrice),se.toString(),18),a="custom"),{currencyCode:this.currencyInfo.currencyCode,spendTargets:[h],networkFeeOption:a,customNetworkFee:{gasLimit:d,gasPrice:f},otherParams:o}}},this.otherMethods={parseWalletConnectV2Payload:o=>R(this,null,function*(){var h,a;try{let d="0",f="0";switch(o.method){case"eth_sendTransaction":case"eth_signTransaction":{const y=(0,n.su)({from:n.XC,to:(0,n.Zz)(n.XC),data:n.XC,gas:(0,n.Zz)(n.XC),gasPrice:(0,n.Zz)(n.XC),value:(0,n.Zz)(n.XC)})(o.params[0]),{gas:k,gasPrice:C,value:v}=y,E=b=>{var L,D;k==null?y.gas=(0,p.X0)(b):b=(0,p.Z8)(k);let K=(D=(L=this.networkFees.default.gasPrice)==null?void 0:L.standardFeeHigh)!=null?D:"0";C==null?y.gasPrice=(0,p.X0)(K):K=(0,p.Z8)(C),f=(0,m.mul)(b,K)};v!=null&&(d=(0,p.Z8)(v)),((h=this.networkFees.default.gasLimit)==null?void 0:h.tokenTransaction)==null?this.ethNetwork.multicastServers("eth_estimateGas",y).then(b=>{const L=(0,m.add)(parseInt(b.result.result,16).toString(),"0");E(L)}).catch(b=>{this.warn("Wallet connect call_request failed to get gas limit",b)}):E((a=this.networkFees.default.gasLimit)==null?void 0:a.tokenTransaction);break}}return{nativeAmount:d,networkFee:f}}catch(d){throw this.warn("Wallet connect call_request ",d),d}}),txRpcParamsToSpendInfo:o=>R(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(o)})}}estimateGasLimit(e){return R(this,null,function*(){var t,s;const{contractAddress:r,estimateGasParams:i,miningFees:u,publicAddress:c}=e,l=i[0].data!=null;if(this.lastEstimatedGasLimit.gasLimit!==""&&this.lastEstimatedGasLimit.publicAddress===c&&this.lastEstimatedGasLimit.contractAddress===r)return this.lastEstimatedGasLimit.gasLimit;let o=u.gasLimit;try{const a=(yield this.ethNetwork.multicastServers("eth_getCode",[i[0].to,"latest"])).result.result!=="0x",d=(f=0)=>R(this,null,function*(){const y=this.networkInfo.defaultNetworkFees.default.gasLimit;try{if(y!=null&&!a&&!l)o=y.regularTransaction;else{const k=yield this.ethNetwork.multicastServers("eth_estimateGas",i);o=(0,m.add)(parseInt(k.result.result,16).toString(),"0"),a&&(o=(0,m.mul)(o,"2"))}this.lastEstimatedGasLimit={publicAddress:c,contractAddress:r,gasLimit:o}}catch{if(y==null){if(f>5)throw new Error("Unable to estimate gas limit after 5 tries. Please try again later");return yield d(f+1)}if(l)throw new Error("Unable to estimate gas limit. Please try again later");y.tokenTransaction!=null&&(o=y.tokenTransaction)}});if(yield d(),(0,m.lt)(o,(s=(t=this.networkFees.default.gasLimit)==null?void 0:t.minGasLimit)!=null?s:"21000"))throw o=u.gasLimit,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum")}catch(h){this.error("makeSpend Error determining gas limit ",h)}return o})}setOtherData(e){this.otherData=pe(e)}updateNetworkFees(){return R(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const s={};Object.keys(t).forEach(r=>{const i=r;s[i]=(0,p.Y7)(t[i])}),this.networkFees.default.gasPrice!=null&&(this.networkFees.default.gasPrice=re(re({},this.networkFees.default.gasPrice),s));break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}})}updateL1RollupParams(){return R(this,null,function*(){if(this.l1RollupParams!=null){try{const e={to:this.l1RollupParams.oracleContractAddress,data:this.l1RollupParams.gasPricel1BaseFeeMethod},t=yield this.ethNetwork.multicastServers("eth_call",e),s=Y(t.result);this.l1RollupParams=fe(re({},this.l1RollupParams),{gasPriceL1Wei:(0,m.ceil)((0,m.mul)((0,p.Z8)(s.result),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=Y(t.result);this.l1RollupParams=fe(re({},this.l1RollupParams),{dynamicOverhead:(0,p.Z8)(s.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return R(this,null,function*(){yield Ae(me.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return R(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:ut;this.infoFeeProvider().then(s=>{this.log.warn("infoFeeProvider:",JSON.stringify(s,null,2)),this.networkFees=(0,p.nu)(this.networkFees,s)}).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>R(this,null,function*(){return yield this.addToLoop("updateNetworkFees",t)})),this.addToLoop("updateL1RollupParams",dt).catch(()=>{}),this.ethNetwork.needsLoop(),Ae(me.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return R(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return R(this,null,function*(){const{publicKey:e}=this.walletLocalData;return{publicAddress:/[A-F]/.test(e)?e:S().toChecksumAddress(e.replace("0x",""))}})}getMaxSpendable(e){return R(this,null,function*(){e=(0,Be.s)(e,this.currencyInfo);const{edgeSpendInfo:t,currencyCode:s}=this.makeSpendCheck(e),r=this.getBalance({currencyCode:e.currencyCode}),u=e.spendTargets[0].publicAddress;if(u==null)throw new Error("makeSpend Missing publicAddress");const{contractAddress:c,data:l,value:o}=this.getTxParameterInformation(t,s,this.currencyInfo);if(e.currencyCode===this.currencyInfo.currencyCode){const h=(a,d)=>R(this,null,function*(){const f=(0,m.sub)(d,a);if((0,m.lte)(f,"1"))return a;const y=(0,m.add)(a,(0,m.div)(f,"2"));e.spendTargets[0].nativeAmount=y;const k=je(e,this.networkFees,this.currencyInfo,this.networkInfo);k.useEstimatedGasLimit&&(k.gasLimit=yield this.estimateGasLimit({contractAddress:c,estimateGasParams:[{to:c!=null?c:u,from:this.walletLocalData.publicKey,gas:"0xffffff",value:o,data:l},"latest"],miningFees:k,publicAddress:u}));const C=(0,m.mul)(k.gasPrice,k.gasLimit);let v="0";if(this.l1RollupParams!=null){const b={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:k.gasLimit,to:u,value:(0,p.X0)(y),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};v=Me(b)}const E=(0,m.add)((0,m.add)(y,C),v);return(0,m.gt)(E,r)?yield h(a,y):yield h(y,d)});return yield h("0",(0,m.add)(r,"1"))}else return e.spendTargets[0].nativeAmount=r,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}getTxParameterInformation(e,t,s){var r;const{memos:i=[]}=e,{spendTargets:u}=e,c=u[0],{publicAddress:l,nativeAmount:o}=c;let h=((r=i[0])==null?void 0:r.type)==="hex"?i[0].value:void 0;h!=null&&!h.startsWith("0x")&&(h=`0x${h}`);let a;if(t===s.currencyCode)return a=o==null?void 0:(0,p.X0)(o),{data:h,value:a};{let d;if(h!=null)d=l;else{const f=this.getTokenInfo(t);if(f==null||typeof f.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");d=f.contractAddress;const y=Pe().simpleEncode("transfer(address,uint256):(uint256)",l,(0,p.X0)(o!=null?o:"0"));a="0x0",h="0x"+V.from(y).toString("hex")}return{contractAddress:d,data:h,value:a}}}makeSpend(e){return R(this,null,function*(){var t,s;e=(0,Be.s)(e,this.currencyInfo);const{edgeSpendInfo:r,currencyCode:i,skipChecks:u}=this.makeSpendCheck(e),{memos:c=[]}=r,{pendingTxs:l=[]}=r;if(r.spendTargets.length!==1)throw new Error("Error: only one output allowed");const o=r.spendTargets[0],{publicAddress:h}=o;let{nativeAmount:a}=o;if(h==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new ne.$D;if(!S().isValidAddress(h))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let d;const f=je(r,this.networkFees,this.currencyInfo,this.networkInfo);let y;if(l.length>0){const A=this.walletLocalData.otherData,_=this.walletLocalData.numUnconfirmedSpendTxs>0?A.unconfirmedNextNonce:A.nextNonce;y=(0,m.add)(_,l.length.toString())}const{contractAddress:k,data:C,value:v}=this.getTxParameterInformation(r,i,this.currencyInfo);k==null?d={from:[this.walletLocalData.publicKey],to:[h],gas:f.gasLimit,gasPrice:f.gasPrice,gasUsed:"0",nonceUsed:y,data:C,isFromMakeSpend:!0}:d={from:[this.walletLocalData.publicKey],to:[k],gas:f.gasLimit,gasPrice:f.gasPrice,gasUsed:"0",tokenRecipientAddress:h,nonceUsed:y,data:C,isFromMakeSpend:!0},f.useEstimatedGasLimit&&(d.gas=yield this.estimateGasLimit({contractAddress:k,estimateGasParams:[{to:k!=null?k:h,from:this.walletLocalData.publicKey,gas:"0xffffff",value:v,data:C},"latest"],miningFees:f,publicAddress:h}));const E=(t=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?t:"0";let b=(0,m.mul)(f.gasPrice,d.gas),L="0",D=null,K="0";if(this.l1RollupParams!=null){const A={nonce:d.nonceUsed,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:d.gas,to:d.to[0],value:v,data:d.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};K=Me(A)}if(i===this.currencyInfo.currencyCode){if(b=(0,m.add)(b,K),L=(0,m.add)(b,a),!u&&(0,m.gt)(L,E))throw new ne.C_;a=(0,m.mul)(L,"-1")}else{if(D=(0,m.add)(b,K),!u&&(0,m.gt)(b,E))throw new ne.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:b});const A=(s=this.walletLocalData.totalBalances[i])!=null?s:"0";if(!u&&(0,m.gt)(a,A))throw new ne.C_;b="0",a=(0,m.mul)(a,"-1")}const M={blockHeight:0,currencyCode:i,date:0,feeRateUsed:Te(f.gasPrice,d.gas),isSend:a.startsWith("-"),memos:c,nativeAmount:a,networkFee:b,otherParams:d,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return D&&(M.parentNetworkFee=D),M})}signMessage(e,t,s){return R(this,null,function*(){const r=Ce(this.currencyInfo.pluginId)(t);if(st(s.otherParams).typedData){const u=JSON.parse(e);try{return this.utils.signTypedData(u,r)}catch{return(0,ot.signTypedData_v4)(V.from(r.privateKey,"hex"),{data:u})}}return this.utils.signMessage(e,r)})}signTx(e,t){return R(this,null,function*(){const s=Ce(this.currencyInfo.pluginId)(t),r=(0,p.Xp)(e),i=(0,p.NC)(r.gas),u=(0,p.NC)(r.gasPrice);let c;if(e.currencyCode===this.currencyInfo.currencyCode){const E=(0,m.add)(e.nativeAmount,e.networkFee);c=(0,m.mul)("-1",E,16)}else c=(0,m.mul)("-1",e.nativeAmount,16);(0,m.lt)(c,"0")&&(c="0x00");let l=r.nonceUsed;if(!l)if(this.walletLocalData.numUnconfirmedSpendTxs&&(0,m.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)){const E=(0,m.sub)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce);if((0,m.lte)(E,"5"))l=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0;else{const b=new Error("Excessive pending spend transactions");throw b.name="ErrorExcessivePendingSpends",b}}else l=this.otherData.nextNonce;const o=(0,p.NC)(l);let h;if(r.data!=null)h=r.data,e.currencyCode!==this.currencyInfo.currencyCode&&(c="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)h="";else{const E=Pe().simpleEncode("transfer(address,uint256):(uint256)",r.tokenRecipientAddress,c);h="0x"+V.from(E).toString("hex"),c="0x00"}const{chainParams:a}=this.networkInfo,d=Oe().custom(a),f={nonce:o,gasPrice:u,gasLimit:i,to:r.to[0],value:c,data:h},y=V.from(s.privateKey,"hex"),k=ct().fromPrivateKey(y);this.warn(`signTx getAddressString ${k.getAddressString()}`);const v=xe.Transaction.fromTxData(f,{common:d}).sign(y);return e.signedTx=(0,p.$9)(v.serialize()),e.txid=(0,p.$9)(v.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=l),this.warn(`signTx
10
10
  ${(0,p.oX)(e)}`),e})}broadcastTx(e){return R(this,null,function*(){return yield this.ethNetwork.multicastServers("broadcastTx",e),this.warn(`SUCCESS broadcastTx
11
- ${(0,p.oX)(e)}`),e})}accelerate(e){return R(this,null,function*(){var t,s,r;const{currencyCode:i}=e,h=(0,n.Vk)(te)(e.otherParams);let c=e.txid,l=yield this.findTransaction(i,(0,p.f0)(c));if(l===-1&&((h==null?void 0:h.replacedTxid)!=null&&h.replacedTxid!==""&&(c=h.replacedTxid,l=yield this.findTransaction(i,(0,p.f0)(c))),l===-1))return null;const o=this.transactionList[i][l],d=(0,n.Vk)(te)(o.otherParams);if(o==null||o.blockHeight!==0||d==null||d.nonceUsed==null||!d.isFromMakeSpend)return null;const a=((t=o.spendTargets)!=null?t:[])[0];if(a==null)return null;const u=(0,g.mul)(d.gasPrice,"2"),f=d.gas,y=fe(re({},d),{gas:f,gasPrice:u,replacedTxid:c});let{nativeAmount:k}=a,C=(0,g.mul)(u,f),v="0",E;const b=(s=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?s:"0";if(i===this.currencyInfo.currencyCode){if(v=(0,g.add)(C,k),(0,g.gt)(v,b))throw new ne.C_;k=(0,g.mul)(v,"-1")}else{if(E=C,(0,g.gt)(C,b))throw new ne.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:C});const L=(r=this.walletLocalData.totalBalances[i])!=null?r:"0";if((0,g.gt)(k,L))throw new ne.C_;C="0",k=(0,g.mul)(k,"-1")}return fe(re({},e),{txid:"",feeRateUsed:Te(u,f),nativeAmount:k,networkFee:C,otherParams:y,parentNetworkFee:E})})}saveTx(e){return R(this,null,function*(){var t;const s=(0,n.Vk)(te)(e.otherParams);if((s==null?void 0:s.replacedTxid)!=null){const{currencyCode:r}=e,i=(0,p.f0)(s.replacedTxid),h=this.findTransaction(r,i);if(h!==-1){const c=this.transactionList[r][h],l=e.metadata,o=fe(re({},c),{metadata:l,blockHeight:-1});this.addTransaction(r,o)}}if(e.blockHeight===0){const r=(t=e.otherParams)==null?void 0:t.nonceUsed;r!=null&&(this.otherData.unconfirmedNextNonce=(0,g.add)(r,"1"))}Ae(me.prototype,this,"saveTx").call(this,e)})}}function zt(m,e,t,s){return R(this,null,function*(){const{currencyInfo:r,initOptions:i}=m,h=Fe(t),c=new me(m,e,h,Z(i),s,r);return yield c.loadEngine(),c})}var Vt=Object.defineProperty,Qt=Object.defineProperties,Yt=Object.getOwnPropertyDescriptors,Ze=Object.getOwnPropertySymbols,qt=Object.prototype.hasOwnProperty,en=Object.prototype.propertyIsEnumerable,We=(m,e,t)=>e in m?Vt(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,ze=(m,e)=>{for(var t in e||(e={}))qt.call(e,t)&&We(m,t,e[t]);if(Ze)for(var t of Ze(e))en.call(e,t)&&We(m,t,e[t]);return m},Ve=(m,e)=>Qt(m,Yt(e)),z=(m,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},h=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,h);c((t=t.apply(m,e)).next())});class Qe{constructor(e){const{builtinTokens:t,currencyInfo:s,io:r,networkInfo:i}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=r,this.networkInfo=i}getDisplayPrivateKey(e){return z(this,null,function*(){const{pluginId:t}=this.currencyInfo;return Ce(t)(e.keys).privateKey})}getDisplayPublicKey(e){return z(this,null,function*(){const{keys:t}=Fe(e);return t.publicKey})}importPrivateKey(e){return z(this,null,function*(){const{pluginId:t}=this.currencyInfo,{pluginMnemonicKeyName:s,pluginRegularKeyName:r}=this.networkInfo;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const i=q.Buffer.from(e.replace(/^0x/,""),"hex");if(!S().isValidPrivate(i))throw new Error("Invalid private key");const h=i.toString("hex"),c={[r]:h};return this.derivePublicKey({type:`wallet:${t}`,id:"fake",keys:c}),c}else{if(!(0,J.validateMnemonic)(e))throw new Error("Invalid input");const i=yield this._mnemonicToHex(e);return{[s]:e,[r]:i}}})}createPrivateKey(e){return z(this,null,function*(){const{pluginMnemonicKeyName:t,pluginRegularKeyName:s}=this.networkInfo;if(e.replace("wallet:","")!==this.currencyInfo.pluginId)throw new Error("InvalidWalletType");const i=q.Buffer.from(this.io.random(32)),h=(0,J.entropyToMnemonic)(i),c=yield this._mnemonicToHex(h);return{[t]:h,[s]:c}})}derivePublicKey(e){return z(this,null,function*(){const{pluginId:t}=this.currencyInfo,{hdPathCoinType:s,pluginMnemonicKeyName:r,pluginRegularKeyName:i}=this.networkInfo;if(e.type!==`wallet:${t}`)throw new Error("Invalid wallet type");let h;if(e.keys[r]!=null){const c=(0,J.mnemonicToSeedSync)(e.keys[r]),l=ae().fromMasterSeed(c),o=`m/44'/${s}'/0'/0`,u=l.derivePath(`${o}/0`).getWallet().getPublicKey(),f=S().pubToAddress(u).toString("hex");h=S().toChecksumAddress(f)}else{const c=q.Buffer.from(e.keys[i].replace(/^0x/,""),"hex");if(!S().isValidPrivate(c))throw new Error("Invalid private key");h=`0x${S().privateToAddress(c).toString("hex")}`}if(!S().isValidAddress(h))throw new Error("Invalid address");return{publicKey:h}})}_mnemonicToHex(e){return z(this,null,function*(){const{hdPathCoinType:t}=this.networkInfo,s=ae().fromMasterSeed((0,J.mnemonicToSeedSync)(e)),r=`m/44'/${t}'/0'/0`;return s.derivePath(`${r}/0`).getWallet().getPrivateKeyString().replace(/^0x/,"")})}parseUri(e,t,s){return z(this,null,function*(){var r,i,h,c,l;const o={};this.networkInfo.uriNetworks.forEach(k=>{o[k]=!0});const{parsedUri:d,edgeParsedUri:a}=(0,G.k)(this.currencyInfo,e,o,t||this.currencyInfo.currencyCode,s);let u="";a.publicAddress&&(u=a.publicAddress,a.publicAddress=a.publicAddress.toLowerCase());let[f,y]=u.split("-");if(y||(y=f,f="pay"),u=y,/[A-F]/.test(u)&&!S().isValidChecksumAddress(u))throw new Error("InvalidPublicAddressError");if(u=u.toLowerCase(),!S().isValidAddress(u||""))throw new Error("InvalidPublicAddressError");if(f==="token"||f==="token_info"){if(!d.query)throw new Error("InvalidUriError");const k=(r=d.query.symbol)!=null?r:"SYM";if(k.length<2||k.length>5)throw new Error("Wrong Token symbol");const C=(i=d.query.name)!=null?i:k,v=(h=d.query.decimals)!=null?h:"18";let E="1000000000000000000";const b=parseInt(v);if(b<0||b>18)throw new Error("Wrong number of decimals");E="1"+"0".repeat(b);const L=(c=d.query.type)!=null?c:this.networkInfo.ercTokenStandard;return{token:{currencyCode:k,contractAddress:y.toLowerCase(),currencyName:C,multiplier:E,denominations:[{name:k,multiplier:E}],type:L.toUpperCase()}}}if(f==="pay"){const k=u,C=d.pathname.split("/")[1],v=d.query;switch(C){case"transfer":{const E=(l=v.address)!=null?l:"",b=k!=null?k:"",L=v.uint256!=null?(0,p.EE)(v.uint256):a.nativeAmount,D=this.currencyInfo.metaTokens.find(K=>K.contractAddress===b);if(t!=null&&(D==null||D.currencyCode!==t))throw new Error("InternalErrorInvalidCurrencyCode");if(!S().isValidAddress(E))throw new Error("InvalidPublicAddressError");if(!S().isValidAddress(b))throw new Error("InvalidContractAddressError");return Ve(ze({},a),{currencyCode:D==null?void 0:D.currencyCode,nativeAmount:L,publicAddress:E})}case void 0:{const E=k,b=v.value!=null?(0,p.EE)(v.value):a.nativeAmount;return Ve(ze({},a),{publicAddress:E,nativeAmount:b})}default:throw new Error("UnsupportedContractFunction")}}throw new Error("InvalidUriError")})}encodeUri(e){return z(this,arguments,function*(t,s=[]){const{publicAddress:r,nativeAmount:i,currencyCode:h}=t;if(!S().isValidAddress(r))throw new Error("InvalidPublicAddressError");let l;if(typeof i=="string"){const d=(0,p.Qs)(h!=null?h:this.currencyInfo.currencyCode,this.currencyInfo,s);if(d==null)throw new Error("InternalErrorInvalidCurrencyCode");l=(0,g.div)(i,d.multiplier,18)}return(0,G.Q)(t,this.currencyInfo.pluginId,l)})}getSplittableTypes(e){return Object.keys(X.s).map(t=>`wallet:${t}`)}getTokenId(e){return z(this,null,function*(){(0,ee.Rp)(e);const t=(0,ee.Oj)(e.networkLocation);if(t==null||!S().isValidAddress(t.contractAddress))throw new Error("ErrorInvalidContractAddress");return t.contractAddress.toLowerCase().replace(/^0x/,"")})}}function tn(m){return z(this,null,function*(){return new Qe(m)})}},88924:function(){},55024:function(){}}]);
11
+ ${(0,p.oX)(e)}`),e})}accelerate(e){return R(this,null,function*(){var t,s,r;const{currencyCode:i}=e,u=(0,n.Vk)(te)(e.otherParams);let c=e.txid,l=yield this.findTransaction(i,(0,p.f0)(c));if(l===-1&&((u==null?void 0:u.replacedTxid)!=null&&u.replacedTxid!==""&&(c=u.replacedTxid,l=yield this.findTransaction(i,(0,p.f0)(c))),l===-1))return null;const o=this.transactionList[i][l],h=(0,n.Vk)(te)(o.otherParams);if(o==null||o.blockHeight!==0||h==null||h.nonceUsed==null||!h.isFromMakeSpend)return null;const a=((t=o.spendTargets)!=null?t:[])[0];if(a==null)return null;const d=(0,m.mul)(h.gasPrice,"2"),f=h.gas,y=fe(re({},h),{gas:f,gasPrice:d,replacedTxid:c});let{nativeAmount:k}=a,C=(0,m.mul)(d,f),v="0",E;const b=(s=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?s:"0";if(i===this.currencyInfo.currencyCode){if(v=(0,m.add)(C,k),(0,m.gt)(v,b))throw new ne.C_;k=(0,m.mul)(v,"-1")}else{if(E=C,(0,m.gt)(C,b))throw new ne.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:C});const L=(r=this.walletLocalData.totalBalances[i])!=null?r:"0";if((0,m.gt)(k,L))throw new ne.C_;C="0",k=(0,m.mul)(k,"-1")}return fe(re({},e),{txid:"",feeRateUsed:Te(d,f),nativeAmount:k,networkFee:C,otherParams:y,parentNetworkFee:E})})}saveTx(e){return R(this,null,function*(){var t;const s=(0,n.Vk)(te)(e.otherParams);if((s==null?void 0:s.replacedTxid)!=null){const{currencyCode:r}=e,i=(0,p.f0)(s.replacedTxid),u=this.findTransaction(r,i);if(u!==-1){const c=this.transactionList[r][u],l=e.metadata,o=fe(re({},c),{metadata:l,blockHeight:-1});this.addTransaction(r,o)}}if(e.blockHeight===0){const r=(t=e.otherParams)==null?void 0:t.nonceUsed;r!=null&&(this.otherData.unconfirmedNextNonce=(0,m.add)(r,"1"))}Ae(me.prototype,this,"saveTx").call(this,e)})}}function zt(g,e,t,s){return R(this,null,function*(){const{currencyInfo:r,initOptions:i}=g,u=Fe(t),c=new me(g,e,u,Z(i),s,r);return yield c.loadEngine(),c})}var Vt=Object.defineProperty,Qt=Object.defineProperties,Yt=Object.getOwnPropertyDescriptors,Ze=Object.getOwnPropertySymbols,qt=Object.prototype.hasOwnProperty,en=Object.prototype.propertyIsEnumerable,We=(g,e,t)=>e in g?Vt(g,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):g[e]=t,ze=(g,e)=>{for(var t in e||(e={}))qt.call(e,t)&&We(g,t,e[t]);if(Ze)for(var t of Ze(e))en.call(e,t)&&We(g,t,e[t]);return g},Ve=(g,e)=>Qt(g,Yt(e)),z=(g,e,t)=>new Promise((s,r)=>{var i=l=>{try{c(t.next(l))}catch(o){r(o)}},u=l=>{try{c(t.throw(l))}catch(o){r(o)}},c=l=>l.done?s(l.value):Promise.resolve(l.value).then(i,u);c((t=t.apply(g,e)).next())});class Qe{constructor(e){const{builtinTokens:t,currencyInfo:s,io:r,networkInfo:i}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=r,this.networkInfo=i}getDisplayPrivateKey(e){return z(this,null,function*(){const{pluginId:t}=this.currencyInfo;return Ce(t)(e.keys).privateKey})}getDisplayPublicKey(e){return z(this,null,function*(){const{keys:t}=Fe(e);return t.publicKey})}importPrivateKey(e){return z(this,null,function*(){const{pluginId:t}=this.currencyInfo,{pluginMnemonicKeyName:s,pluginRegularKeyName:r}=this.networkInfo;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const i=q.Buffer.from(e.replace(/^0x/,""),"hex");if(!S().isValidPrivate(i))throw new Error("Invalid private key");const u=i.toString("hex"),c={[r]:u};return this.derivePublicKey({type:`wallet:${t}`,id:"fake",keys:c}),c}else{if(!(0,J.validateMnemonic)(e))throw new Error("Invalid input");const i=yield this._mnemonicToHex(e);return{[s]:e,[r]:i}}})}createPrivateKey(e){return z(this,null,function*(){const{pluginMnemonicKeyName:t,pluginRegularKeyName:s}=this.networkInfo;if(e.replace("wallet:","")!==this.currencyInfo.pluginId)throw new Error("InvalidWalletType");const i=q.Buffer.from(this.io.random(32)),u=(0,J.entropyToMnemonic)(i),c=yield this._mnemonicToHex(u);return{[t]:u,[s]:c}})}derivePublicKey(e){return z(this,null,function*(){const{pluginId:t}=this.currencyInfo,{hdPathCoinType:s,pluginMnemonicKeyName:r,pluginRegularKeyName:i}=this.networkInfo;if(e.type!==`wallet:${t}`)throw new Error("Invalid wallet type");let u;if(e.keys[r]!=null){const c=(0,J.mnemonicToSeedSync)(e.keys[r]),l=ae().fromMasterSeed(c),o=`m/44'/${s}'/0'/0`,d=l.derivePath(`${o}/0`).getWallet().getPublicKey(),f=S().pubToAddress(d).toString("hex");u=S().toChecksumAddress(f)}else{const c=q.Buffer.from(e.keys[i].replace(/^0x/,""),"hex");if(!S().isValidPrivate(c))throw new Error("Invalid private key");u=`0x${S().privateToAddress(c).toString("hex")}`}if(!S().isValidAddress(u))throw new Error("Invalid address");return{publicKey:u}})}_mnemonicToHex(e){return z(this,null,function*(){const{hdPathCoinType:t}=this.networkInfo,s=ae().fromMasterSeed((0,J.mnemonicToSeedSync)(e)),r=`m/44'/${t}'/0'/0`;return s.derivePath(`${r}/0`).getWallet().getPrivateKeyString().replace(/^0x/,"")})}parseUri(e,t,s){return z(this,null,function*(){var r,i,u,c,l;const o={};this.networkInfo.uriNetworks.forEach(k=>{o[k]=!0});const{parsedUri:h,edgeParsedUri:a}=(0,G.k)(this.currencyInfo,e,o,t||this.currencyInfo.currencyCode,s);let d="";a.publicAddress&&(d=a.publicAddress,a.publicAddress=a.publicAddress.toLowerCase());let[f,y]=d.split("-");if(y||(y=f,f="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(f==="token"||f==="token_info"){if(!h.query)throw new Error("InvalidUriError");const k=(r=h.query.symbol)!=null?r:"SYM";if(k.length<2||k.length>5)throw new Error("Wrong Token symbol");const C=(i=h.query.name)!=null?i:k,v=(u=h.query.decimals)!=null?u:"18";let E="1000000000000000000";const b=parseInt(v);if(b<0||b>18)throw new Error("Wrong number of decimals");E="1"+"0".repeat(b);const L=(c=h.query.type)!=null?c:this.networkInfo.ercTokenStandard;return{token:{currencyCode:k,contractAddress:y.toLowerCase(),currencyName:C,multiplier:E,denominations:[{name:k,multiplier:E}],type:L.toUpperCase()}}}if(f==="pay"){const k=d,C=h.pathname.split("/")[1],v=h.query;switch(C){case"transfer":{const E=(l=v.address)!=null?l:"",b=k!=null?k:"",L=v.uint256!=null?(0,p.EE)(v.uint256):a.nativeAmount,D=this.currencyInfo.metaTokens.find(K=>K.contractAddress===b);if(t!=null&&(D==null||D.currencyCode!==t))throw new Error("InternalErrorInvalidCurrencyCode");if(!S().isValidAddress(E))throw new Error("InvalidPublicAddressError");if(!S().isValidAddress(b))throw new Error("InvalidContractAddressError");return Ve(ze({},a),{currencyCode:D==null?void 0:D.currencyCode,nativeAmount:L,publicAddress:E})}case void 0:{const E=k,b=v.value!=null?(0,p.EE)(v.value):a.nativeAmount;return Ve(ze({},a),{publicAddress:E,nativeAmount:b})}default:throw new Error("UnsupportedContractFunction")}}throw new Error("InvalidUriError")})}encodeUri(e){return z(this,arguments,function*(t,s=[]){const{publicAddress:r,nativeAmount:i,currencyCode:u}=t;if(!S().isValidAddress(r))throw new Error("InvalidPublicAddressError");let l;if(typeof i=="string"){const h=(0,p.Qs)(u!=null?u:this.currencyInfo.currencyCode,this.currencyInfo,s);if(h==null)throw new Error("InternalErrorInvalidCurrencyCode");l=(0,m.div)(i,h.multiplier,18)}return(0,G.Q)(t,this.currencyInfo.pluginId,l)})}getSplittableTypes(e){return Object.keys(X.s).map(t=>`wallet:${t}`)}getTokenId(e){return z(this,null,function*(){(0,ee.Rp)(e);const t=(0,ee.Oj)(e.networkLocation);if(t==null||!S().isValidAddress(t.contractAddress))throw new Error("ErrorInvalidContractAddress");return t.contractAddress.toLowerCase().replace(/^0x/,"")})}}function tn(g){return z(this,null,function*(){return new Qe(g)})}},88924:function(){},55024:function(){}}]);
@@ -1,2 +1,2 @@
1
- "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[159],{79014:function(W,B,h){h.d(B,{Q:function(){return x},k:function(){return b}});var m=h(77591),U=h.n(m),R=h(24350),O=h(84564),H=h.n(O),z=h(76714),g=Object.defineProperty,N=Object.getOwnPropertySymbols,L=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,A=(a,p,y)=>p in a?g(a,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):a[p]=y,E=(a,p)=>{for(var y in p||(p={}))L.call(p,y)&&A(a,y,p[y]);if(N)for(var y of N(p))K.call(p,y)&&A(a,y,p[y]);return a};function b(a,p,y,w,D=[]){const d=E({},H()(p,{},!0)),T=p.startsWith(`${a.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!y[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${a.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const k={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},C=d.query.label,f=d.query.message,I=d.query.category;(C!=null||f!=null||I!=null||T)&&(k.metadata={},k.metadata.name=C,k.metadata.notes=f,k.metadata.category=I,k.metadata.gateway=T!=null?T:!1);const S=d.query.amount;if(S!=null&&typeof S=="string"){w==null&&(w=a.currencyCode);const v=(0,z.Qs)(w!=null?w:"",a,D);if(v==null)throw new Error("InternalErrorInvalidCurrencyCode");let P=(0,m.mul)(S,v.multiplier);P=(0,m.toFixed)(P,0,0),k.nativeAmount=P,k.currencyCode=w}return{edgeParsedUri:k,parsedUri:d}}function x(a,p,y){if(a.publicAddress==null)throw new Error("InvalidPublicAddressError");if(y==null&&a.label==null&&a.message==null)return a.publicAddress;{let w="";y!=null&&(w+="amount="+y+"&"),(a.label!=null||a.message!=null)&&(typeof a.label=="string"&&(w+="label="+a.label+"&"),typeof a.message=="string"&&(w+="message="+a.message+"&")),w=w.substr(0,w.length-1);const D={scheme:p,path:a.publicAddress,query:w};return(0,R.qC)(D)}}},62560:function(W,B,h){h.r(B),h.d(B,{ZcashTools:function(){return P},makeCurrencyEngine:function(){return S},makeCurrencyTools:function(){return F}});var m=h(77591),U=h(2153),R=h(48764),O=h(62177),H=h(79014),z=h(76714),g=h(82448);const N=(0,g.su)({first:g.mH,last:g.mH}),L=(0,g.su)({alias:(0,g.Vk)(g.XC),blockRange:(0,g.Vk)(N,()=>({first:0,last:0}))}),K=(0,g.su)({birthdayHeight:g.mH,publicKey:g.XC}),A=(0,O.jd)(K),E=l=>{const t=(0,g.su)({[`${l}Mnemonic`]:g.XC,[`${l}BirthdayHeight`]:g.mH});return(0,g.W1)(e=>{const n=t(e);return{mnemonic:n[`${l}Mnemonic`],birthdayHeight:n[`${l}BirthdayHeight`]}},e=>({[`${l}Mnemonic`]:e.mnemonic,[`${l}BirthdayHeight`]:e.birthdayHeight}))};var b=h(94935),x=h(84650),a=h(72681),p=Object.defineProperty,y=Object.getOwnPropertySymbols,w=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,d=Object.prototype.propertyIsEnumerable,T=Reflect.get,$=(l,t,e)=>t in l?p(l,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[t]=e,k=(l,t)=>{for(var e in t||(t={}))D.call(t,e)&&$(l,e,t[e]);if(y)for(var e of y(t))d.call(t,e)&&$(l,e,t[e]);return l},C=(l,t,e)=>T(w(l),e,t),f=(l,t,e)=>new Promise((n,r)=>{var i=s=>{try{c(e.next(s))}catch(u){r(u)}},o=s=>{try{c(e.throw(s))}catch(u){r(u)}},c=s=>s.done?n(s.value):Promise.resolve(s.value).then(i,o);c((e=e.apply(l,t)).next())});class I extends x.P{constructor(t,e,n,r,i){super(t,e,n,r);const{networkInfo:o}=t;this.pluginId=this.currencyInfo.pluginId,this.networkInfo=o,this.makeSynchronizer=i,this.queryMutex=!1,this.started=!1}setOtherData(t){this.otherData=L(t)}initData(){const{birthdayHeight:t}=this.initializer;this.otherData.blockRange.first===0&&(this.otherData.blockRange={first:t,last:t}),this.initialNumBlocksToDownload=-1,this.synchronizerStatus="DISCONNECTED",this.availableZatoshi="0",this.progressRatio=0}initSubscriptions(){this.synchronizer!=null&&(this.synchronizer.on("update",t=>f(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=>f(this,null,function*(){this.synchronizerStatus=t.name,yield this.queryAll()})))}queryAll(){return f(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 o=n-t;this.initialNumBlocksToDownload<0&&(this.initialNumBlocksToDownload=o),r=o===0||this.initialNumBlocksToDownload===0?1:1-o/this.initialNumBlocksToDownload}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=r*.8;const i=(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]+this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode])/2;i!==this.progressRatio&&(Math.abs(i-this.progressRatio)>.1||i===1)&&(this.progressRatio=i,this.updateOnAddressesChecked())}}startEngine(){return f(this,null,function*(){this.engineOn=!0,this.started=!0,yield C(I.prototype,this,"startEngine").call(this)})}isSynced(){return this.synchronizerStatus==="SYNCED"}queryBalance(){return f(this,null,function*(){if(!(!this.isSynced()||this.synchronizer==null))try{const t=yield this.synchronizer.getBalance();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 f(this,null,function*(){if(this.synchronizer!=null)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=[];t.memo!=null&&r.push({type:"text",value:t.memo});const i={blockHeight:t.minedHeight,currencyCode:this.currencyInfo.currencyCode,date:t.blockTimeInSeconds,isSend:e.startsWith("-"),memos:r,nativeAmount:e,networkFee:this.networkInfo.defaultNetworkFee,otherParams:{},ourReceiveAddresses:n,signedTx:"",txid:t.rawTransactionId,walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,i)}syncNetwork(t){return f(this,null,function*(){if(!this.started)return 1e3;const e=E(this.currencyInfo.pluginId)(t==null?void 0:t.privateKeys),{rpcNode:n}=this.networkInfo;return this.initializer=k({mnemonicSeed:e.mnemonic,birthdayHeight:e.birthdayHeight,alias:this.walletInfo.keys.publicKey.slice(0,99)},n),this.synchronizer=yield this.makeSynchronizer(this.initializer),this.initData(),this.initSubscriptions(),yield new Promise(r=>{this.stopSyncing=r})})}killEngine(){return f(this,null,function*(){var t;this.started=!1,this.stopSyncing!=null&&(yield this.stopSyncing(1e3),this.stopSyncing=void 0),yield(t=this.synchronizer)==null?void 0:t.stop(),yield C(I.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return f(this,null,function*(){yield C(I.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return f(this,null,function*(){var t;yield C(I.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine(),(t=this.synchronizer)==null||t.rescan().catch(e=>this.warn("resyncBlockchain failed: ",e)),this.initData(),this.synchronizerStatus="SYNCING"})}getMaxSpendable(){return f(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 f(this,null,function*(){var e;if(t=(0,a.s)(t,this.currencyInfo),!this.isSynced())throw new Error("Cannot spend until wallet is synced");const{edgeSpendInfo:n,currencyCode:r}=this.makeSpendCheck(t),{memos:i=[]}=n,o=n.spendTargets[0],{publicAddress:c,nativeAmount:s}=o;if(c==null)throw new Error("makeSpend Missing publicAddress");if(s==null)throw new b.$D;if((0,m.eq)(s,"0"))throw new b.$D;const u=(0,m.add)(s,this.networkInfo.defaultNetworkFee);if((0,m.gt)(u,(e=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?e:"0"))throw new b.C_;if((0,m.gt)(u,this.availableZatoshi))throw new b.C_("Amount exceeds available balance");const M=(0,m.mul)(u,"-1");return{blockHeight:0,currencyCode:r,date:0,isSend:!0,memos:i,nativeAmount:M,networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t){return f(this,null,function*(){return t})}broadcastTx(t,e){return f(this,null,function*(){var n;if(this.synchronizer==null)throw new Error("Synchronizer undefined");const{memos:r}=t,i=E(this.pluginId)(e==null?void 0:e.privateKeys);if(t.spendTargets==null||t.spendTargets.length!==1)throw new Error("Invalid spend targets");const o=((n=r[0])==null?void 0:n.type)==="text"?r[0].value:"",c=t.spendTargets[0],s={zatoshi:(0,m.sub)((0,m.abs)(t.nativeAmount),t.networkFee),toAddress:c.publicAddress,memo:o,fromAccountIndex:0,mnemonicSeed:i.mnemonic};try{const u=yield this.synchronizer.sendToAddress(s);t.txid=u.txId,t.signedTx=u.raw,t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
- ${(0,z.oX)(t)}`)}catch(u){throw this.warn("FAILURE broadcastTx failed: ",u),u}return t})}getFreshAddress(){return f(this,null,function*(){if(this.synchronizer==null)throw new Error("Synchronizer undefined");return{publicAddress:yield this.synchronizer.deriveUnifiedAddress()}})}}function S(l,t,e,n){return f(this,null,function*(){const r=A(e),{makeSynchronizer:i}=l.nativeIo["edge-currency-accountbased"].zcash,o=new I(l,t,r,n,i);return yield o.loadEngine(),o})}var v=(l,t,e)=>new Promise((n,r)=>{var i=s=>{try{c(e.next(s))}catch(u){r(u)}},o=s=>{try{c(e.throw(s))}catch(u){r(u)}},c=s=>s.done?n(s.value):Promise.resolve(s.value).then(i,o);c((e=e.apply(l,t)).next())});class P{constructor(t){const{builtinTokens:e,currencyInfo:n,io:r,networkInfo:i}=t;this.builtinTokens=e,this.currencyInfo=n,this.io=r,this.networkInfo=i;const o=t.nativeIo["edge-currency-accountbased"];if(o==null)throw new Error("Need opts");const{Tools:c}=o.zcash;this.nativeTools=c}getDisplayPrivateKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;return E(e)(t.keys).mnemonic})}getDisplayPublicKey(t){return v(this,null,function*(){const{keys:e}=A(t);return e.publicKey})}getNewWalletBirthdayBlockheight(){return v(this,null,function*(){try{return yield this.nativeTools.getBirthdayHeight(this.networkInfo.rpcNode.defaultHost,this.networkInfo.rpcNode.defaultPort)}catch{return this.networkInfo.defaultBirthday}})}isValidAddress(t){return v(this,null,function*(){return yield this.nativeTools.isValidAddress(t)})}importPrivateKey(t){return v(this,arguments,function*(e,n={}){const{pluginId:r}=this.currencyInfo;if(!(0,U.validateMnemonic)(e))throw new Error(`Invalid ${this.currencyInfo.currencyCode} mnemonic`);const o=yield this.getNewWalletBirthdayBlockheight();let c=o;const{birthdayHeight:s}=n;if(s!=null){(0,O.jD)(s);const u=parseInt(s);if(u>o)throw new Error("InvalidBirthdayHeight");c=u}return{[`${r}Mnemonic`]:e,[`${r}BirthdayHeight`]:c}})}createPrivateKey(t){return v(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=R.Buffer.from(this.io.random(32)).toString("hex"),n=(0,U.entropyToMnemonic)(e);return yield this.importPrivateKey(n)})}checkPublicKey(t){return v(this,null,function*(){try{return K(t),!0}catch{return!1}})}derivePublicKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo,n=E(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 this.nativeTools.deriveViewingKey(r,this.networkInfo.rpcNode.networkName);return{birthdayHeight:n.birthdayHeight,publicKey:i}})}parseUri(t,e,n){return v(this,null,function*(){const{pluginId:r}=this.currencyInfo,i={[r]:!0},{edgeParsedUri:o,edgeParsedUri:{publicAddress:c}}=(0,H.k)(this.currencyInfo,t,i,e!=null?e:this.currencyInfo.currencyCode,n);if(c==null||!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");return o})}encodeUri(t){return v(this,arguments,function*(e,n=[]){const{pluginId:r}=this.currencyInfo,{nativeAmount:i,currencyCode:o,publicAddress:c}=e;if(!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");let s;if(i!=null){const M=(0,z.Qs)(o!=null?o:this.currencyInfo.currencyCode,this.currencyInfo,n);if(M==null)throw new Error("InternalErrorInvalidCurrencyCode");s=(0,m.div)(i,M.multiplier,18)}return(0,H.Q)(e,`${r}`,s)})}}function F(l){return v(this,null,function*(){return new P(l)})}}}]);
1
+ "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[159],{79014:function(W,B,h){h.d(B,{Q:function(){return L},k:function(){return b}});var g=h(77591),U=h.n(g),R=h(24350),O=h(84564),H=h.n(O),z=h(76714),m=Object.defineProperty,N=Object.getOwnPropertySymbols,x=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,A=(a,p,y)=>p in a?m(a,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):a[p]=y,E=(a,p)=>{for(var y in p||(p={}))x.call(p,y)&&A(a,y,p[y]);if(N)for(var y of N(p))K.call(p,y)&&A(a,y,p[y]);return a};function b(a,p,y,w,D=[]){const d=E({},H()(p,{},!0)),T=p.startsWith(`${a.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!y[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${a.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const k={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},C=d.query.label,f=d.query.message,I=d.query.category;(C!=null||f!=null||I!=null||T)&&(k.metadata={},k.metadata.name=C,k.metadata.notes=f,k.metadata.category=I,k.metadata.gateway=T!=null?T:!1);const S=d.query.amount;if(S!=null&&typeof S=="string"){w==null&&(w=a.currencyCode);const v=(0,z.Qs)(w!=null?w:"",a,D);if(v==null)throw new Error("InternalErrorInvalidCurrencyCode");let P=(0,g.mul)(S,v.multiplier);P=(0,g.toFixed)(P,0,0),k.nativeAmount=P,k.currencyCode=w}return{edgeParsedUri:k,parsedUri:d}}function L(a,p,y){if(a.publicAddress==null)throw new Error("InvalidPublicAddressError");if(y==null&&a.label==null&&a.message==null)return a.publicAddress;{let w="";y!=null&&(w+="amount="+y+"&"),(a.label!=null||a.message!=null)&&(typeof a.label=="string"&&(w+="label="+a.label+"&"),typeof a.message=="string"&&(w+="message="+a.message+"&")),w=w.substr(0,w.length-1);const D={scheme:p,path:a.publicAddress,query:w};return(0,R.qC)(D)}}},62560:function(W,B,h){h.r(B),h.d(B,{ZcashTools:function(){return P},makeCurrencyEngine:function(){return S},makeCurrencyTools:function(){return F}});var g=h(77591),U=h(2153),R=h(48764),O=h(62177),H=h(79014),z=h(76714),m=h(82448);const N=(0,m.su)({first:m.mH,last:m.mH}),x=(0,m.su)({alias:(0,m.Vk)(m.XC),blockRange:(0,m.Vk)(N,()=>({first:0,last:0}))}),K=(0,m.su)({birthdayHeight:m.mH,publicKey:m.XC}),A=(0,O.jd)(K),E=l=>{const t=(0,m.su)({[`${l}Mnemonic`]:m.XC,[`${l}BirthdayHeight`]:m.mH});return(0,m.W1)(e=>{const n=t(e);return{mnemonic:n[`${l}Mnemonic`],birthdayHeight:n[`${l}BirthdayHeight`]}},e=>({[`${l}Mnemonic`]:e.mnemonic,[`${l}BirthdayHeight`]:e.birthdayHeight}))};var b=h(94935),L=h(84650),a=h(72681),p=Object.defineProperty,y=Object.getOwnPropertySymbols,w=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,d=Object.prototype.propertyIsEnumerable,T=Reflect.get,$=(l,t,e)=>t in l?p(l,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[t]=e,k=(l,t)=>{for(var e in t||(t={}))D.call(t,e)&&$(l,e,t[e]);if(y)for(var e of y(t))d.call(t,e)&&$(l,e,t[e]);return l},C=(l,t,e)=>T(w(l),e,t),f=(l,t,e)=>new Promise((n,r)=>{var s=o=>{try{c(e.next(o))}catch(u){r(u)}},i=o=>{try{c(e.throw(o))}catch(u){r(u)}},c=o=>o.done?n(o.value):Promise.resolve(o.value).then(s,i);c((e=e.apply(l,t)).next())});class I extends L.P{constructor(t,e,n,r,s){super(t,e,n,r);const{networkInfo:i}=t;this.pluginId=this.currencyInfo.pluginId,this.networkInfo=i,this.makeSynchronizer=s,this.queryMutex=!1,this.started=!1}setOtherData(t){this.otherData=x(t)}initData(){const{birthdayHeight:t}=this.initializer;this.otherData.blockRange.first===0&&(this.otherData.blockRange={first:t,last:t}),this.initialNumBlocksToDownload=-1,this.synchronizerStatus="DISCONNECTED",this.availableZatoshi="0",this.progressRatio=0}initSubscriptions(){this.synchronizer!=null&&(this.synchronizer.on("update",t=>f(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=>f(this,null,function*(){this.synchronizerStatus=t.name,yield this.queryAll()})))}queryAll(){return f(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 s=(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]+this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode])/2;s!==this.progressRatio&&(Math.abs(s-this.progressRatio)>.1||s===1)&&(this.progressRatio=s,this.updateOnAddressesChecked())}}startEngine(){return f(this,null,function*(){this.engineOn=!0,this.started=!0,yield C(I.prototype,this,"startEngine").call(this)})}isSynced(){return this.synchronizerStatus==="SYNCED"}queryBalance(){return f(this,null,function*(){if(!(!this.isSynced()||this.synchronizer==null))try{const t=yield this.synchronizer.getBalance();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 f(this,null,function*(){if(this.synchronizer!=null)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,g.add)(e,this.networkInfo.defaultNetworkFee)}`:n.push(this.walletInfo.keys.publicKey);const r=t.memos.filter(i=>i!=="").map(i=>({memoName:"memo",type:"text",value:i})),s={blockHeight:t.minedHeight,currencyCode:this.currencyInfo.currencyCode,date:t.blockTimeInSeconds,isSend:e.startsWith("-"),memos:r,nativeAmount:e,networkFee:this.networkInfo.defaultNetworkFee,otherParams:{},ourReceiveAddresses:n,signedTx:"",txid:t.rawTransactionId,walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,s)}syncNetwork(t){return f(this,null,function*(){if(!this.started)return 1e3;const e=E(this.currencyInfo.pluginId)(t==null?void 0:t.privateKeys),{rpcNode:n}=this.networkInfo;return this.initializer=k({mnemonicSeed:e.mnemonic,birthdayHeight:e.birthdayHeight,alias:this.walletInfo.keys.publicKey.slice(0,99)},n),this.synchronizer=yield this.makeSynchronizer(this.initializer),this.initData(),this.initSubscriptions(),yield new Promise(r=>{this.stopSyncing=r})})}killEngine(){return f(this,null,function*(){var t;this.started=!1,this.stopSyncing!=null&&(yield this.stopSyncing(1e3),this.stopSyncing=void 0),yield(t=this.synchronizer)==null?void 0:t.stop(),yield C(I.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return f(this,null,function*(){yield C(I.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return f(this,null,function*(){var t;yield C(I.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine(),(t=this.synchronizer)==null||t.rescan().catch(e=>this.warn("resyncBlockchain failed: ",e)),this.initData(),this.synchronizerStatus="SYNCING"})}getMaxSpendable(){return f(this,null,function*(){const t=(0,g.sub)(this.availableZatoshi,this.networkInfo.defaultNetworkFee);if((0,g.lte)(t,"0"))throw new b.C_;return t})}makeSpend(t){return f(this,null,function*(){var e;if(t=(0,a.s)(t,this.currencyInfo),!this.isSynced())throw new Error("Cannot spend until wallet is synced");const{edgeSpendInfo:n,currencyCode:r}=this.makeSpendCheck(t),{memos:s=[]}=n,i=n.spendTargets[0],{publicAddress:c,nativeAmount:o}=i;if(c==null)throw new Error("makeSpend Missing publicAddress");if(o==null)throw new b.$D;if((0,g.eq)(o,"0"))throw new b.$D;const u=(0,g.add)(o,this.networkInfo.defaultNetworkFee);if((0,g.gt)(u,(e=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?e:"0"))throw new b.C_;if((0,g.gt)(u,this.availableZatoshi))throw new b.C_("Amount exceeds available balance");const M=(0,g.mul)(u,"-1");return{blockHeight:0,currencyCode:r,date:0,isSend:!0,memos:s,nativeAmount:M,networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t){return f(this,null,function*(){return t})}broadcastTx(t,e){return f(this,null,function*(){var n;if(this.synchronizer==null)throw new Error("Synchronizer undefined");const{memos:r}=t,s=E(this.pluginId)(e==null?void 0:e.privateKeys);if(t.spendTargets==null||t.spendTargets.length!==1)throw new Error("Invalid spend targets");const i=((n=r[0])==null?void 0:n.type)==="text"?r[0].value:"",c=t.spendTargets[0],o={zatoshi:(0,g.sub)((0,g.abs)(t.nativeAmount),t.networkFee),toAddress:c.publicAddress,memo:i,fromAccountIndex:0,mnemonicSeed:s.mnemonic};try{const u=yield this.synchronizer.sendToAddress(o);t.txid=u.txId,t.signedTx=u.raw,t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
+ ${(0,z.oX)(t)}`)}catch(u){throw this.warn("FAILURE broadcastTx failed: ",u),u}return t})}getFreshAddress(){return f(this,null,function*(){if(this.synchronizer==null)throw new Error("Synchronizer undefined");return{publicAddress:yield this.synchronizer.deriveUnifiedAddress()}})}}function S(l,t,e,n){return f(this,null,function*(){const r=A(e),{makeSynchronizer:s}=l.nativeIo["edge-currency-accountbased"].zcash,i=new I(l,t,r,n,s);return yield i.loadEngine(),i})}var v=(l,t,e)=>new Promise((n,r)=>{var s=o=>{try{c(e.next(o))}catch(u){r(u)}},i=o=>{try{c(e.throw(o))}catch(u){r(u)}},c=o=>o.done?n(o.value):Promise.resolve(o.value).then(s,i);c((e=e.apply(l,t)).next())});class P{constructor(t){const{builtinTokens:e,currencyInfo:n,io:r,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=n,this.io=r,this.networkInfo=s;const i=t.nativeIo["edge-currency-accountbased"];if(i==null)throw new Error("Need opts");const{Tools:c}=i.zcash;this.nativeTools=c}getDisplayPrivateKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;return E(e)(t.keys).mnemonic})}getDisplayPublicKey(t){return v(this,null,function*(){const{keys:e}=A(t);return e.publicKey})}getNewWalletBirthdayBlockheight(){return v(this,null,function*(){try{return yield this.nativeTools.getBirthdayHeight(this.networkInfo.rpcNode.defaultHost,this.networkInfo.rpcNode.defaultPort)}catch{return this.networkInfo.defaultBirthday}})}isValidAddress(t){return v(this,null,function*(){return yield this.nativeTools.isValidAddress(t)})}importPrivateKey(t){return v(this,arguments,function*(e,n={}){const{pluginId:r}=this.currencyInfo;if(!(0,U.validateMnemonic)(e))throw new Error(`Invalid ${this.currencyInfo.currencyCode} mnemonic`);const i=yield this.getNewWalletBirthdayBlockheight();let c=i;const{birthdayHeight:o}=n;if(o!=null){(0,O.jD)(o);const u=parseInt(o);if(u>i)throw new Error("InvalidBirthdayHeight");c=u}return{[`${r}Mnemonic`]:e,[`${r}BirthdayHeight`]:c}})}createPrivateKey(t){return v(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=R.Buffer.from(this.io.random(32)).toString("hex"),n=(0,U.entropyToMnemonic)(e);return yield this.importPrivateKey(n)})}checkPublicKey(t){return v(this,null,function*(){try{return K(t),!0}catch{return!1}})}derivePublicKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo,n=E(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 s=yield this.nativeTools.deriveViewingKey(r,this.networkInfo.rpcNode.networkName);return{birthdayHeight:n.birthdayHeight,publicKey:s}})}parseUri(t,e,n){return v(this,null,function*(){const{pluginId:r}=this.currencyInfo,s={[r]:!0},{edgeParsedUri:i,edgeParsedUri:{publicAddress:c}}=(0,H.k)(this.currencyInfo,t,s,e!=null?e:this.currencyInfo.currencyCode,n);if(c==null||!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");return i})}encodeUri(t){return v(this,arguments,function*(e,n=[]){const{pluginId:r}=this.currencyInfo,{nativeAmount:s,currencyCode:i,publicAddress:c}=e;if(!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");let o;if(s!=null){const M=(0,z.Qs)(i!=null?i:this.currencyInfo.currencyCode,this.currencyInfo,n);if(M==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,g.div)(s,M.multiplier,18)}return(0,H.Q)(e,`${r}`,o)})}}function F(l){return v(this,null,function*(){return new P(l)})}}}]);
@@ -818,6 +818,9 @@ var _feeProviders = require('./fees/feeProviders');
818
818
 
819
819
  // Get data:
820
820
  let data = _optionalChain([memos, 'access', _18 => _18[0], 'optionalAccess', _19 => _19.type]) === 'hex' ? memos[0].value : undefined
821
+ if (data != null && !data.startsWith('0x')) {
822
+ data = `0x${data}`
823
+ }
821
824
 
822
825
  // Get contractAddress and/or value:
823
826
  let value
@@ -256,7 +256,7 @@ const MAX_SIGNATURE_COST = '1040' // (32 + 32 + 1) * 16 max cost for adding r, s
256
256
 
257
257
  const scalar = _biggystring.div.call(void 0, dynamicOverhead, '1000000', 18)
258
258
 
259
- const total = _biggystring.mul.call(void 0, _biggystring.mul.call(void 0, gasPriceL1Wei, gasUsed), scalar)
259
+ const total = _biggystring.ceil.call(void 0, _biggystring.mul.call(void 0, _biggystring.mul.call(void 0, gasPriceL1Wei, gasUsed), scalar), 0)
260
260
 
261
261
  return total
262
262
  }; exports.calcL1RollupFees = calcL1RollupFees
@@ -261,20 +261,20 @@ var _zcashTypes = require('./zcashTypes');
261
261
  ourReceiveAddresses.push(this.walletInfo.keys.publicKey)
262
262
  }
263
263
 
264
- const memos = []
265
- if (tx.memo != null) {
266
- memos.push({
264
+ const edgeMemos = tx.memos
265
+ .filter(text => text !== '')
266
+ .map(text => ({
267
+ memoName: 'memo',
267
268
  type: 'text',
268
- value: tx.memo
269
- })
270
- }
269
+ value: text
270
+ }))
271
271
 
272
272
  const edgeTransaction = {
273
273
  blockHeight: tx.minedHeight,
274
274
  currencyCode: this.currencyInfo.currencyCode,
275
275
  date: tx.blockTimeInSeconds,
276
276
  isSend: netNativeAmount.startsWith('-'),
277
- memos,
277
+ memos: edgeMemos,
278
278
  nativeAmount: netNativeAmount,
279
279
  networkFee: this.networkInfo.defaultNetworkFee,
280
280
  otherParams: {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "edge-currency-accountbased",
3
- "version": "2.4.0",
3
+ "version": "2.4.1",
4
4
  "description": "Edge currency plugin for account based currencies",
5
5
  "homepage": "https://edge.app/",
6
6
  "repository": {
@@ -140,7 +140,7 @@
140
140
  "path-browserify": "^1.0.1",
141
141
  "prettier": "^2.2.0",
142
142
  "process": "^0.11.10",
143
- "react-native-zcash": "0.4.1",
143
+ "react-native-zcash": "0.4.2",
144
144
  "rimraf": "^3.0.2",
145
145
  "stream-browserify": "^2.0.2",
146
146
  "stream-http": "^3.2.0",
@@ -153,6 +153,6 @@
153
153
  "webpack-dev-server": "^4.11.1"
154
154
  },
155
155
  "peerDependencies": {
156
- "react-native-zcash": "^0.4.1"
156
+ "react-native-zcash": "^0.4.2"
157
157
  }
158
158
  }