edge-currency-accountbased 3.2.5 → 3.2.6
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 +5 -0
- package/android/src/main/assets/edge-currency-accountbased/ethereum.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/filecoin.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/fio.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/polkadot.chunk.js +1 -1
- package/lib/ethereum/networkAdapters/FilfoxAdapter.js +1 -1
- package/lib/filecoin/Filfox.js +1 -0
- package/lib/fio/FioEngine.js +302 -250
- package/lib/polkadot/PolkadotEngine.js +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 3.2.6 (2024-03-20)
|
|
6
|
+
|
|
7
|
+
- changed: Update subscan transfers endpoint url
|
|
8
|
+
- fixed: Correctly use the ETH transaction hash as txid for FEVM transactions to fix duplicate transaction bug on Filecoin FEVM
|
|
9
|
+
|
|
5
10
|
## 3.2.5 (2024-03-11)
|
|
6
11
|
|
|
7
12
|
- fixed: Performance issue with getMaxSpendable caused by recursive calls
|
|
@@ -6,6 +6,6 @@ Invalid return value ${JSON.stringify(e)}
|
|
|
6
6
|
${(0,y.oX)(n)}`),new Error("Invalid return value on transaction send")}logError(e,t){(0,y.HY)(t).includes("rateLimited")?this.ethEngine.log(e,t):this.ethEngine.error(e,t)}serialServers(e){return be(this,null,function*(){var t;const n=((t=this.config.servers)!=null?t:[]).map(s=>()=>be(this,null,function*(){return yield e(s)}));return yield(0,y.QJ)((0,y.Sy)(n))})}parallelServers(e){return be(this,null,function*(){var t;const n=((t=this.config.servers)!=null?t:[]).map(s=>be(this,null,function*(){return yield e(s)}));return yield(0,y.Wp)(n)})}throwError(e,t,n){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 ${n}`)}}}var ye=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class rt extends he{constructor(){super(...arguments),this.broadcast=null,this.fetchTokenBalance=null,this.fetchTokenBalances=null,this.fetchTxs=null,this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchBlockheight=()=>ye(this,null,function*(){try{const e=yield this.fetchPostAmberdataRpc("eth_blockNumber",[]);return{blockHeight:parseInt((0,b.tT)(e).result,16),server:"amberdata"}}catch(e){throw this.logError("checkBlockHeightAmberdata",e),new Error("checkTxsAmberdata (regular tx) response is invalid")}}),this.fetchNonce=()=>ye(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey;try{const t=yield this.fetchPostAmberdataRpc("eth_getTransactionCount",[e,"latest"]);return{newNonce:`${parseInt((0,b.tT)(t).result,16)}`,server:"amberdata"}}catch(t){throw this.logError("checkNonceAmberdata",t),new Error("Amberdata returned invalid JSON")}})}fetchPostAmberdataRpc(e){return ye(this,arguments,function*(t,n=[]){const{amberdataApiKey:s=""}=this.ethEngine.initOptions;return yield this.serialServers(a=>ye(this,null,function*(){const i=`${this.config.servers[0]}`,o={jsonrpc:"2.0",method:t,params:n,id:1},r=yield this.ethEngine.fetchCors(i,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":s,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(o)}),l=ie()(i,{},!0);return r.ok||this.throwError(r,"fetchPostAmberdataRpc",l),yield r.json()}))})}fetchGetAmberdataApi(e){return ye(this,null,function*(){const{amberdataApiKey:t=""}=this.ethEngine.initOptions;return yield this.serialServers(n=>ye(this,null,function*(){const s=`${st._E}${e}`,a=yield this.ethEngine.fetchCors(s,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":t}});return a.ok||this.throwError(a,"fetchGetAmberdata",s),yield a.json()}))})}}var ae=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class ot extends he{constructor(){super(...arguments),this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchTokenBalances=null,this.fetchTxs=null,this.fetchBlockheight=()=>ae(this,null,function*(){try{const{result:e,server:t}=yield this.serialServers(s=>ae(this,null,function*(){const a=yield this.fetchGetBlockbook(s,"/api/v2");return{server:s,result:a}}));return{blockHeight:(0,b.EX)(e).blockbook.bestHeight,server:t}}catch(e){throw this.ethEngine.log("checkBlockHeightBlockbook blockHeight ",e),new Error("checkBlockHeightBlockbook returned invalid JSON")}}),this.broadcast=e=>ae(this,null,function*(){return yield this.parallelServers(t=>ae(this,null,function*(){const n=yield this.fetchGetBlockbook(t,`/api/v2/sendtx/${e.signedTx}`);return{result:this.broadcastResponseHandler(n,t,e),server:"blockbook"}}))}),this.fetchNonce=()=>ae(this,null,function*(){return yield this.checkAddressBlockbook()}),this.fetchTokenBalance=()=>ae(this,null,function*(){return yield this.checkAddressBlockbook()})}checkAddressBlockbook(){return ae(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey.toLowerCase(),t={newNonce:"0",tokenBal:{},server:""},n="/api/v2/address/"+e+"?&details=tokenBalances",{result:s,server:a}=yield this.serialServers(u=>ae(this,null,function*(){const h=yield this.fetchGetBlockbook(u,n);return{server:u,result:h}}));let i;try{i=(0,b.hZ)(s)}catch{throw this.ethEngine.error(`checkTxsBlockbook ${a} error BlockbookAddress ${JSON.stringify(s)}`),new Error(`checkTxsBlockbook ${a} returned invalid JSON for BlockbookAddress`)}const{nonce:o,tokens:r,balance:l}=i;t.newNonce=o,t.tokenBal!=null&&(t.tokenBal[this.ethEngine.currencyInfo.currencyCode]=l),t.server=a;for(const u of r)try{const{symbol:h,balance:f}=(0,b.OM)(u);t.tokenBal[h]=f}catch{throw this.ethEngine.error(`checkTxsBlockbook ${a} BlockbookTokenBalance ${JSON.stringify(u)}`),new Error(`checkTxsBlockbook ${a} returned invalid JSON for BlockbookTokenBalance`)}return t})}fetchGetBlockbook(e,t){return ae(this,null,function*(){const n=e+t;return yield(e.includes("trezor")?yield this.ethEngine.fetchCors(n,{headers:{"User-Agent":"http.agent"}}):yield this.ethEngine.fetchCors(n)).json()})}}var Te=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class it extends he{constructor(){super(...arguments),this.broadcast=null,this.fetchNonce=null,this.fetchTokenBalances=null,this.fetchTxs=null,this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchBlockheight=()=>Te(this,null,function*(){try{const e=yield this.fetchGetBlockchair(`/${this.ethEngine.currencyInfo.pluginId}/stats`,!1);return{blockHeight:parseInt((0,b.cc)(e).data.blocks.toString(),10),server:"blockchair"}}catch(e){throw this.logError(e),new Error("checkBlockHeightBlockchair returned invalid JSON")}}),this.fetchTokenBalance=e=>Te(this,null,function*(){let t;const n=this.ethEngine.walletLocalData.publicKey,s=`/${this.ethEngine.currencyInfo.pluginId}/dashboards/address/${n}?erc_20=true`;try{const i=yield this.fetchGetBlockchair(s,!1);t=(0,b.x4)(i)}catch(i){throw this.logError("checkTokenBalBlockchair",i),new Error("checkTokenBalBlockchair response is invalid")}const a={[this.ethEngine.currencyInfo.currencyCode]:t.data[n].address.balance};for(const i of t.data[n].layer_2.erc_20)try{const o=(0,b.aB)(i),r=o.balance,l=o.token_address,u=o.token_symbol,h=this.ethEngine.getTokenInfo(u);h!=null&&h.contractAddress===l&&(a[u]=r)}catch(o){throw this.ethEngine.error(`checkTokenBalBlockchair tokenData ${(0,y.HY)(o)}
|
|
7
7
|
${JSON.stringify(i)}`),new Error("checkTokenBalBlockchair tokenData is invalid")}return{tokenBal:a,server:"blockchair"}})}fetchGetBlockchair(e,t=!1){return Te(this,null,function*(){const{blockchairApiKey:n}=this.ethEngine.initOptions;return yield this.serialServers(s=>Te(this,null,function*(){const a=t&&n!=null?`&key=${n}`:"",i=`${s}${e}`,o=yield this.ethEngine.fetchCors(`${i}${a}`);return o.ok||this.throwError(o,"fetchGetBlockchair",i),yield o.json()}))})}}var xe=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class at extends he{constructor(){super(...arguments),this.fetchNonce=null,this.fetchBlockheight=null,this.fetchTokenBalance=null,this.fetchTokenBalances=null,this.fetchTxs=null,this.getBaseFeePerGas=null,this.multicastRpc=null,this.broadcast=e=>xe(this,null,function*(){return yield this.parallelServers(t=>xe(this,null,function*(){const n=`v1/${this.ethEngine.currencyInfo.currencyCode.toLowerCase()}/main/txs/push`,s=e.signedTx.replace("0x",""),a=yield this.fetchPostBlockcypher(n,{tx:s},t);return{result:this.broadcastResponseHandler(a,t,e),server:"blockcypher"}}))})}fetchPostBlockcypher(e,t,n){return xe(this,null,function*(){const{blockcypherApiKey:s}=this.ethEngine.initOptions;let a="";s!=null&&s.length>5&&(a="&token="+s);const i=`${n}/${e}${a}`,o=yield this.ethEngine.fetchCors(i,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(t)}),r=ie()(i,{},!0);return o.ok||this.throwError(o,"fetchPostBlockcypher",r.hostname),yield o.json()})}}var lt=k(62177);const ct=d=>{const e=(0,p.XC)(d);if(/0[xX][0-9a-fA-F]+/.test(e))return parseInt(e,16);throw new TypeError("Expected a hex number")},ut=d=>{const e=(0,p.XC)(d);if(/0[xX][0-9a-fA-F]+/.test(e))return(0,c.add)(d,"0");throw new TypeError("Expected a hex number")},Be=(0,p.su)({result:ct}),ht=(0,p.su)({result:ut}),dt=(0,p.su)({safeLow:p.mH,average:p.mH,fast:p.mH,fastest:p.mH}),ft=(0,p.su)({types:(0,p.su)((0,p._2)((0,p.su)({name:p.XC,type:p.XC}))),primaryType:p.XC,domain:p.JC,message:p.JC});var pt=k(86352),ge=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});const Ce=(d,e)=>{const t=Object.keys(e);for(const n of t){const s=e[n];typeof s=="string"&&d(` ${n}: ${(0,c.div)(s,"1000000000",18)} gwei`)}},mt=(d,e,t,n,s)=>({infoFeeProvider:()=>ge(void 0,null,function*(){return yield wt(d,e)}),externalFeeProviders:[gt,vt,yt].map(i=>()=>ge(void 0,null,function*(){return yield i(d,e,t,n,s)}))}),yt=(d,e,t,n,s)=>ge(void 0,null,function*(){const{networkAdapterConfigs:a,supportsEIP1559:i=!1}=s;if(i)return;const o=a.find(w=>w.type==="rpc");if(o==null)return;const r=o.servers,l=(0,y.sD)(r,1)[0],u={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify({method:"eth_gasPrice",params:[],id:1,jsonrpc:"2.0"})},h=yield d(l,u);if(!h.ok){const w=yield h.text();throw new Error(`fetchFeesFromRpc fetch error: ${w}`)}const f=yield h.json(),m=(0,p.Vk)(b.tT)(f);if(m==null)throw new Error(`fetchFeesFromRpc ${l} returned invalid json: ${f}`);const{result:v}=m,g=(0,y.Z8)(v),P={lowFee:(0,c.mul)(g,"1"),standardFeeLow:(0,c.mul)(g,"1.06"),standardFeeHigh:(0,c.mul)(g,"1.12"),highFee:(0,c.mul)(g,"1.25")};return n(`fetchFeesFromRpc: ${e.currencyCode}`),Ce(n,P),P}),gt=(d,e,t,n,s)=>ge(void 0,null,function*(){const{networkAdapterConfigs:a}=s,i=a.find(B=>B.type==="evmscan");if(i==null)return;const o=i.servers,r=Ne(t,e,n);if(o==null||r==null)return;const l=`&apikey=${Array.isArray(r)?(0,y.sD)(r,1)[0]:r!=null?r:""}`,u=`${(0,y.sD)(o,1)[0]}/api?module=gastracker&action=gasoracle${l}`,h=yield d(u);if(!h.ok)throw new Error(`EvmScan fetch error: ${JSON.stringify(h)}`);const f=yield h.json(),m=f.message.includes("NOTOK");if(!(f!=null&&!m))throw new Error(`fetchFeesFromEvmScan unrecognized response message: ${f.message}`);const{SafeGasPrice:g,ProposeGasPrice:P,FastGasPrice:w}=(0,b.TI)(f.result),E=parseFloat(g);let A=parseFloat(P),F=parseFloat(w);A<=E&&(A=E+1),F<=A&&(F=A+1);const K=`${E*Y}`,$=`${(E+A)/2*Y}`,Q=`${F*Y}`,L=`${F*Y/Pe}`,R={lowFee:K,standardFeeLow:$,standardFeeHigh:Q,highFee:L};return n(`fetchFeesFromEvmScan: ${e.currencyCode}`),Ce(n,R),R}),vt=(d,e,t,n,s)=>ge(void 0,null,function*(){const{ethGasStationUrl:a}=s,i=kt(t,e,n);if(a==null||i==null)return;const o=i?`?api-key=${i||""}`:"",l=yield(yield d(`${a}${o}`)).json(),u=dt(l);if(e.currencyCode==="MATIC"&&(u.safeLow*=10,u.average=(l.fast+l.safeLow)/2*10,u.fast=l.standard*10,u.fastest*=10),u.safeLow<=0||u.safeLow>ue)throw new Error("Invalid safeLow value from Gas Station");if(u.average<1||u.average>ue)throw new Error("Invalid average value from Gas Station");if(u.fast<1||u.fast>ue)throw new Error("Invalid fastest value from Gas Station");if(u.fastest<1||u.fastest>ue)throw new Error("Invalid fastest value from Gas Station");u.average<=u.safeLow&&(u.average=u.safeLow+1),u.fast<=u.average&&(u.fast=u.average+1),u.fastest<=u.fast&&(u.fastest=u.fast+1);let h=u.safeLow,f=u.fast,m=((u.fast+u.fastest)*.5+u.fastest)*.5,v=m>u.fastest?m:u.fastest;h=Math.round(h)*pe,f=Math.round(f)*pe,m=Math.round(m)*pe,v=Math.round(v)*pe;const g={lowFee:h.toString(),standardFeeLow:f.toString(),standardFeeHigh:m.toString(),highFee:v.toString()};return n(`fetchFeesFromEvmGasStation: ${e.currencyCode}`),Ce(n,g),g}),wt=(d,e,...t)=>ge(void 0,[d,e,...t],function*(n,{pluginId:s},a={}){const o=yield(yield(0,pt.Vn)(`v1/networkFees/${s}`,void 0,a.timeout,n)).json();return(0,b.b6)(o)}),Ne=(d,e,t)=>{const{evmScanApiKey:n,etherscanApiKey:s,ftmscanApiKey:a,bscscanApiKey:i,polygonscanApiKey:o}=d;if(n!=null)return n;const{currencyCode:r}=e;if(r==="ETH"&&s!=null)return t.warn("INIT OPTION 'etherscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),s;if(r==="FTM"&&a!=null)return t.warn("INIT OPTION 'ftmscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),a;if(r==="BNB"&&i!=null)return t.warn("INIT OPTION 'bscscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),i;if(r==="MATIC"&&o!=null)return t.warn("INIT OPTION 'polygonscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),o},kt=(d,e,t)=>{const{gasStationApiKey:n,ethGasStationApiKey:s}=d;if(n!=null)return n;const{currencyCode:a}=e;if(a==="ETH"&&s!=null)return t.warn("INIT OPTION 'ethGasStationApiKey' IS DEPRECATED. USE 'gasStationApiKey' INSTEAD"),s};var V=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});const Et=50;class Pt extends he{constructor(){super(...arguments),this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchTokenBalances=null,this.fetchBlockheight=()=>V(this,null,function*(){const{result:e,server:t}=yield this.serialServers(s=>V(this,null,function*(){if(!s.includes("etherscan")&&!s.includes("blockscout"))throw new Error(`Unsupported command eth_blockNumber in ${s}`);let a="?module=proxy&action=eth_blockNumber";s.includes("blockscout")&&(a="?module=block&action=eth_block_number");const i=yield this.fetchGetEtherscan(s,a);if(typeof i.result!="string"){const o=`Invalid return value eth_blockNumber in ${s}`;throw this.ethEngine.error(o),new Error(o)}return{server:s,result:i}}));return{blockHeight:Be(e).result,server:t}}),this.broadcast=e=>V(this,null,function*(){return yield this.parallelServers(t=>V(this,null,function*(){const n=`?module=proxy&action=eth_sendRawTransaction&hex=${e.signedTx}`,s=yield this.fetchGetEtherscan(t,n);return{result:this.broadcastResponseHandler(s,t,e),server:"etherscan"}}))}),this.fetchNonce=()=>V(this,null,function*(){const t=`?module=proxy&action=eth_getTransactionCount&address=${this.ethEngine.walletLocalData.publicKey}&tag=latest`,{result:n,server:s}=yield this.serialServers(i=>V(this,null,function*(){if(!i.includes("etherscan")&&!i.includes("blockscout"))throw new Error(`Unsupported command eth_getTransactionCount in ${i}`);const o=yield this.fetchGetEtherscan(i,t);if(typeof o.result!="string"){const r=`Invalid return value eth_getTransactionCount in ${i}`;throw this.ethEngine.error(r),new Error(r)}return{server:i,result:o}}));return{newNonce:ht(n).result,server:s}}),this.fetchTokenBalance=e=>V(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey;let n,s,a,i;try{if(e===this.ethEngine.currencyInfo.currencyCode){const o=`?module=account&action=balance&address=${t}&tag=latest`;n=yield this.serialServers(r=>V(this,null,function*(){const l=yield this.fetchGetEtherscan(r,o);if(typeof l.result!="string"||l.result===""){const u=`Invalid return value eth_getBalance in ${r}`;throw this.ethEngine.error(u),new Error(u)}return(0,lt.jD)(l.result),{server:r,result:l}})),s=n.result,a=n.server}else{const o=this.ethEngine.getTokenInfo(e);if(o!=null&&typeof o.contractAddress=="string"){const l=`?module=account&action=tokenbalance&contractaddress=${o.contractAddress}&address=${t}&tag=latest`,u=yield this.serialServers(h=>V(this,null,function*(){const f=yield this.fetchGetEtherscan(h,l);if(typeof f.result!="string"||f.result===""){const m=`Invalid return value getTokenBalance in ${h}`;throw this.ethEngine.error(m),new Error(m)}return{server:h,result:f}}));s=u.result,a=u.server}}i=(0,b.tT)(s)}catch(o){throw this.ethEngine.error(`checkTokenBalEthscan token ${e} response ${String(n!=null?n:"")} `,o),new Error(`checkTokenBalEthscan invalid ${e} response ${JSON.stringify(s)}`)}if(/^\d+$/.test(i.result)){const o=i.result;return{tokenBal:{[e]:o},server:a}}else throw new Error(`checkTokenBalEthscan returned invalid JSON for ${e}`)}),this.fetchTxs=e=>V(this,null,function*(){var t,n,s;const{startBlock:a,currencyCode:i}=e;let o,r;if(i===this.ethEngine.currencyInfo.currencyCode){const u=yield this.getAllTxsEthscan(a,i,b.EV,{searchRegularTxs:!0}),h=yield this.getAllTxsEthscan(a,i,b.xF,{searchRegularTxs:!1});o=(n=(t=u.server)!=null?t:h.server)!=null?n:"",r=[...u.allTransactions,...h.allTransactions]}else{const u=this.ethEngine.getTokenInfo(i);if(u!=null&&typeof u.contractAddress=="string"){const h=u.contractAddress,f=yield this.getAllTxsEthscan(a,i,b.T0,{contractAddress:h});o=(s=f.server)!=null?s:"",r=f.allTransactions}else return{}}const l={blockHeight:a,edgeTransactions:r};return{tokenTxs:{[i]:l},server:o}})}fetchGetEtherscan(e,t){return V(this,null,function*(){const n=Ne(this.ethEngine.initOptions,this.ethEngine.currencyInfo,this.ethEngine.log);e.indexOf("cors-http")===0&&(e=e.replace(/^cors-http/,"http"));const a=Array.isArray(n)?(0,y.sD)(n,1)[0]:n!=null?n:"",i=a!==""?`&apikey=${a}`:"",o=`${e}/api${t}`,r=yield this.ethEngine.fetchCors(`${o}${i}`);return r.ok||this.throwError(r,"fetchGetEtherscan",o),yield r.json()})}getAllTxsEthscan(e,t,n,s){return V(this,null,function*(){const a=this.ethEngine.walletLocalData.publicKey;let i=1;const o=[];let r;const l=s.contractAddress,u=s.searchRegularTxs;for(;;){const h=Et;let f;t===this.ethEngine.currencyInfo.currencyCode?f=`?action=${u?"txlist":"txlistinternal"}&module=account`:f=`?action=tokentx&contractaddress=${l}&module=account`;const m=`${f}&address=${a}&startblock=${e}&endblock=999999999&sort=asc&page=${i}&offset=${h}`,v=this.config.servers.length===0?{result:{result:[]},server:void 0}:yield this.serialServers(P=>V(this,null,function*(){const w=yield this.fetchGetEtherscan(P,m);if(typeof w.result!="object"||typeof w.result.length!="number"){const E=`Invalid return value getTransactions in ${P}`;throw w.result!=="Max rate limit reached"&&this.ethEngine.error(E),new Error(E)}return{server:P,result:w}}));r=v.server;const g=v.result.result;for(let P=0;P<g.length;P++)try{const w=n(g[P]),E=yield this.processEvmScanTransaction(w,t);o.push(E)}catch(w){throw this.ethEngine.error(`getAllTxsEthscan ${n.name}
|
|
8
8
|
${(0,y.HY)(w)}
|
|
9
|
-
${JSON.stringify(g[P])}`),new Error(`getAllTxsEthscan ${n.name} is invalid`)}if(g.length===0)break;i++}return{allTransactions:o,server:r}})}processEvmScanTransaction(e,t){return V(this,null,function*(){var n;const s=[],a=(n=e.hash)!=null?n:e.transactionHash;if(a==null)throw new Error("Invalid transaction result format");const i=e.from.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),o=t!==this.ethEngine.currencyInfo.currencyCode,r="gasPrice"in e?e.gasPrice:void 0,l=r!=null?(0,c.mul)(r,e.gasUsed):"0";let u="0";if(i&&this.ethEngine.networkInfo.optimismRollupParams!=null){const w=yield this.ethEngine.ethNetwork.multicastRpc("eth_getTransactionReceipt",[a]),E=(0,b.zv)(w.result.result);u=(0,c.add)(u,(0,y.X0)(E.l1Fee))}let h,f,m;i?o?(h=(0,c.sub)("0",e.value),f="0",m=(0,c.add)(l,u)):e.from.toLowerCase()===e.to.toLowerCase()?(h=(0,c.sub)((0,c.sub)("0",l),u),f=(0,c.add)(l,u)):(h=(0,c.sub)((0,c.sub)((0,c.sub)("0",e.value),l),u),f=(0,c.add)(l,u)):(h=e.value,f="0",s.push(this.ethEngine.walletLocalData.publicKey));const v={from:[e.from],to:[e.to],gas:e.gas,gasPrice:r!=null?r:"",gasUsed:e.gasUsed,isFromMakeSpend:!1};let g=parseInt(e.blockNumber);return g<0&&(g=0),{blockHeight:g,currencyCode:t,date:parseInt(e.timeStamp),feeRateUsed:r!=null?Ie(r,e.gas,e.gasUsed):void 0,isSend:h.startsWith("-"),memos:[],nativeAmount:h,networkFee:f,otherParams:v,ourReceiveAddresses:s,parentNetworkFee:m,signedTx:"",txid:a,walletId:this.ethEngine.walletId}})}}var bt=k(77258),me=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class Tt extends he{constructor(){super(...arguments),this.fetchBlockheight=null,this.broadcast=null,this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchNonce=null,this.fetchTokenBalance=null,this.fetchTokenBalances=null,this.fetchTxs=e=>me(this,null,function*(){try{return this.currentScan!=null?yield this.currentScan:(this.currentScan=this.checkTransactions(e),yield this.currentScan)}catch(t){throw console.error(t),t}finally{this.currentScan=void 0}}),this.filfoxMessageToEdgeTransaction=(e,t)=>{const n=[],s=t.transfers.filter(o=>o.type==="miner-fee"||o.type==="burner-fee").reduce((o,r)=>(0,c.add)(o,r.value),"0");let a;return t.from===e?(a=`-${s}`,t.to!==e&&(a=(0,c.sub)(a,t.value))):(a=t.value,n.push(e)),{blockHeight:t.height,currencyCode:this.ethEngine.currencyInfo.currencyCode,date:t.timestamp,isSend:a.startsWith("-"),memos:[],nativeAmount:a,networkFee:s,otherParams:{},ourReceiveAddresses:n,signedTx:"",txid:t.cid,walletId:this.ethEngine.walletId}}}checkTransactions(e){return me(this,null,function*(){const{startBlock:t,currencyCode:n}=e,{publicAddress:s}=yield this.ethEngine.getFreshAddress(),a=r=>{const l=this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode],u=r;l<1&&(u>=1||u>l*1.1)&&(this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode]=u,this.ethEngine.updateOnAddressesChecked())},i=({tx:r,progress:l})=>{r!=null&&(this.ethEngine.addTransaction(n,r),this.onUpdateTransactions(),this.ethEngine.walletLocalData.blockHeight<r.blockHeight&&this.onUpdateBlockHeight(r.blockHeight)),a(l)},o=[this.scanTransactionsFromFilfox(s,i)];return yield Promise.all(o),this.ethEngine.walletLocalData.lastAddressQueryHeight=this.ethEngine.walletLocalData.blockHeight,this.ethEngine.walletLocalDataDirty=!0,a(1),{tokenTxs:{[n]:{blockHeight:t,edgeTransactions:[]}},server:this.config.servers.join(",")}})}makeFilfoxApi(e){return new bt.V7(e,this.ethEngine.fetchCors)}onUpdateBlockHeight(e){this.ethEngine.walletLocalData.blockHeight!==e&&(this.ethEngine.walletLocalData.blockHeight=e,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}onUpdateTransactions(){this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}scanTransactionsFromFilfox(e,t){return me(this,null,function*(){const n=new Set;let a=(yield this.serialServers(l=>me(this,null,function*(){return yield this.makeFilfoxApi(l).getAccountTransfers(e,0,1)}))).totalCount;const i=20;let o=Math.ceil(a/i),r=0;for(let l=o-1;l>=0;l--){const u=yield this.serialServers(f=>me(this,null,function*(){return yield this.makeFilfoxApi(f).getAccountTransfers(e,l,i)}));let h=u.transfers;if(u.totalCount!==a){const f=u.totalCount-a,v=(l+1)*(i/f),g=yield this.serialServers(P=>me(this,null,function*(){return yield this.makeFilfoxApi(P).getAccountTransfers(e,v,f)}));h=[...h,...g.transfers],a=u.totalCount,o=Math.ceil(a/i)}for(let f=h.length-1;f>=0;f--){if(!this.ethEngine.engineOn)return;const m=h[f];let v;if(m.height>=this.ethEngine.walletLocalData.lastAddressQueryHeight&&!n.has(m.message)){m.height>this.ethEngine.walletLocalData.lastAddressQueryHeight&&(this.ethEngine.walletLocalData.lastAddressQueryHeight=m.height,this.ethEngine.walletLocalDataDirty=!0);const P=yield this.serialServers(w=>me(this,null,function*(){return yield this.makeFilfoxApi(w).getMessageDetails(m.message)}));v=this.filfoxMessageToEdgeTransaction(e,P)}const g=a===0?1:++r/a;t({tx:v,progress:g}),n.add(m.message)}}})}}var Ae=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class Ct extends he{constructor(){super(...arguments),this.fetchBlockheight=null,this.broadcast=null,this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchNonce=null,this.fetchTokenBalance=null,this.fetchTokenBalances=null,this.fetchTxs=e=>Ae(this,null,function*(){try{return this.currentScan!=null?yield this.currentScan:(this.currentScan=this.checkTransactions(e),yield this.currentScan)}catch(t){throw console.error(t),t}finally{this.currentScan=void 0}})}checkTransactions(e){return Ae(this,null,function*(){const{startBlock:t,currencyCode:n}=e,s=this.ethEngine.walletLocalData.publicKey,a=[];let i;for(;;){const r=yield this.queryTransactions(s,i);if(a.push(...r.items),i=r.next_page_params,r.items.some(l=>l.block<=t)||i==null)break}const o=a.map(r=>this.processScanTransaction(r,n));return{tokenTxs:{[n]:{blockHeight:t,edgeTransactions:o}},server:this.config.servers.join(",")}})}processScanTransaction(e,t){const n=[],s=e.hash;if(s==null)throw new Error("Invalid transaction result format");const a=e.from.hash.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),i=t!==this.ethEngine.currencyInfo.currencyCode,o=e.gas_price,r=o!=null?(0,c.mul)(o,e.gas_used):"0";let l,u,h;a?i?(l=(0,c.sub)("0",e.value),u="0",h=r):e.from.hash.toLowerCase()===e.to.hash.toLowerCase()?(l=(0,c.sub)("0",r),u=r):(l=(0,c.sub)((0,c.sub)("0",e.value),r),u=r):(l=e.value,u="0",n.push(this.ethEngine.walletLocalData.publicKey));const f={from:[e.from.hash],to:[e.to.hash],gas:e.gas_limit,gasPrice:o!=null?o:"",gasUsed:e.gas_used,isFromMakeSpend:!1};let m=e.block;return m<0&&(m=0),{blockHeight:m,currencyCode:t,date:new Date(e.timestamp).getTime()/1e3,feeRateUsed:o!=null?Ie(o,e.gas_limit,e.gas_used):void 0,isSend:l.startsWith("-"),memos:[],nativeAmount:l,networkFee:u,otherParams:f,ourReceiveAddresses:n,parentNetworkFee:h,signedTx:"",txid:s,walletId:this.ethEngine.walletId}}queryTransactions(e,t){return Ae(this,null,function*(){return yield this.serialServers(n=>Ae(this,null,function*(){const s=`addresses/${e}/transactions`,a=t!=null?new URLSearchParams(t).toString():"",i=`${n}/api/v2/${s}?${a}`,r=yield(yield this.ethEngine.fetchCors(i,{method:"GET",headers:{"content-type":"application/json"}})).text();return St(r)}))})}}const Re=(0,p.su)({hash:p.XC,is_contract:(0,p.Zz)(p.jK),is_verified:(0,p.Zz)(p.jK)}),At=(0,p.su)({timestamp:p.XC,gas_limit:p.XC,block:p.mH,to:Re,from:Re,hash:p.XC,gas_price:p.XC,gas_used:p.XC,value:p.XC}),It=(0,p.su)({block_number:p.mH,fee:p.XC,hash:p.XC,index:p.mH,inserted_at:p.XC,items_count:p.mH,value:p.XC}),St=(0,p.$e)((0,p.su)({items:(0,p._2)(At),next_page_params:(0,p.Zz)(It)}));var $e=k(96519),Ft=k(2593),xt=k(21046),Lt=JSON.parse('[{"constant":true,"inputs":[{"name":"user","type":"address"},{"name":"token","type":"address"}],"name":"tokenBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"users","type":"address[]"},{"name":"tokens","type":"address[]"}],"name":"balances","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"}]'),W=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class Ot extends he{constructor(e,t){super(e,t),this.fetchTxs=null,this.fetchBlockheight=()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo,{result:s,server:a}=yield this.serialServers(o=>W(this,null,function*(){const r=yield this.fetchPostRPC("eth_blockNumber",[],n,o);if(r.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${o} included an error ${JSON.stringify(r.error)}`),new Error("Successful eth_blockNumber response object included an error");return{server:ie()(o).hostname,result:r}}));return{blockHeight:Be(s).result,server:a}}),this.broadcast=n=>W(this,null,function*(){const{chainParams:{chainId:s}}=this.ethEngine.networkInfo;return yield this.parallelServers(a=>W(this,null,function*(){const i="eth_sendRawTransaction",o=[n.signedTx],r=yield this.fetchPostRPC(i,o,s,a),l=ie()(a,{},!0);return{result:this.broadcastResponseHandler(r,l.toString(),n),server:l.hostname}}))}),this.getBaseFeePerGas=this.ethEngine.networkInfo.supportsEIP1559!==!0?null:()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo;return yield this.serialServers(s=>W(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],n,s).then(a=>{if(a.error!=null){const o=`multicast get_baseFeePerGas error response from ${s}: ${JSON.stringify(a.error)}`;throw this.ethEngine.warn(o),new Error(o)}return a.result.baseFeePerGas})}))}),this.multicastRpc=(n,s)=>W(this,null,function*(){const{chainParams:{chainId:a}}=this.ethEngine.networkInfo;return yield this.serialServers(i=>W(this,null,function*(){const o=yield this.fetchPostRPC(n,s,a,i);if(o.error!=null)throw this.ethEngine.error(`Successful ${n} response object from ${i} included an error ${JSON.stringify(o.error)}`),new Error(`Successful ${n} response object included an error: ${o.error.message}`);return{server:ie()(i).hostname,result:o}}))}),this.fetchNonce=()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo,s=this.ethEngine.walletLocalData.publicKey,{result:a,server:i}=yield this.serialServers(r=>W(this,null,function*(){const l=yield this.fetchPostRPC("eth_getTransactionCount",[s,"latest"],n,r);if(l.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${r} included an error ${JSON.stringify(l.error)}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:ie()(r).hostname,result:l}})),o=(0,b.tT)(a);if(/0[xX][0-9a-fA-F]+/.test(o.result))return{newNonce:(0,c.add)("0",o.result),server:i};throw new Error("checkNonceRpc returned invalid JSON")}),this.fetchTokenBalance=n=>W(this,null,function*(){const{chainParams:{chainId:s}}=this.ethEngine.networkInfo;let a,i,o,r;const l=this.ethEngine.walletLocalData.publicKey;try{if(n===this.ethEngine.currencyInfo.currencyCode)i=yield this.serialServers(u=>W(this,null,function*(){const h=yield this.fetchPostRPC("eth_getBalance",[l,"latest"],s,u);if(h.error!=null)throw this.ethEngine.error(`Successful eth_getBalance response object from ${u} included an error ${JSON.stringify(h.error)}`),new Error("Successful eth_getBalance response object included an error");if(!(0,y.vq)(h.result))throw new Error(`eth_getBalance not hex for ${ie()(u).hostname}`);return h.result=(0,y.Z8)(h.result),{server:ie()(u).hostname,result:h}})),o=i.result,r=i.server;else{const u=this.ethEngine.getTokenInfo(n);if(u!=null&&typeof u.contractAddress=="string"){const h={data:`0x70a08231${(0,y.gc)((0,y.KT)(l),32)}`,to:u.contractAddress},f=yield this.ethEngine.ethNetwork.multicastRpc("eth_call",[h,"pending"]),m=f.result.result;if(!m.startsWith("0x"))throw new Error("Invalid return value. Result not hex");f.result.result=(0,y.Z8)(m),o=f.result,r=f.server}}a=(0,b.tT)(o)}catch(u){throw this.ethEngine.error(`checkTokenBalRpc token ${n} response ${String(i!=null?i:"")} `,u),new Error(`checkTokenBalRpc invalid ${n} response ${JSON.stringify(o)}`)}return{tokenBal:{[n]:a.result},server:r}}),this.fetchTokenBalances=this.config.ethBalCheckerContract==null?null:()=>W(this,null,function*(){const{allTokensMap:n,networkInfo:s,walletLocalData:a,currencyInfo:i}=this.ethEngine,{chainParams:o}=s,r={},l=[],u=this.config.ethBalCheckerContract;if(u==null)return r;const h="0x0000000000000000000000000000000000000000",f=[h];for(const v of Object.values(this.ethEngine.allTokensMap)){const g=(0,H.Oj)(v.networkLocation);g!=null&&f.unshift(g.contractAddress)}const m=yield this.serialServers(v=>W(this,null,function*(){const g=new ee.r(v,o.chainId),w=yield new $e.CH(u,Lt,g).balances([a.publicKey],f);if(w.length!==f.length)throw new Error("checkEthBalChecker balances length mismatch");return w})).catch(v=>{throw new Error(`All rpc servers failed eth balance checks: ${String(v)}`)});for(let v=0;v<m.length;v++){const g=f[v].toLowerCase(),P=Ft.O$.from(m[v]);let w;if(g===h){const{currencyCode:E}=i;w=E}else{const E=g.replace("0x","");P.gt(xt._Y)&&l.push(E);const A=n[E];if(A==null){this.logError("checkEthBalChecker",new Error(`checkEthBalChecker missing builtinToken: ${g}`));continue}const{currencyCode:F}=A;w=F}r[w]=P.toString()}return{tokenBal:r,detectedTokenIds:l,server:"ethBalChecker"}}),this.config.servers=this.config.servers.map(n=>{try{return this.addRpcApiKey(n)}catch{}}).filter(n=>n!=null)}addRpcApiKey(e){const n=/{{(.*?)}}/g.exec(e);if(n!=null){const s=n[1],a=(0,b.jq)(s),i=this.ethEngine.initOptions[a];if(typeof i=="string")e=e.replace(n[0],i);else throw i==null?new Error(`Missing ${a} in 'initOptions' for ${this.ethEngine.currencyInfo.pluginId}`):new Error("Incorrect apikey type for RPC")}return e}fetchPostRPC(e,t,n,s){return W(this,null,function*(){const a={id:n,jsonrpc:"2.0",method:e,params:t};s=this.addRpcApiKey(s);const i=yield this.ethEngine.fetchCors(s,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(a)}),o=ie()(s,{},!0);return i.ok||this.throwError(i,"fetchPostRPC",o.hostname),yield i.json()})}}var Bt=Object.defineProperty,Nt=Object.defineProperties,Rt=Object.getOwnPropertyDescriptors,De=Object.getOwnPropertySymbols,$t=Object.prototype.hasOwnProperty,Dt=Object.prototype.propertyIsEnumerable,_e=(d,e,t)=>e in d?Bt(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,He=(d,e)=>{for(var t in e||(e={}))$t.call(e,t)&&_e(d,t,e[t]);if(De)for(var t of De(e))Dt.call(e,t)&&_e(d,t,e[t]);return d},_t=(d,e)=>Nt(d,Rt(e)),J=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});const Ht=2e4,Gt=2e4,Ge=2e4,Mt=2e4,Kt=4*2,jt=2*60,Ie=(d,e,t,n)=>{let s={};return s=_t(He(He({gasPrice:(0,c.div)((0,c.add)(d,"0",10),Y.toString(),Y.toString().length-1,10)},t!==void 0?{gasUsed:t}:{}),n!==void 0?{minerTip:(0,c.div)((0,c.add)(n,"0",10),Y.toString(),Y.toString().length-1,10)}:{}),{gasLimit:e}),s};class Ut{constructor(e){this.multicastRpc=(t,n)=>J(this,null,function*(){const s=this.qualifyNetworkAdapters("multicastRpc").map(i=>()=>J(this,null,function*(){return yield i.multicastRpc(t,n)}));return yield(0,y.QJ)(s)}),this.getBaseFeePerGas=()=>J(this,null,function*(){const t=this.qualifyNetworkAdapters("getBaseFeePerGas").map(n=>()=>J(this,null,function*(){return yield n.getBaseFeePerGas()}));return yield(0,y.QJ)(t)}),this.processEthereumNetworkUpdate=(t,n,s)=>{var a,i,o,r,l;if(n!=null){if(n.blockHeight!=null){this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate blockHeight ${(a=n.server)!=null?a:"no server"} won`);const u=n.blockHeight;this.ethEngine.log(`Got block height ${u}`),typeof u=="number"&&this.ethEngine.walletLocalData.blockHeight!==u&&(this.ethNeeds.blockHeightLastChecked=t,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=u,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}if(n.newNonce!=null&&(this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate nonce ${(i=n.server)!=null?i:"no server"} won`),this.ethNeeds.nonceLastChecked=t,this.ethEngine.otherData.nextNonce=n.newNonce,this.ethEngine.walletLocalDataDirty=!0),n.tokenBal!=null){const u=n.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${(o=n.server)!=null?o:"no server"} won`);for(const h of Object.keys(u))this.ethNeeds.tokenBalLastChecked[h]=t,this.ethEngine.updateBalance(h,u[h]);this.ethEngine.currencyEngineCallbacks.onNewTokens((r=n.detectedTokenIds)!=null?r:[]),this.ethNeeds.tokenBalsLastChecked=t}if(n.tokenTxs!=null){const u=n.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${(l=n.server)!=null?l:"no server"} won`);for(const h of Object.keys(u)){this.ethNeeds.tokenTxsLastChecked[h]=t,this.ethEngine.tokenCheckTransactionsStatus[h]=1;const f=u[h];for(const m of f.edgeTransactions)this.ethEngine.addTransaction(h,m);this.ethEngine.walletLocalData.lastTransactionQueryHeight[h]=s,this.ethEngine.walletLocalData.lastTransactionDate[h]=t}this.ethEngine.updateOnAddressesChecked()}this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}},this.ethEngine=e,this.ethNeeds={blockHeightLastChecked:0,nonceLastChecked:0,tokenBalsLastChecked:0,tokenBalLastChecked:{},tokenTxsLastChecked:{}},this.networkAdapters=this.buildNetworkAdapters(this.ethEngine.networkInfo),this.walletId=e.walletInfo.id}processAlethioTransaction(e,t){let n;const s=[];let a;const i=t!==this.ethEngine.currencyInfo.currencyCode,o=e.attributes.value,r=e.attributes.fee!=null&&e.attributes.fee!==""?e.attributes.fee:"0",l=e.relationships.from.data.id,u=e.relationships.to.data.id;t===this.ethEngine.currencyInfo.currencyCode?a=r:a="0";const h=l.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase();if(h)l.toLowerCase()===u.toLowerCase()?n=(0,c.mul)(a,"-1"):(n=(0,c.sub)("0",o),i||(n=(0,c.sub)(n,a)));else if(u.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase())n=o,s.push(this.ethEngine.walletLocalData.publicKey.toLowerCase());else return null;const f={from:[l],to:[u],gas:"0",gasPrice:"0",gasUsed:"0",isFromMakeSpend:!1};let m=e.attributes.globalRank[0];m<0&&(m=0);let v,g="0";return i&&h?v=a:g=a,{blockHeight:m,currencyCode:t,date:e.attributes.blockCreationTime,isSend:n.startsWith("-"),memos:[],nativeAmount:n,networkFee:g,otherParams:f,ourReceiveAddresses:s,parentNetworkFee:v,signedTx:"",txid:e.relationships.transaction.data.id,walletId:this.walletId}}broadcastTx(e){return J(this,null,function*(){const t=this.qualifyNetworkAdapters("broadcast").map(s=>J(this,null,function*(){return yield s.broadcast(e)})),n=yield(0,y.Wp)(t);return this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} broadcastTx ${n.server} won`),n})}check(e,...t){return J(this,null,function*(){return yield(0,y.QJ)(this.qualifyNetworkAdapters(e).map(n=>()=>J(this,null,function*(){return yield n[e](...t)}))).catch(n=>({}))})}getTokenCurrencyCode(e){const t=this.ethEngine.walletLocalData.publicKey;if(e.toLowerCase()===t.toLowerCase())return this.ethEngine.currencyInfo.currencyCode;for(const n of this.ethEngine.enabledTokens){const s=this.ethEngine.getTokenInfo(n);if(s!=null){const a=s.contractAddress;if(e!=null&&typeof a=="string"&&a.toLowerCase()===e.toLowerCase())return n}}}checkAndUpdate(e,t,n,s){return J(this,null,function*(){const a=Date.now();if(a-e>t)try{const i=yield s();this.processEthereumNetworkUpdate(a,i,n)}catch(i){this.ethEngine.error("checkAndUpdate ",i)}})}needsLoop(){return J(this,null,function*(){for(var e,t;this.ethEngine.engineOn;){const n=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,Ht,n,()=>J(this,null,function*(){return yield this.check("fetchBlockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Gt,n,()=>J(this,null,function*(){return yield this.check("fetchNonce")}));const{currencyCode:s}=this.ethEngine.currencyInfo,a=this.ethEngine.enabledTokens;a.includes(s)||a.push(s);const i=this.networkAdapters.find(o=>o.fetchTokenBalances!=null)!=null;i&&(yield this.checkAndUpdate(this.ethNeeds.tokenBalsLastChecked,Ge,n,()=>J(this,null,function*(){return yield this.check("fetchTokenBalances")})));for(const o of a)i||(yield this.checkAndUpdate((e=this.ethNeeds.tokenBalLastChecked[o])!=null?e:0,Ge,n,()=>J(this,null,function*(){return yield this.check("fetchTokenBalance",o)}))),yield this.checkAndUpdate((t=this.ethNeeds.tokenTxsLastChecked[o])!=null?t:0,Mt,n,()=>J(this,null,function*(){var r,l;const u=(r=this.ethEngine.walletLocalData.lastTransactionQueryHeight[o])!=null?r:0,h=(l=this.ethEngine.walletLocalData.lastTransactionDate[o])!=null?l:0,f={startBlock:Math.max(u-Kt,0),startDate:Math.max(h-jt,0),currencyCode:o};return this.qualifyNetworkAdapters("fetchTxs").length===0?{tokenTxs:{[this.ethEngine.currencyInfo.currencyCode]:{blockHeight:f.startBlock,edgeTransactions:[]}},server:"none"}:yield this.check("fetchTxs",f)}));yield(0,y.HB)(1e3)}})}buildNetworkAdapters(e){const{networkAdapterConfigs:t}=e;return t.map(s=>Xt(s,this.ethEngine))}qualifyNetworkAdapters(...e){return this.networkAdapters.filter(t=>e.every(n=>t[n]!=null))}}const Xt=(d,e)=>{switch(d.type){case"amberdata-rpc":return new rt(e,d);case"blockbook":return new ot(e,d);case"blockchair":return new it(e,d);case"blockcypher":return new at(e,d);case"evmscan":return new Pt(e,d);case"filfox":return new Tt(e,d);case"pulsechain-scan":return new Ct(e,d);case"rpc":return new Ot(e,d)}};var Wt=k(93901),Jt=k(79325),Vt=JSON.parse('[{"inputs":[{"internalType":"uint64","name":"size","type":"uint64"},{"internalType":"uint64","name":"leaf","type":"uint64"}],"name":"constructOutboxProof","outputs":[{"internalType":"bytes32","name":"send","type":"bytes32"},{"internalType":"bytes32","name":"root","type":"bytes32"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"deposit","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"l2CallValue","type":"uint256"},{"internalType":"address","name":"excessFeeRefundAddress","type":"address"},{"internalType":"address","name":"callValueRefundAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"estimateRetryableTicket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"blockNum","type":"uint64"}],"name":"findBatchContainingBlock","outputs":[{"internalType":"uint64","name":"batch","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"contractCreation","type":"bool"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"gasEstimateComponents","outputs":[{"internalType":"uint64","name":"gasEstimate","type":"uint64"},{"internalType":"uint64","name":"gasEstimateForL1","type":"uint64"},{"internalType":"uint256","name":"baseFee","type":"uint256"},{"internalType":"uint256","name":"l1BaseFeeEstimate","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"contractCreation","type":"bool"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"gasEstimateL1Component","outputs":[{"internalType":"uint64","name":"gasEstimateForL1","type":"uint64"},{"internalType":"uint256","name":"baseFee","type":"uint256"},{"internalType":"uint256","name":"l1BaseFeeEstimate","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"blockHash","type":"bytes32"}],"name":"getL1Confirmations","outputs":[{"internalType":"uint64","name":"confirmations","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"batchNum","type":"uint256"},{"internalType":"uint64","name":"index","type":"uint64"}],"name":"legacyLookupMessageBatchProof","outputs":[{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"},{"internalType":"uint256","name":"path","type":"uint256"},{"internalType":"address","name":"l2Sender","type":"address"},{"internalType":"address","name":"l1Dest","type":"address"},{"internalType":"uint256","name":"l2Block","type":"uint256"},{"internalType":"uint256","name":"l1Block","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"calldataForL1","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nitroGenesisBlock","outputs":[{"internalType":"uint256","name":"number","type":"uint256"}],"stateMutability":"pure","type":"function"}]'),Se=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});const Qt="low",Zt="standard",zt="high",Me="custom",Ke="1000000000";function je(d,e,t,n){var s,a,i,o,r,l,u,h,f;let m=!0,v,g;const{customNetworkFee:P}=d!=null?d:{};if(d.networkFeeOption===Me&&P!=null){const{gasLimit:B,gasPrice:O}=P;if((isNaN(B)||B==="")&&(isNaN(O)||O==="")){const N=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw N.name="ErrorBelowMinimumFee",N}if(O!=null&&O!==""){const N=(o=(a=(s=e.default)==null?void 0:s.gasPrice)==null?void 0:a.minGasPrice)!=null?o:(i=n.defaultNetworkFees.default.gasPrice)==null?void 0:i.minGasPrice;if(N!=null){const j=(0,c.mul)(O,Ke);if((0,c.lt)(j,N)||/^\s*$/.test(O)){const fe=new Error(`Gas price ${j} wei below minimum ${N} wei`);throw fe.name="ErrorBelowMinimumFee",fe}}g=(0,c.mul)(O,Ke)}if(B!=null&&B!==""){const N=(h=(l=(r=e.default)==null?void 0:r.gasLimit)==null?void 0:l.minGasLimit)!=null?h:(u=n.defaultNetworkFees.default.gasLimit)==null?void 0:u.minGasLimit;if(N!=null&&(0,c.lt)(B,N)||/^\s*$/.test(B)){const j=new Error(`Gas limit ${B} below minimum ${N}`);throw j.name="ErrorBelowMinimumFee",j}v=B,m=!1}}if(v!=null&&g!=null)return{gasLimit:v,gasPrice:g,useEstimatedGasLimit:!1};let w=e.default,E=e.default;if(typeof((f=d.spendTargets[0])==null?void 0:f.publicAddress)=="string"){const B=(0,y.f0)(d.spendTargets[0].publicAddress);typeof e[B]<"u"&&(E=e[B],m=!1,typeof E.gasPrice<"u"&&(w=E))}let A="regularTransaction";d.currencyCode!=null&&d.currencyCode!==t.currencyCode&&(A="tokenTransaction");let F="standard";typeof d.networkFeeOption=="string"&&d.networkFeeOption!==Me&&(F=d.networkFeeOption);const K=E.gasLimit!=null?E.gasLimit[A]:"21000";let $="";if(d.spendTargets[0].nativeAmount==null)throw new Error("ErrorInvalidNativeAmount");let Q=d.spendTargets[0].nativeAmount;if(A==="tokenTransaction"&&(Q=(0,c.div)(Q,"10")),w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const L=w.gasPrice;switch(F){case Qt:$=L.lowFee;break;case Zt:{if((0,c.gte)(Q,w.gasPrice.standardFeeHighAmount)){$=L.standardFeeHigh;break}if((0,c.lte)(Q,L.standardFeeLowAmount)){if(w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");$=w.gasPrice.standardFeeLow;break}const B=(0,c.sub)(L.standardFeeHighAmount,L.standardFeeLowAmount),O=(0,c.sub)(L.standardFeeHigh,L.standardFeeLow),N=(0,c.sub)(Q,L.standardFeeLowAmount),j=(0,c.mul)(N,O),fe=(0,c.div)(j,B);$=(0,c.add)(L.standardFeeLow,fe);break}case zt:$=w.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:v!=null?v:K,gasPrice:g!=null?g:$,useEstimatedGasLimit:m}}const Yt="1040",Ue=d=>{const{chainParams:e,data:t,dynamicOverhead:n,fixedOverhead:s,gasPriceL1Wei:a,gasLimit:i,nonce:o,to:r,value:l="0x0"}=d,u=D.Gn.custom(e),f=T.nL.fromTxData({nonce:o!=null?(0,y.X0)(o):void 0,gasPrice:(0,y.X0)(a),gasLimit:(0,y.X0)(i),to:r,value:l,data:t===null?void 0:t},{common:u}).raw(),g=Xe(f).map(F=>F==null?"":Jt.YU.stringify(F).toLowerCase()).join().match(/(.{1,2})/g);if(g==null)throw new Error("Invalid rawTx string");let P=0;for(let F=0;F<g.length;F++)g[F]==="00"?P+=4:P+=16;const w=(0,c.add)((0,c.add)(P.toString(),s),Yt),E=(0,c.div)(n,"1000000",18);return(0,c.ceil)((0,c.mul)((0,c.mul)(a,w),E),0)};function Xe(d,e=[]){return d.forEach(t=>{if(t!=null){if(Array.isArray(t))return Xe(t,e);e.push(t)}}),e}function We(d,e,t){return Se(this,null,function*(){if(d<2)return{gasPrice:(0,c.mul)("1",e,16)};{const n=e;let s=(0,c.sub)(n,t);return(0,c.lte)(s,"0")&&(s=(0,c.div)(n,"10",0)),{gasPrice:(0,c.mul)("1",n,16),minerTip:(0,c.mul)("1",s,16)}}})}let Fe={destinationAddress:"",l1Gas:"0",l1GasPrice:"10000000000"};const Je=d=>Se(void 0,null,function*(){const{rpcServers:e,nodeInterfaceAddress:t,destinationAddress:n,txData:s}=d;if(n===Fe.destinationAddress)return{l1Gas:Fe.l1Gas,l1GasPrice:Fe.l1GasPrice};const a=o=>Se(void 0,null,function*(){const r=new Wt.c(o),u=yield new $e.CH(t,Vt,r).callStatic.gasEstimateL1Component(n,!1,s,{blockTag:"latest"});return{l1Gas:u.gasEstimateForL1.toString(),l1GasPrice:u.baseFee.toString()}}),i=yield(0,y.QJ)(e.map(o=>()=>Se(void 0,null,function*(){return yield a(o)})));return Fe={destinationAddress:n,l1Gas:i.l1Gas,l1GasPrice:i.l1GasPrice},i});var le=k(48764).Buffer,qt=Object.defineProperty,en=Object.defineProperties,tn=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertySymbols,nn=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty,rn=Object.prototype.propertyIsEnumerable,on=Reflect.get,Qe=(d,e,t)=>e in d?qt(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,te=(d,e)=>{for(var t in e||(e={}))sn.call(e,t)&&Qe(d,t,e[t]);if(Ve)for(var t of Ve(e))rn.call(e,t)&&Qe(d,t,e[t]);return d},de=(d,e)=>en(d,tn(e)),Le=(d,e,t)=>on(nn(d),t,e),M=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class ke extends re.P{constructor(e,t,n,s,a,i){super(e,t,n,a),this.updateNetworkFeesFromBaseFeePerGas=()=>M(this,null,function*(){var l;const{supportsEIP1559:u=!1}=this.networkInfo;if(!u)return;const h=yield this.ethNetwork.getBaseFeePerGas();if(h==null)return;const f=(0,y.Z8)(h),m=this.networkFees;if(m.default==null||m.default.gasPrice==null)return;const v=this.networkInfo.defaultNetworkFees.default,g=m.default.minPriorityFee||v.minPriorityFee,P=(l=m.default.baseFeeMultiplier)!=null?l:v.baseFeeMultiplier;if(g==null||P==null)return;const w={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const E of Object.keys(P)){const A=(0,c.mul)(P[E],f),F=(0,c.add)(A,g);w[E]=(0,c.div)(F,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),Ce(this.log,w),w}),this.initOptions=s,this.networkInfo=e.networkInfo,this.ethNetwork=new Ut(this),this.networkInfo.optimismRollupParams!=null&&(this.optimismRollupParams=this.networkInfo.optimismRollupParams),this.networkFees=this.networkInfo.defaultNetworkFees,this.fetchCors=(0,y.zR)(e.io);const{infoFeeProvider:o,externalFeeProviders:r}=mt(this.fetchCors,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=o,this.externalFeeProviders=[...r,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:(l,u)=>{if(!(0,y.vq)(l))throw new Error("ErrorInvalidMessage");const h=le.from(u.privateKey,"hex"),f=(0,y.ah)(l),m=S().hashPersonalMessage(f),{v,r:g,s:P}=S().ecsign(m,h);return S().toRpcSig(v,g,P)},signTypedData:(l,u)=>{const h=ft(l),f=le.from(u.privateKey,"hex"),{types:m}=h;function v(L,R=[]){if(R.includes(L)||m[L]===void 0)return R;R.push(L);for(const B of m[L])for(const O of v(B.type,R))R.includes(O)||R.push(O);return R}function g(L){let R=v(L);R=R.filter(O=>O!==L),R=[L].concat(R.sort());let B="";for(const O of R)B+=`${O}(${m[O].map(({name:N,type:j})=>`${j} ${N}`).join(",")})`;return B}function P(L){return S().keccak256(g(L))}function w(L,R){const B=[],O=[];B.push("bytes32"),O.push(P(L));for(const N of m[L]){let j=R[N.name];if(N.type==="string"||N.type==="bytes")B.push("bytes32"),j=S().keccak256(j),O.push(j);else if(m[N.type]!==void 0)B.push("bytes32"),j=S().keccak256(w(N.type,j)),O.push(j);else{if(N.type.lastIndexOf("]")===N.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");B.push(N.type),O.push(j)}}return I().rawEncode(B,O)}function E(L,R){return S().keccak256(w(L,R))}function A(){return S().keccak256(le.concat([le.from("1901","hex"),E("EIP712Domain",h.domain),E(h.primaryType,h.message)]))}const F=S().ecsign(A(),f),{v:K,r:$,s:Q}=F;return S().bufferToHex(le.concat([S().setLengthLeft($,32),S().setLengthLeft(Q,32),S().toBuffer(K)]))},txRpcParamsToSpendInfo:l=>{const u={otherParams:l};l.to!=null&&(u.publicAddress=l.to),l.value!=null?u.nativeAmount=(0,y.Z8)(l.value):u.nativeAmount="0";let h,f,m;return l.gas!=null&&(f=(0,y.Z8)(l.gas),h="custom"),l.gasPrice!=null&&(m=(0,c.div)((0,y.Z8)(l.gasPrice),Y.toString(),18),h="custom"),{currencyCode:this.currencyInfo.currencyCode,spendTargets:[u],memos:[{type:"hex",value:(0,y.KT)(l.data),hidden:!0,memoName:"data"}],networkFeeOption:h,customNetworkFee:{gasLimit:f,gasPrice:m},otherParams:l}}},this.otherMethods={parseWalletConnectV2Payload:l=>M(this,null,function*(){var u,h;try{let f="0",m="0";switch(l.method){case"eth_sendTransaction":case"eth_signTransaction":{const v=(0,p.su)({from:p.XC,to:(0,p.Zz)(p.XC),data:p.XC,gas:(0,p.Zz)(p.XC),gasPrice:(0,p.Zz)(p.XC),value:(0,p.Zz)(p.XC)})(l.params[0]),{gas:g,gasPrice:P,value:w}=v,E=A=>{var F,K;g==null?v.gas=(0,y.X0)(A):A=(0,y.Z8)(g);let $=(K=(F=this.networkFees.default.gasPrice)==null?void 0:F.standardFeeHigh)!=null?K:"0";P==null?v.gasPrice=(0,y.X0)($):$=(0,y.Z8)(P),m=(0,c.mul)(A,$)};w!=null&&(f=(0,y.Z8)(w)),((u=this.networkFees.default.gasLimit)==null?void 0:u.tokenTransaction)==null?this.ethNetwork.multicastRpc("eth_estimateGas",[v]).then(A=>{const F=(0,c.add)(parseInt(A.result.result,16).toString(),"0");E(F)}).catch(A=>{this.warn("Wallet connect call_request failed to get gas limit",A)}):E((h=this.networkFees.default.gasLimit)==null?void 0:h.tokenTransaction);break}}return{nativeAmount:f,networkFee:m,tokenId:null}}catch(f){throw this.warn("Wallet connect call_request ",f),f}}),txRpcParamsToSpendInfo:l=>M(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(l)})}}estimateGasLimit(e){return M(this,null,function*(){var t,n;const{estimateGasParams:s,miningFees:a}=e,i=s[0].data!=null;let o=a.gasLimit;try{const l=(yield this.ethNetwork.multicastRpc("eth_getCode",[s[0].to,"latest"])).result.result!=="0x",u=(h=0)=>M(this,null,function*(){const f=this.networkInfo.defaultNetworkFees.default.gasLimit;try{if(f!=null&&!l&&!i)o=f.regularTransaction;else{const m=yield this.ethNetwork.multicastRpc("eth_estimateGas",s);o=(0,c.add)(parseInt(m.result.result,16).toString(),"0"),l&&(o=(0,c.mul)(o,"2"))}}catch{if(f==null){if(h>5)throw new Error("Unable to estimate gas limit after 5 tries. Please try again later");return yield u(h+1)}if(i)throw new Error("Unable to estimate gas limit. Please try again later");f.tokenTransaction!=null&&(o=f.tokenTransaction)}});if(yield u(),(0,c.lt)(o,(n=(t=this.networkFees.default.gasLimit)==null?void 0:t.minGasLimit)!=null?n:"21000"))throw o=a.gasLimit,new Error("Calculated gasLimit less than minimum")}catch(r){this.error("makeSpend Error determining gas limit ",r)}return o})}setOtherData(e){this.otherData=(0,b.gF)(e)}updateNetworkFees(){return M(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const n={};Object.keys(t).forEach(s=>{const a=s;n[a]=(0,y.Y7)(t[a])}),this.networkFees.default.gasPrice!=null&&(this.networkFees.default.gasPrice=te(te({},this.networkFees.default.gasPrice),n));break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}if(this.networkInfo.supportsEIP1559===!0)try{const e=yield this.ethNetwork.getBaseFeePerGas();if(e==null)return;this.networkFees.default.baseFee=e}catch(e){this.error(`Error fetching base fee: ${JSON.stringify(e)}`)}})}updateOptimismRollupParams(){return M(this,null,function*(){if(this.optimismRollupParams!=null){try{const e={to:this.optimismRollupParams.oracleContractAddress,data:this.optimismRollupParams.gasPricel1BaseFeeMethod},t=yield this.ethNetwork.multicastRpc("eth_call",[e,"latest"]),n=(0,b.tT)(t.result);this.optimismRollupParams=de(te({},this.optimismRollupParams),{gasPriceL1Wei:(0,c.ceil)((0,c.mul)((0,y.Z8)(n.result),this.optimismRollupParams.maxGasPriceL1Multiplier),0)})}catch(e){this.log.warn("Failed to update l1GasPrice",e)}try{const e={to:this.optimismRollupParams.oracleContractAddress,data:this.optimismRollupParams.dynamicOverheadMethod},t=yield this.ethNetwork.multicastRpc("eth_call",[e,"latest"]),n=(0,b.tT)(t.result);this.optimismRollupParams=de(te({},this.optimismRollupParams),{dynamicOverhead:(0,y.Z8)(n.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return M(this,null,function*(){yield Le(ke.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return M(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:we;this.infoFeeProvider().then(n=>M(this,null,function*(){if(this.log.warn("infoFeeProvider:",JSON.stringify(n,null,2)),this.networkFees=(0,y.nu)(this.networkFees,n),this.networkInfo.supportsEIP1559===!0)try{const s=yield this.ethNetwork.getBaseFeePerGas();if(s==null)return;this.networkFees.default.baseFee=s}catch(s){this.error(`Error fetching base fee: ${JSON.stringify(s)}`)}})).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>{this.addToLoop("updateNetworkFees",t).catch(n=>this.warn(`Error setting up updateNetworkFees addToLoop: ${String(n)}`))}),this.addToLoop("updateOptimismRollupParams",tt).catch(()=>{}),this.ethNetwork.needsLoop(),Le(ke.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return M(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return M(this,null,function*(){const{publicKey:e}=this.walletLocalData;return{publicAddress:/[A-F]/.test(e)?e:S().toChecksumAddress(e.replace("0x",""))}})}getMaxSpendable(e){return M(this,null,function*(){e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:t,currencyCode:n}=this.makeSpendCheck(e),s=this.getBalance({currencyCode:e.currencyCode}),i=e.spendTargets[0].publicAddress;if(i==null)throw new Error("makeSpend Missing publicAddress");const{contractAddress:o,data:r}=this.getTxParameterInformation(t,n,this.currencyInfo);if(e.currencyCode===this.currencyInfo.currencyCode){e.spendTargets[0].nativeAmount=s;const l=je(e,this.networkFees,this.currencyInfo,this.networkInfo);if(l.useEstimatedGasLimit){const v=(0,c.mul)(l.gasPrice,l.gasLimit),g=(0,c.sub)(s,v),P=yield this.estimateGasLimit({contractAddress:o,estimateGasParams:[{to:o!=null?o:i,from:this.walletLocalData.publicKey,gas:"0xffffff",value:(0,y.X0)(g),data:r},"latest"],miningFees:l,publicAddress:i});l.gasLimit=(0,c.max)(P,l.gasLimit)}const u=(0,c.mul)(l.gasPrice,l.gasLimit);let h="0";if(this.optimismRollupParams!=null){const v=(0,c.sub)(s,u),g={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:l.gasLimit,to:i,value:(0,y.X0)(v),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};h=Ue(g)}else if(this.networkInfo.arbitrumRollupParams!=null){const v=this.ethNetwork.networkAdapters.filter(w=>w.config.type==="rpc").map(w=>w.config.servers).flat(),{l1Gas:g,l1GasPrice:P}=yield Je({destinationAddress:i,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:v,txData:r!=null?r:"0x"});h=(0,c.mul)((0,c.mul)(g,P),"1.1")}const f=(0,c.add)(u,h),m=(0,c.sub)(s,f);if((0,c.lte)(m,"0"))throw new C.C_;return m}else return e.spendTargets[0].nativeAmount=s,yield this.makeSpend(e),s})}getTxParameterInformation(e,t,n){var s;const{memos:a=[]}=e,{spendTargets:i}=e,o=i[0],{publicAddress:r,nativeAmount:l}=o;let u=((s=a[0])==null?void 0:s.type)==="hex"?a[0].value:void 0;u!=null&&!u.startsWith("0x")&&(u=`0x${u}`);let h;if(t===n.currencyCode)return h=l==null?void 0:(0,y.X0)(l),{data:u,value:h};{let f;if(u!=null)f=r;else{const m=this.getTokenInfo(t);if(m==null||typeof m.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");f=m.contractAddress;const v=I().simpleEncode("transfer(address,uint256):(uint256)",r,(0,y.X0)(l!=null?l:"0"));h="0x0",u="0x"+le.from(v).toString("hex")}return{contractAddress:f,data:u,value:h}}}makeSpend(e){return M(this,null,function*(){var t,n,s;e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:a,currencyCode:i,skipChecks:o}=this.makeSpendCheck(e),{memos:r=[]}=a,{pendingTxs:l=[]}=a;if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const u=a.spendTargets[0],{publicAddress:h}=u;let{nativeAmount:f}=u;if(h==null)throw new Error("makeSpend Missing publicAddress");if(f==null)throw new C.$D;if(!S().isValidAddress(h))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let m;const v=je(a,this.networkFees,this.currencyInfo,this.networkInfo),g=this.networkInfo.supportsEIP1559===!0?2:0,P=yield We(g,v.gasPrice,(t=this.networkFees.default.baseFee)!=null?t:yield this.ethNetwork.getBaseFeePerGas());let w;if(l.length>0){const O=this.walletLocalData.otherData,N=this.walletLocalData.numUnconfirmedSpendTxs>0?O.unconfirmedNextNonce:O.nextNonce;w=(0,c.add)(N,l.length.toString())}const{contractAddress:E,data:A,value:F}=this.getTxParameterInformation(a,i,this.currencyInfo);E==null?m=de(te({from:[this.walletLocalData.publicKey],to:[h]},P),{gas:v.gasLimit,gasUsed:"0",nonceUsed:w,data:A,isFromMakeSpend:!0}):m=de(te({from:[this.walletLocalData.publicKey],to:[E]},P),{gas:v.gasLimit,gasUsed:"0",tokenRecipientAddress:h,nonceUsed:w,data:A,isFromMakeSpend:!0}),v.useEstimatedGasLimit&&(m.gas=yield this.estimateGasLimit({contractAddress:E,estimateGasParams:[{to:E!=null?E:h,from:this.walletLocalData.publicKey,gas:"0xffffff",value:F,data:A},"latest"],miningFees:v,publicAddress:h}));const K=(n=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?n:"0";let $=(0,c.mul)(v.gasPrice,m.gas),Q="0",L=null,R="0";if(this.optimismRollupParams!=null){const O={nonce:m.nonceUsed,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:m.gas,to:m.to[0],value:F,data:m.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};R=Ue(O)}else if(this.networkInfo.arbitrumRollupParams!=null){const O=this.ethNetwork.networkAdapters.filter(fe=>fe.config.type==="rpc").map(fe=>fe.config.servers).flat(),{l1Gas:N,l1GasPrice:j}=yield Je({destinationAddress:h,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:O,txData:A!=null?A:"0x"});R=(0,c.mul)((0,c.mul)(N,j),"1.1"),m.gas=(0,c.add)(m.gas,N)}if(i===this.currencyInfo.currencyCode){if($=(0,c.add)($,R),Q=(0,c.add)($,f),!o&&(0,c.gt)(Q,K))throw new C.C_;f=(0,c.mul)(Q,"-1")}else{if(L=(0,c.add)($,R),!o&&(0,c.gt)(L,K))throw new C.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:L});const O=(s=this.walletLocalData.totalBalances[i])!=null?s:"0";if(!o&&(0,c.gt)(f,O))throw new C.C_;$="0",f=(0,c.mul)(f,"-1")}const B={blockHeight:0,currencyCode:i,date:0,feeRateUsed:Ie(v.gasPrice,m.gas,void 0,P.minerTip),isSend:f.startsWith("-"),memos:r,nativeAmount:f,networkFee:$,otherParams:m,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return L&&(B.parentNetworkFee=L),B})}signMessage(e,t,n){return M(this,null,function*(){const s=(0,b.sh)(this.currencyInfo.pluginId)(t);if((0,b.TP)(n.otherParams).typedData){const i=JSON.parse(e);try{return this.utils.signTypedData(i,s)}catch{return(0,x.signTypedData_v4)(le.from(s.privateKey,"hex"),{data:i})}}return this.utils.signMessage(e,s)})}signTx(e,t){return M(this,null,function*(){const n=(0,b.sh)(this.currencyInfo.pluginId)(t),s=(0,y.Xp)(e),a=(0,y.NC)(s.gas);let i;if(e.currencyCode===this.currencyInfo.currencyCode){const A=(0,c.add)(e.nativeAmount,e.networkFee);i=(0,c.mul)("-1",A,16)}else i=(0,c.mul)("-1",e.nativeAmount,16);(0,c.lt)(i,"0")&&(i="0x00");let o=s.nonceUsed;o==null&&(this.walletLocalData.numUnconfirmedSpendTxs!=null&&(0,c.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)?(o=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0):o=this.otherData.nextNonce);const r=(0,y.NC)(o);let l;if(s.data!=null)l=s.data,e.currencyCode!==this.currencyInfo.currencyCode&&(i="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)l="";else{const A=I().simpleEncode("transfer(address,uint256):(uint256)",s.tokenRecipientAddress,i);l="0x"+le.from(A).toString("hex"),i="0x00"}const{chainParams:u}=this.networkInfo,h=D.Gn.custom(u),f=this.networkInfo.supportsEIP1559===!0?2:0,m=this.networkInfo.supportsEIP1559===!0?{maxFeePerGas:s.gasPrice,maxPriorityFeePerGas:s.minerTip}:{gasPrice:s.gasPrice},v=de(te({nonce:r},m),{gasLimit:a,to:s.to[0],value:i,data:l,type:f}),g=le.from(n.privateKey,"hex"),P=Oe().fromPrivateKey(g);this.warn(`signTx getAddressString ${P.getAddressString()}`);const E=T.nL.fromTxData(v,{common:h}).sign(g);return e.signedTx=(0,y.dg)(E.serialize()),e.txid=(0,y.dg)(E.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=o),this.warn(`signTx
|
|
9
|
+
${JSON.stringify(g[P])}`),new Error(`getAllTxsEthscan ${n.name} is invalid`)}if(g.length===0)break;i++}return{allTransactions:o,server:r}})}processEvmScanTransaction(e,t){return V(this,null,function*(){var n;const s=[],a=(n=e.hash)!=null?n:e.transactionHash;if(a==null)throw new Error("Invalid transaction result format");const i=e.from.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),o=t!==this.ethEngine.currencyInfo.currencyCode,r="gasPrice"in e?e.gasPrice:void 0,l=r!=null?(0,c.mul)(r,e.gasUsed):"0";let u="0";if(i&&this.ethEngine.networkInfo.optimismRollupParams!=null){const w=yield this.ethEngine.ethNetwork.multicastRpc("eth_getTransactionReceipt",[a]),E=(0,b.zv)(w.result.result);u=(0,c.add)(u,(0,y.X0)(E.l1Fee))}let h,f,m;i?o?(h=(0,c.sub)("0",e.value),f="0",m=(0,c.add)(l,u)):e.from.toLowerCase()===e.to.toLowerCase()?(h=(0,c.sub)((0,c.sub)("0",l),u),f=(0,c.add)(l,u)):(h=(0,c.sub)((0,c.sub)((0,c.sub)("0",e.value),l),u),f=(0,c.add)(l,u)):(h=e.value,f="0",s.push(this.ethEngine.walletLocalData.publicKey));const v={from:[e.from],to:[e.to],gas:e.gas,gasPrice:r!=null?r:"",gasUsed:e.gasUsed,isFromMakeSpend:!1};let g=parseInt(e.blockNumber);return g<0&&(g=0),{blockHeight:g,currencyCode:t,date:parseInt(e.timeStamp),feeRateUsed:r!=null?Ie(r,e.gas,e.gasUsed):void 0,isSend:h.startsWith("-"),memos:[],nativeAmount:h,networkFee:f,otherParams:v,ourReceiveAddresses:s,parentNetworkFee:m,signedTx:"",txid:a,walletId:this.ethEngine.walletId}})}}var bt=k(77258),me=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class Tt extends he{constructor(){super(...arguments),this.fetchBlockheight=null,this.broadcast=null,this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchNonce=null,this.fetchTokenBalance=null,this.fetchTokenBalances=null,this.fetchTxs=e=>me(this,null,function*(){try{return this.currentScan!=null?yield this.currentScan:(this.currentScan=this.checkTransactions(e),yield this.currentScan)}catch(t){throw console.error(t),t}finally{this.currentScan=void 0}}),this.filfoxMessageToEdgeTransaction=(e,t)=>{const n=[],s=t.transfers.filter(o=>o.type==="miner-fee"||o.type==="burner-fee").reduce((o,r)=>(0,c.add)(o,r.value),"0");let a;return t.from===e?(a=`-${s}`,t.to!==e&&(a=(0,c.sub)(a,t.value))):(a=t.value,n.push(e)),{blockHeight:t.height,currencyCode:this.ethEngine.currencyInfo.currencyCode,date:t.timestamp,isSend:a.startsWith("-"),memos:[],nativeAmount:a,networkFee:s,otherParams:{},ourReceiveAddresses:n,signedTx:"",txid:t.ethTransactionHash,walletId:this.ethEngine.walletId}}}checkTransactions(e){return me(this,null,function*(){const{startBlock:t,currencyCode:n}=e,{publicAddress:s}=yield this.ethEngine.getFreshAddress(),a=r=>{const l=this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode],u=r;l<1&&(u>=1||u>l*1.1)&&(this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode]=u,this.ethEngine.updateOnAddressesChecked())},i=({tx:r,progress:l})=>{r!=null&&(this.ethEngine.addTransaction(n,r),this.onUpdateTransactions(),this.ethEngine.walletLocalData.blockHeight<r.blockHeight&&this.onUpdateBlockHeight(r.blockHeight)),a(l)},o=[this.scanTransactionsFromFilfox(s,i)];return yield Promise.all(o),this.ethEngine.walletLocalData.lastAddressQueryHeight=this.ethEngine.walletLocalData.blockHeight,this.ethEngine.walletLocalDataDirty=!0,a(1),{tokenTxs:{[n]:{blockHeight:t,edgeTransactions:[]}},server:this.config.servers.join(",")}})}makeFilfoxApi(e){return new bt.V7(e,this.ethEngine.fetchCors)}onUpdateBlockHeight(e){this.ethEngine.walletLocalData.blockHeight!==e&&(this.ethEngine.walletLocalData.blockHeight=e,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}onUpdateTransactions(){this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}scanTransactionsFromFilfox(e,t){return me(this,null,function*(){const n=new Set;let a=(yield this.serialServers(l=>me(this,null,function*(){return yield this.makeFilfoxApi(l).getAccountTransfers(e,0,1)}))).totalCount;const i=20;let o=Math.ceil(a/i),r=0;for(let l=o-1;l>=0;l--){const u=yield this.serialServers(f=>me(this,null,function*(){return yield this.makeFilfoxApi(f).getAccountTransfers(e,l,i)}));let h=u.transfers;if(u.totalCount!==a){const f=u.totalCount-a,v=(l+1)*(i/f),g=yield this.serialServers(P=>me(this,null,function*(){return yield this.makeFilfoxApi(P).getAccountTransfers(e,v,f)}));h=[...h,...g.transfers],a=u.totalCount,o=Math.ceil(a/i)}for(let f=h.length-1;f>=0;f--){if(!this.ethEngine.engineOn)return;const m=h[f];let v;if(m.height>=this.ethEngine.walletLocalData.lastAddressQueryHeight&&!n.has(m.message)){m.height>this.ethEngine.walletLocalData.lastAddressQueryHeight&&(this.ethEngine.walletLocalData.lastAddressQueryHeight=m.height,this.ethEngine.walletLocalDataDirty=!0);const P=yield this.serialServers(w=>me(this,null,function*(){return yield this.makeFilfoxApi(w).getMessageDetails(m.message)}));v=this.filfoxMessageToEdgeTransaction(e,P)}const g=a===0?1:++r/a;t({tx:v,progress:g}),n.add(m.message)}}})}}var Ae=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class Ct extends he{constructor(){super(...arguments),this.fetchBlockheight=null,this.broadcast=null,this.getBaseFeePerGas=null,this.multicastRpc=null,this.fetchNonce=null,this.fetchTokenBalance=null,this.fetchTokenBalances=null,this.fetchTxs=e=>Ae(this,null,function*(){try{return this.currentScan!=null?yield this.currentScan:(this.currentScan=this.checkTransactions(e),yield this.currentScan)}catch(t){throw console.error(t),t}finally{this.currentScan=void 0}})}checkTransactions(e){return Ae(this,null,function*(){const{startBlock:t,currencyCode:n}=e,s=this.ethEngine.walletLocalData.publicKey,a=[];let i;for(;;){const r=yield this.queryTransactions(s,i);if(a.push(...r.items),i=r.next_page_params,r.items.some(l=>l.block<=t)||i==null)break}const o=a.map(r=>this.processScanTransaction(r,n));return{tokenTxs:{[n]:{blockHeight:t,edgeTransactions:o}},server:this.config.servers.join(",")}})}processScanTransaction(e,t){const n=[],s=e.hash;if(s==null)throw new Error("Invalid transaction result format");const a=e.from.hash.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),i=t!==this.ethEngine.currencyInfo.currencyCode,o=e.gas_price,r=o!=null?(0,c.mul)(o,e.gas_used):"0";let l,u,h;a?i?(l=(0,c.sub)("0",e.value),u="0",h=r):e.from.hash.toLowerCase()===e.to.hash.toLowerCase()?(l=(0,c.sub)("0",r),u=r):(l=(0,c.sub)((0,c.sub)("0",e.value),r),u=r):(l=e.value,u="0",n.push(this.ethEngine.walletLocalData.publicKey));const f={from:[e.from.hash],to:[e.to.hash],gas:e.gas_limit,gasPrice:o!=null?o:"",gasUsed:e.gas_used,isFromMakeSpend:!1};let m=e.block;return m<0&&(m=0),{blockHeight:m,currencyCode:t,date:new Date(e.timestamp).getTime()/1e3,feeRateUsed:o!=null?Ie(o,e.gas_limit,e.gas_used):void 0,isSend:l.startsWith("-"),memos:[],nativeAmount:l,networkFee:u,otherParams:f,ourReceiveAddresses:n,parentNetworkFee:h,signedTx:"",txid:s,walletId:this.ethEngine.walletId}}queryTransactions(e,t){return Ae(this,null,function*(){return yield this.serialServers(n=>Ae(this,null,function*(){const s=`addresses/${e}/transactions`,a=t!=null?new URLSearchParams(t).toString():"",i=`${n}/api/v2/${s}?${a}`,r=yield(yield this.ethEngine.fetchCors(i,{method:"GET",headers:{"content-type":"application/json"}})).text();return St(r)}))})}}const Re=(0,p.su)({hash:p.XC,is_contract:(0,p.Zz)(p.jK),is_verified:(0,p.Zz)(p.jK)}),At=(0,p.su)({timestamp:p.XC,gas_limit:p.XC,block:p.mH,to:Re,from:Re,hash:p.XC,gas_price:p.XC,gas_used:p.XC,value:p.XC}),It=(0,p.su)({block_number:p.mH,fee:p.XC,hash:p.XC,index:p.mH,inserted_at:p.XC,items_count:p.mH,value:p.XC}),St=(0,p.$e)((0,p.su)({items:(0,p._2)(At),next_page_params:(0,p.Zz)(It)}));var $e=k(96519),Ft=k(2593),xt=k(21046),Lt=JSON.parse('[{"constant":true,"inputs":[{"name":"user","type":"address"},{"name":"token","type":"address"}],"name":"tokenBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"users","type":"address[]"},{"name":"tokens","type":"address[]"}],"name":"balances","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"}]'),W=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class Ot extends he{constructor(e,t){super(e,t),this.fetchTxs=null,this.fetchBlockheight=()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo,{result:s,server:a}=yield this.serialServers(o=>W(this,null,function*(){const r=yield this.fetchPostRPC("eth_blockNumber",[],n,o);if(r.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${o} included an error ${JSON.stringify(r.error)}`),new Error("Successful eth_blockNumber response object included an error");return{server:ie()(o).hostname,result:r}}));return{blockHeight:Be(s).result,server:a}}),this.broadcast=n=>W(this,null,function*(){const{chainParams:{chainId:s}}=this.ethEngine.networkInfo;return yield this.parallelServers(a=>W(this,null,function*(){const i="eth_sendRawTransaction",o=[n.signedTx],r=yield this.fetchPostRPC(i,o,s,a),l=ie()(a,{},!0);return{result:this.broadcastResponseHandler(r,l.toString(),n),server:l.hostname}}))}),this.getBaseFeePerGas=this.ethEngine.networkInfo.supportsEIP1559!==!0?null:()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo;return yield this.serialServers(s=>W(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],n,s).then(a=>{if(a.error!=null){const o=`multicast get_baseFeePerGas error response from ${s}: ${JSON.stringify(a.error)}`;throw this.ethEngine.warn(o),new Error(o)}return a.result.baseFeePerGas})}))}),this.multicastRpc=(n,s)=>W(this,null,function*(){const{chainParams:{chainId:a}}=this.ethEngine.networkInfo;return yield this.serialServers(i=>W(this,null,function*(){const o=yield this.fetchPostRPC(n,s,a,i);if(o.error!=null)throw this.ethEngine.error(`Successful ${n} response object from ${i} included an error ${JSON.stringify(o.error)}`),new Error(`Successful ${n} response object included an error: ${o.error.message}`);return{server:ie()(i).hostname,result:o}}))}),this.fetchNonce=()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo,s=this.ethEngine.walletLocalData.publicKey,{result:a,server:i}=yield this.serialServers(r=>W(this,null,function*(){const l=yield this.fetchPostRPC("eth_getTransactionCount",[s,"latest"],n,r);if(l.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${r} included an error ${JSON.stringify(l.error)}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:ie()(r).hostname,result:l}})),o=(0,b.tT)(a);if(/0[xX][0-9a-fA-F]+/.test(o.result))return{newNonce:(0,c.add)("0",o.result),server:i};throw new Error("checkNonceRpc returned invalid JSON")}),this.fetchTokenBalance=n=>W(this,null,function*(){const{chainParams:{chainId:s}}=this.ethEngine.networkInfo;let a,i,o,r;const l=this.ethEngine.walletLocalData.publicKey;try{if(n===this.ethEngine.currencyInfo.currencyCode)i=yield this.serialServers(u=>W(this,null,function*(){const h=yield this.fetchPostRPC("eth_getBalance",[l,"latest"],s,u);if(h.error!=null)throw this.ethEngine.error(`Successful eth_getBalance response object from ${u} included an error ${JSON.stringify(h.error)}`),new Error("Successful eth_getBalance response object included an error");if(!(0,y.vq)(h.result))throw new Error(`eth_getBalance not hex for ${ie()(u).hostname}`);return h.result=(0,y.Z8)(h.result),{server:ie()(u).hostname,result:h}})),o=i.result,r=i.server;else{const u=this.ethEngine.getTokenInfo(n);if(u!=null&&typeof u.contractAddress=="string"){const h={data:`0x70a08231${(0,y.gc)((0,y.KT)(l),32)}`,to:u.contractAddress},f=yield this.ethEngine.ethNetwork.multicastRpc("eth_call",[h,"pending"]),m=f.result.result;if(!m.startsWith("0x"))throw new Error("Invalid return value. Result not hex");f.result.result=(0,y.Z8)(m),o=f.result,r=f.server}}a=(0,b.tT)(o)}catch(u){throw this.ethEngine.error(`checkTokenBalRpc token ${n} response ${String(i!=null?i:"")} `,u),new Error(`checkTokenBalRpc invalid ${n} response ${JSON.stringify(o)}`)}return{tokenBal:{[n]:a.result},server:r}}),this.fetchTokenBalances=this.config.ethBalCheckerContract==null?null:()=>W(this,null,function*(){const{allTokensMap:n,networkInfo:s,walletLocalData:a,currencyInfo:i}=this.ethEngine,{chainParams:o}=s,r={},l=[],u=this.config.ethBalCheckerContract;if(u==null)return r;const h="0x0000000000000000000000000000000000000000",f=[h];for(const v of Object.values(this.ethEngine.allTokensMap)){const g=(0,H.Oj)(v.networkLocation);g!=null&&f.unshift(g.contractAddress)}const m=yield this.serialServers(v=>W(this,null,function*(){const g=new ee.r(v,o.chainId),w=yield new $e.CH(u,Lt,g).balances([a.publicKey],f);if(w.length!==f.length)throw new Error("checkEthBalChecker balances length mismatch");return w})).catch(v=>{throw new Error(`All rpc servers failed eth balance checks: ${String(v)}`)});for(let v=0;v<m.length;v++){const g=f[v].toLowerCase(),P=Ft.O$.from(m[v]);let w;if(g===h){const{currencyCode:E}=i;w=E}else{const E=g.replace("0x","");P.gt(xt._Y)&&l.push(E);const A=n[E];if(A==null){this.logError("checkEthBalChecker",new Error(`checkEthBalChecker missing builtinToken: ${g}`));continue}const{currencyCode:F}=A;w=F}r[w]=P.toString()}return{tokenBal:r,detectedTokenIds:l,server:"ethBalChecker"}}),this.config.servers=this.config.servers.map(n=>{try{return this.addRpcApiKey(n)}catch{}}).filter(n=>n!=null)}addRpcApiKey(e){const n=/{{(.*?)}}/g.exec(e);if(n!=null){const s=n[1],a=(0,b.jq)(s),i=this.ethEngine.initOptions[a];if(typeof i=="string")e=e.replace(n[0],i);else throw i==null?new Error(`Missing ${a} in 'initOptions' for ${this.ethEngine.currencyInfo.pluginId}`):new Error("Incorrect apikey type for RPC")}return e}fetchPostRPC(e,t,n,s){return W(this,null,function*(){const a={id:n,jsonrpc:"2.0",method:e,params:t};s=this.addRpcApiKey(s);const i=yield this.ethEngine.fetchCors(s,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(a)}),o=ie()(s,{},!0);return i.ok||this.throwError(i,"fetchPostRPC",o.hostname),yield i.json()})}}var Bt=Object.defineProperty,Nt=Object.defineProperties,Rt=Object.getOwnPropertyDescriptors,De=Object.getOwnPropertySymbols,$t=Object.prototype.hasOwnProperty,Dt=Object.prototype.propertyIsEnumerable,_e=(d,e,t)=>e in d?Bt(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,He=(d,e)=>{for(var t in e||(e={}))$t.call(e,t)&&_e(d,t,e[t]);if(De)for(var t of De(e))Dt.call(e,t)&&_e(d,t,e[t]);return d},_t=(d,e)=>Nt(d,Rt(e)),J=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});const Ht=2e4,Gt=2e4,Ge=2e4,Mt=2e4,Kt=4*2,jt=2*60,Ie=(d,e,t,n)=>{let s={};return s=_t(He(He({gasPrice:(0,c.div)((0,c.add)(d,"0",10),Y.toString(),Y.toString().length-1,10)},t!==void 0?{gasUsed:t}:{}),n!==void 0?{minerTip:(0,c.div)((0,c.add)(n,"0",10),Y.toString(),Y.toString().length-1,10)}:{}),{gasLimit:e}),s};class Ut{constructor(e){this.multicastRpc=(t,n)=>J(this,null,function*(){const s=this.qualifyNetworkAdapters("multicastRpc").map(i=>()=>J(this,null,function*(){return yield i.multicastRpc(t,n)}));return yield(0,y.QJ)(s)}),this.getBaseFeePerGas=()=>J(this,null,function*(){const t=this.qualifyNetworkAdapters("getBaseFeePerGas").map(n=>()=>J(this,null,function*(){return yield n.getBaseFeePerGas()}));return yield(0,y.QJ)(t)}),this.processEthereumNetworkUpdate=(t,n,s)=>{var a,i,o,r,l;if(n!=null){if(n.blockHeight!=null){this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate blockHeight ${(a=n.server)!=null?a:"no server"} won`);const u=n.blockHeight;this.ethEngine.log(`Got block height ${u}`),typeof u=="number"&&this.ethEngine.walletLocalData.blockHeight!==u&&(this.ethNeeds.blockHeightLastChecked=t,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=u,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}if(n.newNonce!=null&&(this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate nonce ${(i=n.server)!=null?i:"no server"} won`),this.ethNeeds.nonceLastChecked=t,this.ethEngine.otherData.nextNonce=n.newNonce,this.ethEngine.walletLocalDataDirty=!0),n.tokenBal!=null){const u=n.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${(o=n.server)!=null?o:"no server"} won`);for(const h of Object.keys(u))this.ethNeeds.tokenBalLastChecked[h]=t,this.ethEngine.updateBalance(h,u[h]);this.ethEngine.currencyEngineCallbacks.onNewTokens((r=n.detectedTokenIds)!=null?r:[]),this.ethNeeds.tokenBalsLastChecked=t}if(n.tokenTxs!=null){const u=n.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${(l=n.server)!=null?l:"no server"} won`);for(const h of Object.keys(u)){this.ethNeeds.tokenTxsLastChecked[h]=t,this.ethEngine.tokenCheckTransactionsStatus[h]=1;const f=u[h];for(const m of f.edgeTransactions)this.ethEngine.addTransaction(h,m);this.ethEngine.walletLocalData.lastTransactionQueryHeight[h]=s,this.ethEngine.walletLocalData.lastTransactionDate[h]=t}this.ethEngine.updateOnAddressesChecked()}this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}},this.ethEngine=e,this.ethNeeds={blockHeightLastChecked:0,nonceLastChecked:0,tokenBalsLastChecked:0,tokenBalLastChecked:{},tokenTxsLastChecked:{}},this.networkAdapters=this.buildNetworkAdapters(this.ethEngine.networkInfo),this.walletId=e.walletInfo.id}processAlethioTransaction(e,t){let n;const s=[];let a;const i=t!==this.ethEngine.currencyInfo.currencyCode,o=e.attributes.value,r=e.attributes.fee!=null&&e.attributes.fee!==""?e.attributes.fee:"0",l=e.relationships.from.data.id,u=e.relationships.to.data.id;t===this.ethEngine.currencyInfo.currencyCode?a=r:a="0";const h=l.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase();if(h)l.toLowerCase()===u.toLowerCase()?n=(0,c.mul)(a,"-1"):(n=(0,c.sub)("0",o),i||(n=(0,c.sub)(n,a)));else if(u.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase())n=o,s.push(this.ethEngine.walletLocalData.publicKey.toLowerCase());else return null;const f={from:[l],to:[u],gas:"0",gasPrice:"0",gasUsed:"0",isFromMakeSpend:!1};let m=e.attributes.globalRank[0];m<0&&(m=0);let v,g="0";return i&&h?v=a:g=a,{blockHeight:m,currencyCode:t,date:e.attributes.blockCreationTime,isSend:n.startsWith("-"),memos:[],nativeAmount:n,networkFee:g,otherParams:f,ourReceiveAddresses:s,parentNetworkFee:v,signedTx:"",txid:e.relationships.transaction.data.id,walletId:this.walletId}}broadcastTx(e){return J(this,null,function*(){const t=this.qualifyNetworkAdapters("broadcast").map(s=>J(this,null,function*(){return yield s.broadcast(e)})),n=yield(0,y.Wp)(t);return this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} broadcastTx ${n.server} won`),n})}check(e,...t){return J(this,null,function*(){return yield(0,y.QJ)(this.qualifyNetworkAdapters(e).map(n=>()=>J(this,null,function*(){return yield n[e](...t)}))).catch(n=>({}))})}getTokenCurrencyCode(e){const t=this.ethEngine.walletLocalData.publicKey;if(e.toLowerCase()===t.toLowerCase())return this.ethEngine.currencyInfo.currencyCode;for(const n of this.ethEngine.enabledTokens){const s=this.ethEngine.getTokenInfo(n);if(s!=null){const a=s.contractAddress;if(e!=null&&typeof a=="string"&&a.toLowerCase()===e.toLowerCase())return n}}}checkAndUpdate(e,t,n,s){return J(this,null,function*(){const a=Date.now();if(a-e>t)try{const i=yield s();this.processEthereumNetworkUpdate(a,i,n)}catch(i){this.ethEngine.error("checkAndUpdate ",i)}})}needsLoop(){return J(this,null,function*(){for(var e,t;this.ethEngine.engineOn;){const n=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,Ht,n,()=>J(this,null,function*(){return yield this.check("fetchBlockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Gt,n,()=>J(this,null,function*(){return yield this.check("fetchNonce")}));const{currencyCode:s}=this.ethEngine.currencyInfo,a=this.ethEngine.enabledTokens;a.includes(s)||a.push(s);const i=this.networkAdapters.find(o=>o.fetchTokenBalances!=null)!=null;i&&(yield this.checkAndUpdate(this.ethNeeds.tokenBalsLastChecked,Ge,n,()=>J(this,null,function*(){return yield this.check("fetchTokenBalances")})));for(const o of a)i||(yield this.checkAndUpdate((e=this.ethNeeds.tokenBalLastChecked[o])!=null?e:0,Ge,n,()=>J(this,null,function*(){return yield this.check("fetchTokenBalance",o)}))),yield this.checkAndUpdate((t=this.ethNeeds.tokenTxsLastChecked[o])!=null?t:0,Mt,n,()=>J(this,null,function*(){var r,l;const u=(r=this.ethEngine.walletLocalData.lastTransactionQueryHeight[o])!=null?r:0,h=(l=this.ethEngine.walletLocalData.lastTransactionDate[o])!=null?l:0,f={startBlock:Math.max(u-Kt,0),startDate:Math.max(h-jt,0),currencyCode:o};return this.qualifyNetworkAdapters("fetchTxs").length===0?{tokenTxs:{[this.ethEngine.currencyInfo.currencyCode]:{blockHeight:f.startBlock,edgeTransactions:[]}},server:"none"}:yield this.check("fetchTxs",f)}));yield(0,y.HB)(1e3)}})}buildNetworkAdapters(e){const{networkAdapterConfigs:t}=e;return t.map(s=>Xt(s,this.ethEngine))}qualifyNetworkAdapters(...e){return this.networkAdapters.filter(t=>e.every(n=>t[n]!=null))}}const Xt=(d,e)=>{switch(d.type){case"amberdata-rpc":return new rt(e,d);case"blockbook":return new ot(e,d);case"blockchair":return new it(e,d);case"blockcypher":return new at(e,d);case"evmscan":return new Pt(e,d);case"filfox":return new Tt(e,d);case"pulsechain-scan":return new Ct(e,d);case"rpc":return new Ot(e,d)}};var Wt=k(93901),Jt=k(79325),Vt=JSON.parse('[{"inputs":[{"internalType":"uint64","name":"size","type":"uint64"},{"internalType":"uint64","name":"leaf","type":"uint64"}],"name":"constructOutboxProof","outputs":[{"internalType":"bytes32","name":"send","type":"bytes32"},{"internalType":"bytes32","name":"root","type":"bytes32"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"deposit","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"l2CallValue","type":"uint256"},{"internalType":"address","name":"excessFeeRefundAddress","type":"address"},{"internalType":"address","name":"callValueRefundAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"estimateRetryableTicket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint64","name":"blockNum","type":"uint64"}],"name":"findBatchContainingBlock","outputs":[{"internalType":"uint64","name":"batch","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"contractCreation","type":"bool"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"gasEstimateComponents","outputs":[{"internalType":"uint64","name":"gasEstimate","type":"uint64"},{"internalType":"uint64","name":"gasEstimateForL1","type":"uint64"},{"internalType":"uint256","name":"baseFee","type":"uint256"},{"internalType":"uint256","name":"l1BaseFeeEstimate","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"contractCreation","type":"bool"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"gasEstimateL1Component","outputs":[{"internalType":"uint64","name":"gasEstimateForL1","type":"uint64"},{"internalType":"uint256","name":"baseFee","type":"uint256"},{"internalType":"uint256","name":"l1BaseFeeEstimate","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"blockHash","type":"bytes32"}],"name":"getL1Confirmations","outputs":[{"internalType":"uint64","name":"confirmations","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"batchNum","type":"uint256"},{"internalType":"uint64","name":"index","type":"uint64"}],"name":"legacyLookupMessageBatchProof","outputs":[{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"},{"internalType":"uint256","name":"path","type":"uint256"},{"internalType":"address","name":"l2Sender","type":"address"},{"internalType":"address","name":"l1Dest","type":"address"},{"internalType":"uint256","name":"l2Block","type":"uint256"},{"internalType":"uint256","name":"l1Block","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"calldataForL1","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nitroGenesisBlock","outputs":[{"internalType":"uint256","name":"number","type":"uint256"}],"stateMutability":"pure","type":"function"}]'),Se=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});const Qt="low",Zt="standard",zt="high",Me="custom",Ke="1000000000";function je(d,e,t,n){var s,a,i,o,r,l,u,h,f;let m=!0,v,g;const{customNetworkFee:P}=d!=null?d:{};if(d.networkFeeOption===Me&&P!=null){const{gasLimit:B,gasPrice:O}=P;if((isNaN(B)||B==="")&&(isNaN(O)||O==="")){const N=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw N.name="ErrorBelowMinimumFee",N}if(O!=null&&O!==""){const N=(o=(a=(s=e.default)==null?void 0:s.gasPrice)==null?void 0:a.minGasPrice)!=null?o:(i=n.defaultNetworkFees.default.gasPrice)==null?void 0:i.minGasPrice;if(N!=null){const j=(0,c.mul)(O,Ke);if((0,c.lt)(j,N)||/^\s*$/.test(O)){const fe=new Error(`Gas price ${j} wei below minimum ${N} wei`);throw fe.name="ErrorBelowMinimumFee",fe}}g=(0,c.mul)(O,Ke)}if(B!=null&&B!==""){const N=(h=(l=(r=e.default)==null?void 0:r.gasLimit)==null?void 0:l.minGasLimit)!=null?h:(u=n.defaultNetworkFees.default.gasLimit)==null?void 0:u.minGasLimit;if(N!=null&&(0,c.lt)(B,N)||/^\s*$/.test(B)){const j=new Error(`Gas limit ${B} below minimum ${N}`);throw j.name="ErrorBelowMinimumFee",j}v=B,m=!1}}if(v!=null&&g!=null)return{gasLimit:v,gasPrice:g,useEstimatedGasLimit:!1};let w=e.default,E=e.default;if(typeof((f=d.spendTargets[0])==null?void 0:f.publicAddress)=="string"){const B=(0,y.f0)(d.spendTargets[0].publicAddress);typeof e[B]<"u"&&(E=e[B],m=!1,typeof E.gasPrice<"u"&&(w=E))}let A="regularTransaction";d.currencyCode!=null&&d.currencyCode!==t.currencyCode&&(A="tokenTransaction");let F="standard";typeof d.networkFeeOption=="string"&&d.networkFeeOption!==Me&&(F=d.networkFeeOption);const K=E.gasLimit!=null?E.gasLimit[A]:"21000";let $="";if(d.spendTargets[0].nativeAmount==null)throw new Error("ErrorInvalidNativeAmount");let Q=d.spendTargets[0].nativeAmount;if(A==="tokenTransaction"&&(Q=(0,c.div)(Q,"10")),w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const L=w.gasPrice;switch(F){case Qt:$=L.lowFee;break;case Zt:{if((0,c.gte)(Q,w.gasPrice.standardFeeHighAmount)){$=L.standardFeeHigh;break}if((0,c.lte)(Q,L.standardFeeLowAmount)){if(w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");$=w.gasPrice.standardFeeLow;break}const B=(0,c.sub)(L.standardFeeHighAmount,L.standardFeeLowAmount),O=(0,c.sub)(L.standardFeeHigh,L.standardFeeLow),N=(0,c.sub)(Q,L.standardFeeLowAmount),j=(0,c.mul)(N,O),fe=(0,c.div)(j,B);$=(0,c.add)(L.standardFeeLow,fe);break}case zt:$=w.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:v!=null?v:K,gasPrice:g!=null?g:$,useEstimatedGasLimit:m}}const Yt="1040",Ue=d=>{const{chainParams:e,data:t,dynamicOverhead:n,fixedOverhead:s,gasPriceL1Wei:a,gasLimit:i,nonce:o,to:r,value:l="0x0"}=d,u=D.Gn.custom(e),f=T.nL.fromTxData({nonce:o!=null?(0,y.X0)(o):void 0,gasPrice:(0,y.X0)(a),gasLimit:(0,y.X0)(i),to:r,value:l,data:t===null?void 0:t},{common:u}).raw(),g=Xe(f).map(F=>F==null?"":Jt.YU.stringify(F).toLowerCase()).join().match(/(.{1,2})/g);if(g==null)throw new Error("Invalid rawTx string");let P=0;for(let F=0;F<g.length;F++)g[F]==="00"?P+=4:P+=16;const w=(0,c.add)((0,c.add)(P.toString(),s),Yt),E=(0,c.div)(n,"1000000",18);return(0,c.ceil)((0,c.mul)((0,c.mul)(a,w),E),0)};function Xe(d,e=[]){return d.forEach(t=>{if(t!=null){if(Array.isArray(t))return Xe(t,e);e.push(t)}}),e}function We(d,e,t){return Se(this,null,function*(){if(d<2)return{gasPrice:(0,c.mul)("1",e,16)};{const n=e;let s=(0,c.sub)(n,t);return(0,c.lte)(s,"0")&&(s=(0,c.div)(n,"10",0)),{gasPrice:(0,c.mul)("1",n,16),minerTip:(0,c.mul)("1",s,16)}}})}let Fe={destinationAddress:"",l1Gas:"0",l1GasPrice:"10000000000"};const Je=d=>Se(void 0,null,function*(){const{rpcServers:e,nodeInterfaceAddress:t,destinationAddress:n,txData:s}=d;if(n===Fe.destinationAddress)return{l1Gas:Fe.l1Gas,l1GasPrice:Fe.l1GasPrice};const a=o=>Se(void 0,null,function*(){const r=new Wt.c(o),u=yield new $e.CH(t,Vt,r).callStatic.gasEstimateL1Component(n,!1,s,{blockTag:"latest"});return{l1Gas:u.gasEstimateForL1.toString(),l1GasPrice:u.baseFee.toString()}}),i=yield(0,y.QJ)(e.map(o=>()=>Se(void 0,null,function*(){return yield a(o)})));return Fe={destinationAddress:n,l1Gas:i.l1Gas,l1GasPrice:i.l1GasPrice},i});var le=k(48764).Buffer,qt=Object.defineProperty,en=Object.defineProperties,tn=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertySymbols,nn=Object.getPrototypeOf,sn=Object.prototype.hasOwnProperty,rn=Object.prototype.propertyIsEnumerable,on=Reflect.get,Qe=(d,e,t)=>e in d?qt(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,te=(d,e)=>{for(var t in e||(e={}))sn.call(e,t)&&Qe(d,t,e[t]);if(Ve)for(var t of Ve(e))rn.call(e,t)&&Qe(d,t,e[t]);return d},de=(d,e)=>en(d,tn(e)),Le=(d,e,t)=>on(nn(d),t,e),M=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class ke extends re.P{constructor(e,t,n,s,a,i){super(e,t,n,a),this.updateNetworkFeesFromBaseFeePerGas=()=>M(this,null,function*(){var l;const{supportsEIP1559:u=!1}=this.networkInfo;if(!u)return;const h=yield this.ethNetwork.getBaseFeePerGas();if(h==null)return;const f=(0,y.Z8)(h),m=this.networkFees;if(m.default==null||m.default.gasPrice==null)return;const v=this.networkInfo.defaultNetworkFees.default,g=m.default.minPriorityFee||v.minPriorityFee,P=(l=m.default.baseFeeMultiplier)!=null?l:v.baseFeeMultiplier;if(g==null||P==null)return;const w={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const E of Object.keys(P)){const A=(0,c.mul)(P[E],f),F=(0,c.add)(A,g);w[E]=(0,c.div)(F,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),Ce(this.log,w),w}),this.initOptions=s,this.networkInfo=e.networkInfo,this.ethNetwork=new Ut(this),this.networkInfo.optimismRollupParams!=null&&(this.optimismRollupParams=this.networkInfo.optimismRollupParams),this.networkFees=this.networkInfo.defaultNetworkFees,this.fetchCors=(0,y.zR)(e.io);const{infoFeeProvider:o,externalFeeProviders:r}=mt(this.fetchCors,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=o,this.externalFeeProviders=[...r,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:(l,u)=>{if(!(0,y.vq)(l))throw new Error("ErrorInvalidMessage");const h=le.from(u.privateKey,"hex"),f=(0,y.ah)(l),m=S().hashPersonalMessage(f),{v,r:g,s:P}=S().ecsign(m,h);return S().toRpcSig(v,g,P)},signTypedData:(l,u)=>{const h=ft(l),f=le.from(u.privateKey,"hex"),{types:m}=h;function v(L,R=[]){if(R.includes(L)||m[L]===void 0)return R;R.push(L);for(const B of m[L])for(const O of v(B.type,R))R.includes(O)||R.push(O);return R}function g(L){let R=v(L);R=R.filter(O=>O!==L),R=[L].concat(R.sort());let B="";for(const O of R)B+=`${O}(${m[O].map(({name:N,type:j})=>`${j} ${N}`).join(",")})`;return B}function P(L){return S().keccak256(g(L))}function w(L,R){const B=[],O=[];B.push("bytes32"),O.push(P(L));for(const N of m[L]){let j=R[N.name];if(N.type==="string"||N.type==="bytes")B.push("bytes32"),j=S().keccak256(j),O.push(j);else if(m[N.type]!==void 0)B.push("bytes32"),j=S().keccak256(w(N.type,j)),O.push(j);else{if(N.type.lastIndexOf("]")===N.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");B.push(N.type),O.push(j)}}return I().rawEncode(B,O)}function E(L,R){return S().keccak256(w(L,R))}function A(){return S().keccak256(le.concat([le.from("1901","hex"),E("EIP712Domain",h.domain),E(h.primaryType,h.message)]))}const F=S().ecsign(A(),f),{v:K,r:$,s:Q}=F;return S().bufferToHex(le.concat([S().setLengthLeft($,32),S().setLengthLeft(Q,32),S().toBuffer(K)]))},txRpcParamsToSpendInfo:l=>{const u={otherParams:l};l.to!=null&&(u.publicAddress=l.to),l.value!=null?u.nativeAmount=(0,y.Z8)(l.value):u.nativeAmount="0";let h,f,m;return l.gas!=null&&(f=(0,y.Z8)(l.gas),h="custom"),l.gasPrice!=null&&(m=(0,c.div)((0,y.Z8)(l.gasPrice),Y.toString(),18),h="custom"),{currencyCode:this.currencyInfo.currencyCode,spendTargets:[u],memos:[{type:"hex",value:(0,y.KT)(l.data),hidden:!0,memoName:"data"}],networkFeeOption:h,customNetworkFee:{gasLimit:f,gasPrice:m},otherParams:l}}},this.otherMethods={parseWalletConnectV2Payload:l=>M(this,null,function*(){var u,h;try{let f="0",m="0";switch(l.method){case"eth_sendTransaction":case"eth_signTransaction":{const v=(0,p.su)({from:p.XC,to:(0,p.Zz)(p.XC),data:p.XC,gas:(0,p.Zz)(p.XC),gasPrice:(0,p.Zz)(p.XC),value:(0,p.Zz)(p.XC)})(l.params[0]),{gas:g,gasPrice:P,value:w}=v,E=A=>{var F,K;g==null?v.gas=(0,y.X0)(A):A=(0,y.Z8)(g);let $=(K=(F=this.networkFees.default.gasPrice)==null?void 0:F.standardFeeHigh)!=null?K:"0";P==null?v.gasPrice=(0,y.X0)($):$=(0,y.Z8)(P),m=(0,c.mul)(A,$)};w!=null&&(f=(0,y.Z8)(w)),((u=this.networkFees.default.gasLimit)==null?void 0:u.tokenTransaction)==null?this.ethNetwork.multicastRpc("eth_estimateGas",[v]).then(A=>{const F=(0,c.add)(parseInt(A.result.result,16).toString(),"0");E(F)}).catch(A=>{this.warn("Wallet connect call_request failed to get gas limit",A)}):E((h=this.networkFees.default.gasLimit)==null?void 0:h.tokenTransaction);break}}return{nativeAmount:f,networkFee:m,tokenId:null}}catch(f){throw this.warn("Wallet connect call_request ",f),f}}),txRpcParamsToSpendInfo:l=>M(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(l)})}}estimateGasLimit(e){return M(this,null,function*(){var t,n;const{estimateGasParams:s,miningFees:a}=e,i=s[0].data!=null;let o=a.gasLimit;try{const l=(yield this.ethNetwork.multicastRpc("eth_getCode",[s[0].to,"latest"])).result.result!=="0x",u=(h=0)=>M(this,null,function*(){const f=this.networkInfo.defaultNetworkFees.default.gasLimit;try{if(f!=null&&!l&&!i)o=f.regularTransaction;else{const m=yield this.ethNetwork.multicastRpc("eth_estimateGas",s);o=(0,c.add)(parseInt(m.result.result,16).toString(),"0"),l&&(o=(0,c.mul)(o,"2"))}}catch{if(f==null){if(h>5)throw new Error("Unable to estimate gas limit after 5 tries. Please try again later");return yield u(h+1)}if(i)throw new Error("Unable to estimate gas limit. Please try again later");f.tokenTransaction!=null&&(o=f.tokenTransaction)}});if(yield u(),(0,c.lt)(o,(n=(t=this.networkFees.default.gasLimit)==null?void 0:t.minGasLimit)!=null?n:"21000"))throw o=a.gasLimit,new Error("Calculated gasLimit less than minimum")}catch(r){this.error("makeSpend Error determining gas limit ",r)}return o})}setOtherData(e){this.otherData=(0,b.gF)(e)}updateNetworkFees(){return M(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const n={};Object.keys(t).forEach(s=>{const a=s;n[a]=(0,y.Y7)(t[a])}),this.networkFees.default.gasPrice!=null&&(this.networkFees.default.gasPrice=te(te({},this.networkFees.default.gasPrice),n));break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}if(this.networkInfo.supportsEIP1559===!0)try{const e=yield this.ethNetwork.getBaseFeePerGas();if(e==null)return;this.networkFees.default.baseFee=e}catch(e){this.error(`Error fetching base fee: ${JSON.stringify(e)}`)}})}updateOptimismRollupParams(){return M(this,null,function*(){if(this.optimismRollupParams!=null){try{const e={to:this.optimismRollupParams.oracleContractAddress,data:this.optimismRollupParams.gasPricel1BaseFeeMethod},t=yield this.ethNetwork.multicastRpc("eth_call",[e,"latest"]),n=(0,b.tT)(t.result);this.optimismRollupParams=de(te({},this.optimismRollupParams),{gasPriceL1Wei:(0,c.ceil)((0,c.mul)((0,y.Z8)(n.result),this.optimismRollupParams.maxGasPriceL1Multiplier),0)})}catch(e){this.log.warn("Failed to update l1GasPrice",e)}try{const e={to:this.optimismRollupParams.oracleContractAddress,data:this.optimismRollupParams.dynamicOverheadMethod},t=yield this.ethNetwork.multicastRpc("eth_call",[e,"latest"]),n=(0,b.tT)(t.result);this.optimismRollupParams=de(te({},this.optimismRollupParams),{dynamicOverhead:(0,y.Z8)(n.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return M(this,null,function*(){yield Le(ke.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return M(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:we;this.infoFeeProvider().then(n=>M(this,null,function*(){if(this.log.warn("infoFeeProvider:",JSON.stringify(n,null,2)),this.networkFees=(0,y.nu)(this.networkFees,n),this.networkInfo.supportsEIP1559===!0)try{const s=yield this.ethNetwork.getBaseFeePerGas();if(s==null)return;this.networkFees.default.baseFee=s}catch(s){this.error(`Error fetching base fee: ${JSON.stringify(s)}`)}})).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>{this.addToLoop("updateNetworkFees",t).catch(n=>this.warn(`Error setting up updateNetworkFees addToLoop: ${String(n)}`))}),this.addToLoop("updateOptimismRollupParams",tt).catch(()=>{}),this.ethNetwork.needsLoop(),Le(ke.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return M(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return M(this,null,function*(){const{publicKey:e}=this.walletLocalData;return{publicAddress:/[A-F]/.test(e)?e:S().toChecksumAddress(e.replace("0x",""))}})}getMaxSpendable(e){return M(this,null,function*(){e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:t,currencyCode:n}=this.makeSpendCheck(e),s=this.getBalance({currencyCode:e.currencyCode}),i=e.spendTargets[0].publicAddress;if(i==null)throw new Error("makeSpend Missing publicAddress");const{contractAddress:o,data:r}=this.getTxParameterInformation(t,n,this.currencyInfo);if(e.currencyCode===this.currencyInfo.currencyCode){e.spendTargets[0].nativeAmount=s;const l=je(e,this.networkFees,this.currencyInfo,this.networkInfo);if(l.useEstimatedGasLimit){const v=(0,c.mul)(l.gasPrice,l.gasLimit),g=(0,c.sub)(s,v),P=yield this.estimateGasLimit({contractAddress:o,estimateGasParams:[{to:o!=null?o:i,from:this.walletLocalData.publicKey,gas:"0xffffff",value:(0,y.X0)(g),data:r},"latest"],miningFees:l,publicAddress:i});l.gasLimit=(0,c.max)(P,l.gasLimit)}const u=(0,c.mul)(l.gasPrice,l.gasLimit);let h="0";if(this.optimismRollupParams!=null){const v=(0,c.sub)(s,u),g={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:l.gasLimit,to:i,value:(0,y.X0)(v),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};h=Ue(g)}else if(this.networkInfo.arbitrumRollupParams!=null){const v=this.ethNetwork.networkAdapters.filter(w=>w.config.type==="rpc").map(w=>w.config.servers).flat(),{l1Gas:g,l1GasPrice:P}=yield Je({destinationAddress:i,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:v,txData:r!=null?r:"0x"});h=(0,c.mul)((0,c.mul)(g,P),"1.1")}const f=(0,c.add)(u,h),m=(0,c.sub)(s,f);if((0,c.lte)(m,"0"))throw new C.C_;return m}else return e.spendTargets[0].nativeAmount=s,yield this.makeSpend(e),s})}getTxParameterInformation(e,t,n){var s;const{memos:a=[]}=e,{spendTargets:i}=e,o=i[0],{publicAddress:r,nativeAmount:l}=o;let u=((s=a[0])==null?void 0:s.type)==="hex"?a[0].value:void 0;u!=null&&!u.startsWith("0x")&&(u=`0x${u}`);let h;if(t===n.currencyCode)return h=l==null?void 0:(0,y.X0)(l),{data:u,value:h};{let f;if(u!=null)f=r;else{const m=this.getTokenInfo(t);if(m==null||typeof m.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");f=m.contractAddress;const v=I().simpleEncode("transfer(address,uint256):(uint256)",r,(0,y.X0)(l!=null?l:"0"));h="0x0",u="0x"+le.from(v).toString("hex")}return{contractAddress:f,data:u,value:h}}}makeSpend(e){return M(this,null,function*(){var t,n,s;e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:a,currencyCode:i,skipChecks:o}=this.makeSpendCheck(e),{memos:r=[]}=a,{pendingTxs:l=[]}=a;if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const u=a.spendTargets[0],{publicAddress:h}=u;let{nativeAmount:f}=u;if(h==null)throw new Error("makeSpend Missing publicAddress");if(f==null)throw new C.$D;if(!S().isValidAddress(h))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let m;const v=je(a,this.networkFees,this.currencyInfo,this.networkInfo),g=this.networkInfo.supportsEIP1559===!0?2:0,P=yield We(g,v.gasPrice,(t=this.networkFees.default.baseFee)!=null?t:yield this.ethNetwork.getBaseFeePerGas());let w;if(l.length>0){const O=this.walletLocalData.otherData,N=this.walletLocalData.numUnconfirmedSpendTxs>0?O.unconfirmedNextNonce:O.nextNonce;w=(0,c.add)(N,l.length.toString())}const{contractAddress:E,data:A,value:F}=this.getTxParameterInformation(a,i,this.currencyInfo);E==null?m=de(te({from:[this.walletLocalData.publicKey],to:[h]},P),{gas:v.gasLimit,gasUsed:"0",nonceUsed:w,data:A,isFromMakeSpend:!0}):m=de(te({from:[this.walletLocalData.publicKey],to:[E]},P),{gas:v.gasLimit,gasUsed:"0",tokenRecipientAddress:h,nonceUsed:w,data:A,isFromMakeSpend:!0}),v.useEstimatedGasLimit&&(m.gas=yield this.estimateGasLimit({contractAddress:E,estimateGasParams:[{to:E!=null?E:h,from:this.walletLocalData.publicKey,gas:"0xffffff",value:F,data:A},"latest"],miningFees:v,publicAddress:h}));const K=(n=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?n:"0";let $=(0,c.mul)(v.gasPrice,m.gas),Q="0",L=null,R="0";if(this.optimismRollupParams!=null){const O={nonce:m.nonceUsed,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:m.gas,to:m.to[0],value:F,data:m.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};R=Ue(O)}else if(this.networkInfo.arbitrumRollupParams!=null){const O=this.ethNetwork.networkAdapters.filter(fe=>fe.config.type==="rpc").map(fe=>fe.config.servers).flat(),{l1Gas:N,l1GasPrice:j}=yield Je({destinationAddress:h,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:O,txData:A!=null?A:"0x"});R=(0,c.mul)((0,c.mul)(N,j),"1.1"),m.gas=(0,c.add)(m.gas,N)}if(i===this.currencyInfo.currencyCode){if($=(0,c.add)($,R),Q=(0,c.add)($,f),!o&&(0,c.gt)(Q,K))throw new C.C_;f=(0,c.mul)(Q,"-1")}else{if(L=(0,c.add)($,R),!o&&(0,c.gt)(L,K))throw new C.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:L});const O=(s=this.walletLocalData.totalBalances[i])!=null?s:"0";if(!o&&(0,c.gt)(f,O))throw new C.C_;$="0",f=(0,c.mul)(f,"-1")}const B={blockHeight:0,currencyCode:i,date:0,feeRateUsed:Ie(v.gasPrice,m.gas,void 0,P.minerTip),isSend:f.startsWith("-"),memos:r,nativeAmount:f,networkFee:$,otherParams:m,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return L&&(B.parentNetworkFee=L),B})}signMessage(e,t,n){return M(this,null,function*(){const s=(0,b.sh)(this.currencyInfo.pluginId)(t);if((0,b.TP)(n.otherParams).typedData){const i=JSON.parse(e);try{return this.utils.signTypedData(i,s)}catch{return(0,x.signTypedData_v4)(le.from(s.privateKey,"hex"),{data:i})}}return this.utils.signMessage(e,s)})}signTx(e,t){return M(this,null,function*(){const n=(0,b.sh)(this.currencyInfo.pluginId)(t),s=(0,y.Xp)(e),a=(0,y.NC)(s.gas);let i;if(e.currencyCode===this.currencyInfo.currencyCode){const A=(0,c.add)(e.nativeAmount,e.networkFee);i=(0,c.mul)("-1",A,16)}else i=(0,c.mul)("-1",e.nativeAmount,16);(0,c.lt)(i,"0")&&(i="0x00");let o=s.nonceUsed;o==null&&(this.walletLocalData.numUnconfirmedSpendTxs!=null&&(0,c.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)?(o=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0):o=this.otherData.nextNonce);const r=(0,y.NC)(o);let l;if(s.data!=null)l=s.data,e.currencyCode!==this.currencyInfo.currencyCode&&(i="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)l="";else{const A=I().simpleEncode("transfer(address,uint256):(uint256)",s.tokenRecipientAddress,i);l="0x"+le.from(A).toString("hex"),i="0x00"}const{chainParams:u}=this.networkInfo,h=D.Gn.custom(u),f=this.networkInfo.supportsEIP1559===!0?2:0,m=this.networkInfo.supportsEIP1559===!0?{maxFeePerGas:s.gasPrice,maxPriorityFeePerGas:s.minerTip}:{gasPrice:s.gasPrice},v=de(te({nonce:r},m),{gasLimit:a,to:s.to[0],value:i,data:l,type:f}),g=le.from(n.privateKey,"hex"),P=Oe().fromPrivateKey(g);this.warn(`signTx getAddressString ${P.getAddressString()}`);const E=T.nL.fromTxData(v,{common:h}).sign(g);return e.signedTx=(0,y.dg)(E.serialize()),e.txid=(0,y.dg)(E.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=o),this.warn(`signTx
|
|
10
10
|
${(0,y.oX)(e)}`),e})}broadcastTx(e){return M(this,null,function*(){return yield this.ethNetwork.broadcastTx(e),this.warn(`SUCCESS broadcastTx
|
|
11
|
-
${(0,y.oX)(e)}`),e})}accelerate(e){return M(this,null,function*(){var t,n,s,a;const{currencyCode:i}=e,o=(0,p.Vk)(b.Al)(e.otherParams);let r=e.txid,l=yield this.findTransaction(i,(0,y.f0)(r));if(l===-1&&((o==null?void 0:o.replacedTxid)!=null&&o.replacedTxid!==""&&(r=o.replacedTxid,l=yield this.findTransaction(i,(0,y.f0)(r))),l===-1))return null;const u=this.transactionList[i][l],h=(0,p.Vk)(b.Al)(u.otherParams);if(u==null||u.blockHeight!==0||h==null||h.nonceUsed==null||!h.isFromMakeSpend)return null;const f=((t=u.spendTargets)!=null?t:[])[0];if(f==null)return null;const m=this.networkInfo.supportsEIP1559===!0?2:0,v=yield We(m,(0,c.mul)(h.gasPrice,"2"),(n=this.networkFees.default.baseFee)!=null?n:yield this.ethNetwork.getBaseFeePerGas()),g=h.gas,P=de(te(te({},h),v),{gas:g,replacedTxid:r});let{nativeAmount:w}=f,E=(0,c.mul)(v.gasPrice,g),A="0",F;const K=(s=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?s:"0";if(i===this.currencyInfo.currencyCode){if(A=(0,c.add)(E,w),(0,c.gt)(A,K))throw new C.C_;w=(0,c.mul)(A,"-1")}else{if(F=E,(0,c.gt)(E,K))throw new C.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:E});const $=(a=this.walletLocalData.totalBalances[i])!=null?a:"0";if((0,c.gt)(w,$))throw new C.C_;E="0",w=(0,c.mul)(w,"-1")}return de(te({},e),{txid:"",feeRateUsed:Ie(v.gasPrice,g,h.gasUsed,v.minerTip),nativeAmount:w,networkFee:E,otherParams:P,parentNetworkFee:F})})}saveTx(e){return M(this,null,function*(){var t;const n=(0,p.Vk)(b.Al)(e.otherParams);if((n==null?void 0:n.replacedTxid)!=null){const{currencyCode:s}=e,a=(0,y.f0)(n.replacedTxid),i=this.findTransaction(s,a);if(i!==-1){const o=this.transactionList[s][i],r=e.metadata,l=de(te({},o),{metadata:r,blockHeight:-1});this.addTransaction(s,l)}}if(e.blockHeight===0){const s=(t=e.otherParams)==null?void 0:t.nonceUsed;s!=null&&(this.otherData.unconfirmedNextNonce=(0,c.add)(s,"1"))}Le(ke.prototype,this,"saveTx").call(this,e)})}}function an(d,e,t,n){return M(this,null,function*(){const{currencyInfo:s,initOptions:a}=d,i=(0,b.VX)(t),o=new ke(d,e,i,(0,b.dp)(a),n,s);return yield o.loadEngine(),o})}var ln=Object.defineProperty,cn=Object.defineProperties,un=Object.getOwnPropertyDescriptors,Ze=Object.getOwnPropertySymbols,hn=Object.prototype.hasOwnProperty,dn=Object.prototype.propertyIsEnumerable,ze=(d,e,t)=>e in d?ln(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,Ye=(d,e)=>{for(var t in e||(e={}))hn.call(e,t)&&ze(d,t,e[t]);if(Ze)for(var t of Ze(e))dn.call(e,t)&&ze(d,t,e[t]);return d},qe=(d,e)=>cn(d,un(e)),q=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class et{constructor(e){const{builtinTokens:t,currencyInfo:n,io:s,networkInfo:a,initOptions:i}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=s,this.networkInfo=a,this.initOptions=i}getDisplayPrivateKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo;return(0,b.sh)(t)(e.keys).privateKey})}getDisplayPublicKey(e){return q(this,null,function*(){const{keys:t}=(0,b.VX)(e);return t.publicKey})}importPrivateKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo,{pluginMnemonicKeyName:n,pluginRegularKeyName:s}=this.networkInfo;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const a=Z.Buffer.from(e.replace(/^0x/,""),"hex");if(!S().isValidPrivate(a))throw new Error("Invalid private key");const i=a.toString("hex"),o={[s]:i};return this.derivePublicKey({type:`wallet:${t}`,id:"fake",keys:o}),o}else{if(!(0,X.validateMnemonic)(e))throw new Error("Invalid input");const a=yield this._mnemonicToHex(e);return{[n]:e,[s]:a}}})}createPrivateKey(e){return q(this,null,function*(){const{pluginMnemonicKeyName:t,pluginRegularKeyName:n}=this.networkInfo;if(e.replace("wallet:","")!==this.currencyInfo.pluginId)throw new Error("InvalidWalletType");const a=Z.Buffer.from(this.io.random(32)),i=(0,X.entropyToMnemonic)(a),o=yield this._mnemonicToHex(i);return{[t]:i,[n]:o}})}derivePublicKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo,{hdPathCoinType:n,pluginMnemonicKeyName:s,pluginRegularKeyName:a}=this.networkInfo;if(e.type!==`wallet:${t}`)throw new Error("Invalid wallet type");let i;if(e.keys[s]!=null){const o=(0,X.mnemonicToSeedSync)(e.keys[s]),r=se().fromMasterSeed(o),l=`m/44'/${n}'/0'/0`,f=r.derivePath(`${l}/0`).getWallet().getPublicKey(),m=S().pubToAddress(f).toString("hex");i=S().toChecksumAddress(m)}else{const o=Z.Buffer.from(e.keys[a].replace(/^0x/,""),"hex");if(!S().isValidPrivate(o))throw new Error("Invalid private key");i=`0x${S().privateToAddress(o).toString("hex")}`}if(!S().isValidAddress(i))throw new Error("Invalid address");return{publicKey:i}})}_mnemonicToHex(e){return q(this,null,function*(){const{hdPathCoinType:t}=this.networkInfo,n=se().fromMasterSeed((0,X.mnemonicToSeedSync)(e)),s=`m/44'/${t}'/0'/0`;return n.derivePath(`${s}/0`).getWallet().getPrivateKeyString().replace(/^0x/,"")})}parseUri(e,t,n){return q(this,null,function*(){var s,a,i,o,r;const l={};this.networkInfo.uriNetworks.forEach(g=>{l[g]=!0});const{parsedUri:u,edgeParsedUri:h}=(0,_.k)(this.currencyInfo,e,l,t||this.currencyInfo.currencyCode,n);let f="";h.publicAddress&&(f=h.publicAddress,h.publicAddress=h.publicAddress.toLowerCase());let[m,v]=f.split("-");if(v||(v=m,m="pay"),f=v,/[A-F]/.test(f)&&!S().isValidChecksumAddress(f))throw new Error("InvalidPublicAddressError");if(f=f.toLowerCase(),!S().isValidAddress(f||""))throw new Error("InvalidPublicAddressError");if(m==="token"||m==="token_info"){if(!u.query)throw new Error("InvalidUriError");const g=(s=u.query.symbol)!=null?s:"SYM";if(g.length<2||g.length>5)throw new Error("Wrong Token symbol");const P=(a=u.query.name)!=null?a:g,w=(i=u.query.decimals)!=null?i:"18";let E="1000000000000000000";const A=parseInt(w);if(A<0||A>18)throw new Error("Wrong number of decimals");E="1"+"0".repeat(A);const F=(o=u.query.type)!=null?o:this.networkInfo.ercTokenStandard;return{token:{currencyCode:g,contractAddress:v.toLowerCase(),currencyName:P,multiplier:E,denominations:[{name:g,multiplier:E}],type:F.toUpperCase()}}}if(m==="pay"){const g=f,P=u.pathname.split("/")[1],w=u.query;switch(P){case"transfer":{const E=(r=w.address)!=null?r:"",A=g!=null?g:"",F=w.uint256!=null?(0,y.EE)(w.uint256):h.nativeAmount,K=this.currencyInfo.metaTokens.find($=>$.contractAddress===A);if(t!=null&&(K==null||K.currencyCode!==t))throw new Error("InternalErrorInvalidCurrencyCode");if(!S().isValidAddress(E))throw new Error("InvalidPublicAddressError");if(!S().isValidAddress(A))throw new Error("InvalidContractAddressError");return qe(Ye({},h),{currencyCode:K==null?void 0:K.currencyCode,nativeAmount:F,publicAddress:E})}case void 0:{const E=g,A=w.value!=null?(0,y.EE)(w.value):h.nativeAmount;return qe(Ye({},h),{publicAddress:E,nativeAmount:A})}default:throw new Error("UnsupportedContractFunction")}}throw new Error("InvalidUriError")})}encodeUri(e){return q(this,arguments,function*(t,n=[]){const{publicAddress:s,nativeAmount:a,currencyCode:i}=t;if(!S().isValidAddress(s))throw new Error("InvalidPublicAddressError");let r;if(typeof a=="string"){const u=(0,y.Qs)(i!=null?i:this.currencyInfo.currencyCode,this.currencyInfo,n);if(u==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,c.div)(a,u.multiplier,18)}return(0,_.Q)(t,this.currencyInfo.pluginId,r)})}getSplittableTypes(e){return Object.keys(G.s).map(t=>`wallet:${t}`)}getTokenId(e){return q(this,null,function*(){(0,H.Rp)(e);const t=(0,H.Oj)(e.networkLocation);if(t==null||!S().isValidAddress(t.contractAddress))throw new Error("ErrorInvalidContractAddress");return t.contractAddress.toLowerCase().replace(/^0x/,"")})}resolveEnsName(e){return q(this,null,function*(){const{networkAdapterConfigs:t}=this.networkInfo,n=t.find(i=>i.type==="rpc");if(n==null)throw new Error("resolveEnsName: No RpcAdapterConfig");const a=n.servers.map(i=>new ee.r(i,1));return yield(0,y.a7)({func:i=>q(this,null,function*(){return yield i.resolveName(e)}),providers:a})})}}function fn(d){return q(this,null,function*(){return new et(d)})}},77258:function(Ee,ne,k){"use strict";k.d(ne,{V7:function(){return y}});var c=k(82448),X=(G,b,D)=>new Promise((T,p)=>{var C=I=>{try{U(D.next(I))}catch(oe){p(oe)}},x=I=>{try{U(D.throw(I))}catch(oe){p(oe)}},U=I=>I.done?T(I.value):Promise.resolve(I.value).then(C,x);U((D=D.apply(G,b)).next())});const Z=(0,c.su)({statusCode:c.mH,message:c.XC,error:c.XC}),z=G=>(0,c.$e)((0,c._C)(Z,G)),S=(0,c.su)({cid:c.XC,from:c.XC,height:c.mH,method:c.XC,nonce:c.mH,receipt:(0,c.su)({exitCode:c.mH}),timestamp:c.mH,to:c.XC,value:c.XC}),ce=(0,c.su)({cid:c.XC,height:c.mH,timestamp:c.mH,from:c.XC,to:c.XC,value:c.XC,gasLimit:c.mH,gasFeeCap:c.XC,gasPremium:c.XC,receipt:(0,c.su)({exitCode:c.mH,return:c.XC,gasUsed:c.mH}),baseFee:c.XC,fee:(0,c.su)({baseFeeBurn:c.XC,overEstimationBurn:c.XC,minerPenalty:c.XC,minerTip:c.XC,refund:c.XC}),transfers:(0,c._2)((0,c.su)({from:c.XC,fromId:c.XC,to:c.XC,toId:c.XC,value:c.XC,type:c.XC}))}),se=(0,c.su)({from:c.XC,height:c.mH,message:c.XC,timestamp:c.mH,to:c.XC,type:c.XC,value:c.XC}),ee=(0,c.su)({messages:(0,c._2)(S),totalCount:c.mH}),H=ce,_=(0,c.su)({transfers:(0,c._2)(se),totalCount:c.mH});class y{constructor(b,D){this.baseUrl=b,this.fetch=D}getAccountMessages(b,D,T=20){return X(this,null,function*(){const p=new URL(`${this.baseUrl}/address/${b}/messages`),C=new URLSearchParams({page:D.toString(),pageSize:T.toString()});p.search=C.toString();const U=yield(yield this.fetch(p.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),I=z(ee)(U);if("error"in I)throw new Error(`Error response code ${I.statusCode}: ${I.message} ${I.error}`);return I})}getAccountTransfers(b,D,T=20){return X(this,null,function*(){const p=new URL(`${this.baseUrl}/address/${b}/transfers`),C=new URLSearchParams({page:D.toString(),pageSize:T.toString()});p.search=C.toString();const U=yield(yield this.fetch(p.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),I=z(_)(U);if("error"in I)throw new Error(`Error response code ${I.statusCode}: ${I.message} ${I.error}`);return I})}getMessageDetails(b){return X(this,null,function*(){const T=yield(yield this.fetch(`${this.baseUrl}/message/${b}`,{method:"GET",headers:{"content-type":"application/json"}})).text(),p=z(H)(T);if("error"in p)throw new Error(`Error response code ${p.statusCode}: ${p.message} ${p.error}`);return p})}}},44613:function(Ee,ne,k){"use strict";k.d(ne,{_E:function(){return _},dh:function(){return D},wI:function(){return y}});var c=k(68142),X=k.n(c),Z=k(79325),z=k(3666),S=k.n(z),ce=k(76714),se=k(48764).Buffer;const{utils:{crypto:{decode58Check:ee,getBase58CheckAddress:H}}}=S(),_=T=>{const p=ee(T);return Z.YU.stringify(p)},y=T=>{const p=Z.YU.parse(T);return H(Array.from(p))},G="a9059cbb",b=T=>{if(!T.startsWith(G))throw new Error("Not a TRC20 data payload");const p=T.replace(G,""),C=`41${p.substring(24,64)}`,x=y(C),U=p.substring(64,128),I=hexToDecimal(U);return[x,I]},D=(T,p)=>{const C=_(T).replace(/^(41)/,"0x"),x=X().simpleEncode("transfer(address,uint256):(uint256)",C,p);return se.from(x).toString("hex")}},89214:function(){},52361:function(){},94616:function(){},88924:function(){},55024:function(){}}]);
|
|
11
|
+
${(0,y.oX)(e)}`),e})}accelerate(e){return M(this,null,function*(){var t,n,s,a;const{currencyCode:i}=e,o=(0,p.Vk)(b.Al)(e.otherParams);let r=e.txid,l=yield this.findTransaction(i,(0,y.f0)(r));if(l===-1&&((o==null?void 0:o.replacedTxid)!=null&&o.replacedTxid!==""&&(r=o.replacedTxid,l=yield this.findTransaction(i,(0,y.f0)(r))),l===-1))return null;const u=this.transactionList[i][l],h=(0,p.Vk)(b.Al)(u.otherParams);if(u==null||u.blockHeight!==0||h==null||h.nonceUsed==null||!h.isFromMakeSpend)return null;const f=((t=u.spendTargets)!=null?t:[])[0];if(f==null)return null;const m=this.networkInfo.supportsEIP1559===!0?2:0,v=yield We(m,(0,c.mul)(h.gasPrice,"2"),(n=this.networkFees.default.baseFee)!=null?n:yield this.ethNetwork.getBaseFeePerGas()),g=h.gas,P=de(te(te({},h),v),{gas:g,replacedTxid:r});let{nativeAmount:w}=f,E=(0,c.mul)(v.gasPrice,g),A="0",F;const K=(s=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?s:"0";if(i===this.currencyInfo.currencyCode){if(A=(0,c.add)(E,w),(0,c.gt)(A,K))throw new C.C_;w=(0,c.mul)(A,"-1")}else{if(F=E,(0,c.gt)(E,K))throw new C.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:E});const $=(a=this.walletLocalData.totalBalances[i])!=null?a:"0";if((0,c.gt)(w,$))throw new C.C_;E="0",w=(0,c.mul)(w,"-1")}return de(te({},e),{txid:"",feeRateUsed:Ie(v.gasPrice,g,h.gasUsed,v.minerTip),nativeAmount:w,networkFee:E,otherParams:P,parentNetworkFee:F})})}saveTx(e){return M(this,null,function*(){var t;const n=(0,p.Vk)(b.Al)(e.otherParams);if((n==null?void 0:n.replacedTxid)!=null){const{currencyCode:s}=e,a=(0,y.f0)(n.replacedTxid),i=this.findTransaction(s,a);if(i!==-1){const o=this.transactionList[s][i],r=e.metadata,l=de(te({},o),{metadata:r,blockHeight:-1});this.addTransaction(s,l)}}if(e.blockHeight===0){const s=(t=e.otherParams)==null?void 0:t.nonceUsed;s!=null&&(this.otherData.unconfirmedNextNonce=(0,c.add)(s,"1"))}Le(ke.prototype,this,"saveTx").call(this,e)})}}function an(d,e,t,n){return M(this,null,function*(){const{currencyInfo:s,initOptions:a}=d,i=(0,b.VX)(t),o=new ke(d,e,i,(0,b.dp)(a),n,s);return yield o.loadEngine(),o})}var ln=Object.defineProperty,cn=Object.defineProperties,un=Object.getOwnPropertyDescriptors,Ze=Object.getOwnPropertySymbols,hn=Object.prototype.hasOwnProperty,dn=Object.prototype.propertyIsEnumerable,ze=(d,e,t)=>e in d?ln(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,Ye=(d,e)=>{for(var t in e||(e={}))hn.call(e,t)&&ze(d,t,e[t]);if(Ze)for(var t of Ze(e))dn.call(e,t)&&ze(d,t,e[t]);return d},qe=(d,e)=>cn(d,un(e)),q=(d,e,t)=>new Promise((n,s)=>{var a=r=>{try{o(t.next(r))}catch(l){s(l)}},i=r=>{try{o(t.throw(r))}catch(l){s(l)}},o=r=>r.done?n(r.value):Promise.resolve(r.value).then(a,i);o((t=t.apply(d,e)).next())});class et{constructor(e){const{builtinTokens:t,currencyInfo:n,io:s,networkInfo:a,initOptions:i}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=s,this.networkInfo=a,this.initOptions=i}getDisplayPrivateKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo;return(0,b.sh)(t)(e.keys).privateKey})}getDisplayPublicKey(e){return q(this,null,function*(){const{keys:t}=(0,b.VX)(e);return t.publicKey})}importPrivateKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo,{pluginMnemonicKeyName:n,pluginRegularKeyName:s}=this.networkInfo;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const a=Z.Buffer.from(e.replace(/^0x/,""),"hex");if(!S().isValidPrivate(a))throw new Error("Invalid private key");const i=a.toString("hex"),o={[s]:i};return this.derivePublicKey({type:`wallet:${t}`,id:"fake",keys:o}),o}else{if(!(0,X.validateMnemonic)(e))throw new Error("Invalid input");const a=yield this._mnemonicToHex(e);return{[n]:e,[s]:a}}})}createPrivateKey(e){return q(this,null,function*(){const{pluginMnemonicKeyName:t,pluginRegularKeyName:n}=this.networkInfo;if(e.replace("wallet:","")!==this.currencyInfo.pluginId)throw new Error("InvalidWalletType");const a=Z.Buffer.from(this.io.random(32)),i=(0,X.entropyToMnemonic)(a),o=yield this._mnemonicToHex(i);return{[t]:i,[n]:o}})}derivePublicKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo,{hdPathCoinType:n,pluginMnemonicKeyName:s,pluginRegularKeyName:a}=this.networkInfo;if(e.type!==`wallet:${t}`)throw new Error("Invalid wallet type");let i;if(e.keys[s]!=null){const o=(0,X.mnemonicToSeedSync)(e.keys[s]),r=se().fromMasterSeed(o),l=`m/44'/${n}'/0'/0`,f=r.derivePath(`${l}/0`).getWallet().getPublicKey(),m=S().pubToAddress(f).toString("hex");i=S().toChecksumAddress(m)}else{const o=Z.Buffer.from(e.keys[a].replace(/^0x/,""),"hex");if(!S().isValidPrivate(o))throw new Error("Invalid private key");i=`0x${S().privateToAddress(o).toString("hex")}`}if(!S().isValidAddress(i))throw new Error("Invalid address");return{publicKey:i}})}_mnemonicToHex(e){return q(this,null,function*(){const{hdPathCoinType:t}=this.networkInfo,n=se().fromMasterSeed((0,X.mnemonicToSeedSync)(e)),s=`m/44'/${t}'/0'/0`;return n.derivePath(`${s}/0`).getWallet().getPrivateKeyString().replace(/^0x/,"")})}parseUri(e,t,n){return q(this,null,function*(){var s,a,i,o,r;const l={};this.networkInfo.uriNetworks.forEach(g=>{l[g]=!0});const{parsedUri:u,edgeParsedUri:h}=(0,_.k)(this.currencyInfo,e,l,t||this.currencyInfo.currencyCode,n);let f="";h.publicAddress&&(f=h.publicAddress,h.publicAddress=h.publicAddress.toLowerCase());let[m,v]=f.split("-");if(v||(v=m,m="pay"),f=v,/[A-F]/.test(f)&&!S().isValidChecksumAddress(f))throw new Error("InvalidPublicAddressError");if(f=f.toLowerCase(),!S().isValidAddress(f||""))throw new Error("InvalidPublicAddressError");if(m==="token"||m==="token_info"){if(!u.query)throw new Error("InvalidUriError");const g=(s=u.query.symbol)!=null?s:"SYM";if(g.length<2||g.length>5)throw new Error("Wrong Token symbol");const P=(a=u.query.name)!=null?a:g,w=(i=u.query.decimals)!=null?i:"18";let E="1000000000000000000";const A=parseInt(w);if(A<0||A>18)throw new Error("Wrong number of decimals");E="1"+"0".repeat(A);const F=(o=u.query.type)!=null?o:this.networkInfo.ercTokenStandard;return{token:{currencyCode:g,contractAddress:v.toLowerCase(),currencyName:P,multiplier:E,denominations:[{name:g,multiplier:E}],type:F.toUpperCase()}}}if(m==="pay"){const g=f,P=u.pathname.split("/")[1],w=u.query;switch(P){case"transfer":{const E=(r=w.address)!=null?r:"",A=g!=null?g:"",F=w.uint256!=null?(0,y.EE)(w.uint256):h.nativeAmount,K=this.currencyInfo.metaTokens.find($=>$.contractAddress===A);if(t!=null&&(K==null||K.currencyCode!==t))throw new Error("InternalErrorInvalidCurrencyCode");if(!S().isValidAddress(E))throw new Error("InvalidPublicAddressError");if(!S().isValidAddress(A))throw new Error("InvalidContractAddressError");return qe(Ye({},h),{currencyCode:K==null?void 0:K.currencyCode,nativeAmount:F,publicAddress:E})}case void 0:{const E=g,A=w.value!=null?(0,y.EE)(w.value):h.nativeAmount;return qe(Ye({},h),{publicAddress:E,nativeAmount:A})}default:throw new Error("UnsupportedContractFunction")}}throw new Error("InvalidUriError")})}encodeUri(e){return q(this,arguments,function*(t,n=[]){const{publicAddress:s,nativeAmount:a,currencyCode:i}=t;if(!S().isValidAddress(s))throw new Error("InvalidPublicAddressError");let r;if(typeof a=="string"){const u=(0,y.Qs)(i!=null?i:this.currencyInfo.currencyCode,this.currencyInfo,n);if(u==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,c.div)(a,u.multiplier,18)}return(0,_.Q)(t,this.currencyInfo.pluginId,r)})}getSplittableTypes(e){return Object.keys(G.s).map(t=>`wallet:${t}`)}getTokenId(e){return q(this,null,function*(){(0,H.Rp)(e);const t=(0,H.Oj)(e.networkLocation);if(t==null||!S().isValidAddress(t.contractAddress))throw new Error("ErrorInvalidContractAddress");return t.contractAddress.toLowerCase().replace(/^0x/,"")})}resolveEnsName(e){return q(this,null,function*(){const{networkAdapterConfigs:t}=this.networkInfo,n=t.find(i=>i.type==="rpc");if(n==null)throw new Error("resolveEnsName: No RpcAdapterConfig");const a=n.servers.map(i=>new ee.r(i,1));return yield(0,y.a7)({func:i=>q(this,null,function*(){return yield i.resolveName(e)}),providers:a})})}}function fn(d){return q(this,null,function*(){return new et(d)})}},77258:function(Ee,ne,k){"use strict";k.d(ne,{V7:function(){return y}});var c=k(82448),X=(G,b,D)=>new Promise((T,p)=>{var C=I=>{try{U(D.next(I))}catch(oe){p(oe)}},x=I=>{try{U(D.throw(I))}catch(oe){p(oe)}},U=I=>I.done?T(I.value):Promise.resolve(I.value).then(C,x);U((D=D.apply(G,b)).next())});const Z=(0,c.su)({statusCode:c.mH,message:c.XC,error:c.XC}),z=G=>(0,c.$e)((0,c._C)(Z,G)),S=(0,c.su)({cid:c.XC,from:c.XC,height:c.mH,method:c.XC,nonce:c.mH,receipt:(0,c.su)({exitCode:c.mH}),timestamp:c.mH,to:c.XC,value:c.XC}),ce=(0,c.su)({cid:c.XC,ethTransactionHash:c.XC,height:c.mH,timestamp:c.mH,from:c.XC,to:c.XC,value:c.XC,gasLimit:c.mH,gasFeeCap:c.XC,gasPremium:c.XC,receipt:(0,c.su)({exitCode:c.mH,return:c.XC,gasUsed:c.mH}),baseFee:c.XC,fee:(0,c.su)({baseFeeBurn:c.XC,overEstimationBurn:c.XC,minerPenalty:c.XC,minerTip:c.XC,refund:c.XC}),transfers:(0,c._2)((0,c.su)({from:c.XC,fromId:c.XC,to:c.XC,toId:c.XC,value:c.XC,type:c.XC}))}),se=(0,c.su)({from:c.XC,height:c.mH,message:c.XC,timestamp:c.mH,to:c.XC,type:c.XC,value:c.XC}),ee=(0,c.su)({messages:(0,c._2)(S),totalCount:c.mH}),H=ce,_=(0,c.su)({transfers:(0,c._2)(se),totalCount:c.mH});class y{constructor(b,D){this.baseUrl=b,this.fetch=D}getAccountMessages(b,D,T=20){return X(this,null,function*(){const p=new URL(`${this.baseUrl}/address/${b}/messages`),C=new URLSearchParams({page:D.toString(),pageSize:T.toString()});p.search=C.toString();const U=yield(yield this.fetch(p.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),I=z(ee)(U);if("error"in I)throw new Error(`Error response code ${I.statusCode}: ${I.message} ${I.error}`);return I})}getAccountTransfers(b,D,T=20){return X(this,null,function*(){const p=new URL(`${this.baseUrl}/address/${b}/transfers`),C=new URLSearchParams({page:D.toString(),pageSize:T.toString()});p.search=C.toString();const U=yield(yield this.fetch(p.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),I=z(_)(U);if("error"in I)throw new Error(`Error response code ${I.statusCode}: ${I.message} ${I.error}`);return I})}getMessageDetails(b){return X(this,null,function*(){const T=yield(yield this.fetch(`${this.baseUrl}/message/${b}`,{method:"GET",headers:{"content-type":"application/json"}})).text(),p=z(H)(T);if("error"in p)throw new Error(`Error response code ${p.statusCode}: ${p.message} ${p.error}`);return p})}}},44613:function(Ee,ne,k){"use strict";k.d(ne,{_E:function(){return _},dh:function(){return D},wI:function(){return y}});var c=k(68142),X=k.n(c),Z=k(79325),z=k(3666),S=k.n(z),ce=k(76714),se=k(48764).Buffer;const{utils:{crypto:{decode58Check:ee,getBase58CheckAddress:H}}}=S(),_=T=>{const p=ee(T);return Z.YU.stringify(p)},y=T=>{const p=Z.YU.parse(T);return H(Array.from(p))},G="a9059cbb",b=T=>{if(!T.startsWith(G))throw new Error("Not a TRC20 data payload");const p=T.replace(G,""),C=`41${p.substring(24,64)}`,x=y(C),U=p.substring(64,128),I=hexToDecimal(U);return[x,I]},D=(T,p)=>{const C=_(T).replace(/^(41)/,"0x"),x=X().simpleEncode("transfer(address,uint256):(uint256)",C,p);return se.from(x).toString("hex")}},89214:function(){},52361:function(){},94616:function(){},88924:function(){},55024:function(){}}]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[8518],{79014:function(Y,_,m){"use strict";m.d(_,{Q:function(){return w},k:function(){return T}});var n=m(77591),v=m.n(n),U=m(24350),x=m(84564),t=m.n(x),B=m(76714),M=Object.defineProperty,D=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,$=(f,h,g)=>h in f?M(f,h,{enumerable:!0,configurable:!0,writable:!0,value:g}):f[h]=g,X=(f,h)=>{for(var g in h||(h={}))F.call(h,g)&&$(f,g,h[g]);if(D)for(var g of D(h))K.call(h,g)&&$(f,g,h[g]);return f};function T(f,h,g,C,b=[]){const d=X({},t()(h,{},!0)),k=h.startsWith(`${f.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!g[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${f.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const S={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},R=d.query.label,G=d.query.message,V=d.query.category;(R!=null||G!=null||V!=null||k)&&(S.metadata={},S.metadata.name=R,S.metadata.notes=G,S.metadata.category=V,S.metadata.gateway=k!=null?k:!1);const N=d.query.amount;if(N!=null&&typeof N=="string"){C==null&&(C=f.currencyCode);const j=(0,B.Qs)(C!=null?C:"",f,b);if(j==null)throw new Error("InternalErrorInvalidCurrencyCode");let W=(0,n.mul)(N,j.multiplier);W=(0,n.toFixed)(W,0,0),S.nativeAmount=W,S.currencyCode=C}return{edgeParsedUri:S,parsedUri:d}}function w(f,h,g){if(f.publicAddress==null)throw new Error("InvalidPublicAddressError");if(g==null&&f.label==null&&f.message==null)return f.publicAddress;{let C="";g!=null&&(C+="amount="+g+"&"),(f.label!=null||f.message!=null)&&(typeof f.label=="string"&&(C+="label="+f.label+"&"),typeof f.message=="string"&&(C+="message="+f.message+"&")),C=C.substr(0,C.length-1);const b={scheme:h,path:f.publicAddress,query:C};return(0,U.qC)(b)}}},59677:function(Y,_,m){"use strict";m.r(_),m.d(_,{FilecoinTools:function(){return te},makeCurrencyEngine:function(){return Ee},makeCurrencyTools:function(){return Ae}});var n=m(23145),v=m(77591),U=m(37786),x=m(2153),t=m(82448),B=m(21964),M=m.n(B),D=m(79325),F=m(79014),K=m(76714),$=m(62177);const X=(0,t.su)({}),T=(0,t.su)({sigJson:(0,t.Zz)((0,t.su)({Data:t.XC,Type:(0,t.Wf)(1,3)})),txJson:(0,t.su)({To:t.XC,From:t.XC,Nonce:t.mH,Value:t.XC,GasLimit:t.mH,GasFeeCap:t.XC,GasPremium:t.XC,Method:t.mH,Params:t.XC})}),w=(0,t.su)({address:t.XC,publicKey:t.XC}),f=(0,$.jd)(w),h=u=>{const e=(0,t.su)({[`${u}Mnemonic`]:t.XC,[`${u}Key`]:t.XC});return(0,t.W1)(s=>{const a=e(s);return{mnemonic:a[`${u}Mnemonic`],privateKey:a[`${u}Key`]}},s=>({[`${u}Mnemonic`]:s.mnemonic,[`${u}Key`]:s.privateKey}))};var g=m(94935),C=m(84650),b=m(72681),d=m(77258),k=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});const Z=u=>(0,t.su)({result:u}),S=(0,t.su)({code:t.mH,message:t.XC}),R=u=>(0,t.$e)((0,t._C)(S,Z(u))),G=(0,t.su)({height:t.mH,block_time:t.mH,cid:t.XC,from:t.XC,to:t.XC,value:t.XC,exit_code:t.XC,method_name:t.XC}),V=(0,t.su)({account_type:t.XC,account_info:(0,t.su)({account_basic:(0,t.su)({account_id:t.XC,account_address:t.XC,account_type:t.XC,account_balance:t.XC,nonce:t.mH,code_cid:t.XC,create_time:t.XC,latest_transfer_time:t.XC})})}),N=(0,t.su)({messages_by_account_id_list:(0,t.Vk)((0,t._2)(G),()=>[]),total_count:t.mH}),j=(0,t.su)({MessageDetails:(0,t.su)({message_basic:(0,t.su)({height:t.mH,block_time:t.mH,cid:t.XC,from:t.XC,to:t.XC,value:t.XC,exit_code:t.XC,method_name:t.XC}),blk_cids:(0,t._2)(t.XC),consume_list:(0,t._2)((0,t.su)({from:t.XC,to:t.XC,value:t.XC,consume_type:t.XC})),version:t.mH,nonce:t.mH,gas_fee_cap:t.XC,gas_premium:t.XC,gas_limit:t.mH,gas_used:t.XC,base_fee:t.XC,all_gas_fee:t.XC,eth_message:t.XC})});class W{constructor(e,s){this.baseUrl=e,this.fetch=s}getAccountInfo(e){return k(this,null,function*(){const a=yield(yield this.fetch(`${this.baseUrl}/AccountInfoByID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:e})})).text(),r=R(V)(a);if(!("result"in r))throw new Error(`Error response code ${r.code}: ${r.message}`);return r.result})}getAccountMessages(e,s,a=20){return k(this,null,function*(){const o=yield(yield this.fetch(`${this.baseUrl}/MessagesByAccountID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:e,address:"",filters:{index:s,page:0,limit:a,method_name:""}})})).text(),i=R(N)(o);if(!("result"in i))throw new Error(`Error response code ${i.code}: ${i.message}`);return i.result})}getMessageDetails(e){return k(this,null,function*(){const a=yield(yield this.fetch(`${this.baseUrl}/MessageDetails`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({message_cid:e})})).text(),r=R(j)(a);if(!("result"in r))throw new Error(`Error response code ${r.code}: ${r.message}`);return r.result})}}var ne=Math.pow,re=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});const oe=u=>(0,t.su)({id:t.mH,jsonrpc:t.XC,result:u}),ie=(0,t.su)({id:t.mH,jsonrpc:t.XC,error:(0,t.su)({code:t.mH,message:t.XC})}),ae=u=>(0,t.$e)((0,t._C)(ie,oe(u))),ce=(0,t.su)({Height:t.mH});class le{constructor(e,s){this.baseUrl=e,this.fetch=s}getChainHead(){return re(this,null,function*(){const e=Math.floor(Math.random()*ne(10,8)),a=yield(yield this.fetch(this.baseUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,jsonrpc:"2.0",method:"Filecoin.ChainHead",params:null})})).text(),r=ae(ce)(a);if("error"in r)throw new Error(`Error response code ${r.error.code}: ${r.error.message}`);return r})}}var ue=Object.defineProperty,de=Object.defineProperties,he=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertySymbols,fe=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable,ge=Reflect.get,ee=(u,e,s)=>e in u?ue(u,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[e]=s,ye=(u,e)=>{for(var s in e||(e={}))pe.call(e,s)&&ee(u,s,e[s]);if(q)for(var s of q(e))me.call(e,s)&&ee(u,s,e[s]);return u},Ce=(u,e)=>de(u,he(e)),Q=(u,e,s)=>ge(fe(u),s,e),P=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});const ve=15e3,we=3e4,Pe=15e3;class L extends C.P{constructor(e,s,a,r){super(e,s,a,r),this.filfoxMessageToEdgeTransaction=i=>{const l=this.address.toString(),c=[],p=i.transfers.filter(A=>A.type==="miner-fee"||A.type==="burner-fee").reduce((A,I)=>(0,v.add)(A,I.value),"0");let y;return i.from===l?(y=`-${p}`,i.to!==l&&(y=(0,v.sub)(y,i.value))):(y=i.value,c.push(l)),{blockHeight:i.height,currencyCode:this.currencyInfo.currencyCode,date:i.timestamp,isSend:y.startsWith("-"),memos:[],nativeAmount:y,networkFee:p,otherParams:{},ourReceiveAddresses:c,signedTx:"",txid:i.cid,walletId:this.walletId}};const{networkInfo:o}=e;this.address=n.kL.fromString(a.keys.address),this.availableAttoFil="0",this.isScanning=!1,this.networkInfo=o,this.pluginId=this.currencyInfo.pluginId,this.filRpc=new n.rP(n.Zc[e.networkInfo.rpcNode.networkName],{url:e.networkInfo.rpcNode.url,token:e.currencyInfo.currencyCode}),this.filfoxApi=new d.V7(e.networkInfo.filfoxUrl,e.io.fetchCors),this.filscanApi=new W(e.networkInfo.filscanUrl,e.io.fetchCors),this.rpcExtra=new le(e.networkInfo.rpcNode.url,e.io.fetchCors)}setOtherData(e){this.otherData=X(e)}initData(){this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=0,this.availableAttoFil="0"}initSubscriptions(){this.addToLoop("checkBalance",ve).catch(e=>this.log(e)),this.addToLoop("checkBlockHeight",we).catch(e=>this.log(e)),this.addToLoop("checkTransactions",Pe).catch(e=>this.log(e))}onUpdateBlockHeight(e){this.walletLocalData.blockHeight!==e&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}startEngine(){return P(this,null,function*(){this.engineOn=!0,this.initData(),this.initSubscriptions(),yield Q(L.prototype,this,"startEngine").call(this)})}killEngine(){return P(this,null,function*(){yield Q(L.prototype,this,"killEngine").call(this),yield new Promise(e=>{const s=setInterval(()=>{this.isScanning||(clearInterval(s),e())},300)})})}clearBlockchainCache(){return P(this,null,function*(){yield Q(L.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return P(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return P(this,null,function*(){const{address:e}=this.walletInfo.keys;return{publicAddress:e}})}getMaxSpendable(e){return P(this,null,function*(){var s;const a=e.spendTargets[0].publicAddress;if(a==null)throw new Error("Missing publicAddress");e.skipChecks=!0;const r=e.spendTargets[0];if(r==null)throw new Error("missing spendTargets");r.nativeAmount=(s=r.nativeAmount)!=null?s:"0";const o=yield this.makeSpend(e),i=(0,v.sub)(this.availableAttoFil,o.networkFee),l=n.YW.getNew(n.kL.fromString(a),this.address,n.WU.fromAtto(i),0);yield l.prepareToSend(this.filRpc);const{GasLimit:c,GasPremium:p,GasFeeCap:y}=l.toJSON(),E=(0,v.mul)(c.toString(),y),A=(0,v.sub)(this.availableAttoFil,E);return this.lastMaxSpendable={nativeAmount:A,params:{GasLimit:c,GasPremium:p,GasFeeCap:y}},A})}makeSpend(e){return P(this,null,function*(){e=(0,b.s)(e,this.currencyInfo);const{edgeSpendInfo:s,currencyCode:a,skipChecks:r}=this.makeSpendCheck(e),{memos:o=[]}=s,i=s.spendTargets[0];if(i==null)throw new Error("missing spendTargets");const{publicAddress:l,nativeAmount:c}=i;if(l==null)throw new Error("Missing publicAddress in EdgeSpendInfo");if(c==null)throw new g.$D;const p=this.tools.normalizeAddress(l),y=n.YW.getNew(p,this.address,n.WU.fromAtto(c),0);yield y.prepareToSend(this.filRpc);const E=y.toJSON();if(this.lastMaxSpendable!=null){const{nativeAmount:se,params:Te}=this.lastMaxSpendable;(0,v.eq)(se,se)&&(Object.assign(E,Te),delete this.lastMaxSpendable)}const A={sigJson:void 0,txJson:E},I=(0,v.mul)(E.GasLimit.toString(),E.GasFeeCap),O=(0,v.add)(c,I),J=(0,v.mul)(O,"-1"),z=this.availableAttoFil;if(!r&&(0,v.gt)(O,z))throw new g.C_;return{blockHeight:0,currencyCode:a,date:0,isSend:!0,memos:o,nativeAmount:J,networkFee:I,otherParams:A,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,s){return P(this,null,function*(){const a=T(e.otherParams),r=n.YW.fromJSON(a.txJson),o=h(this.pluginId)(s),i=n.w5.deriveAccount(o.mnemonic,n.BG.SECP256K1,this.tools.derivationPath),l=yield n.w5.signTransaction(i,r);return e.otherParams=Ce(ye({},e.otherParams),{sigJson:l.toJSON()}),e.date=Date.now()/1e3,e})}broadcastTx(e,s){return P(this,null,function*(){const a=T(e.otherParams);if(a.sigJson==null)throw new Error("Cannot broadcast unsigned transaction");const r=n.Pc.fromJSON(a.sigJson),o=n.YW.fromJSON(a.txJson),i=yield this.filRpc.broadcastTransaction(o,r);if("error"in i)throw new Error(i.error.message);return e.txid=i.result["/"],e})}getDisplayPrivateSeed(e){return h(this.pluginId)(e).mnemonic}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}loadEngine(){return P(this,null,function*(){yield Q(L.prototype,this,"loadEngine").call(this),this.engineOn=!0})}checkBalance(){return P(this,null,function*(){const e=yield this.filRpc.walletBalance(this.address);if("error"in e)throw new Error(e.error.message);const{result:s}=e;this.availableAttoFil=s,this.updateBalance(this.currencyInfo.currencyCode,s),this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.walletLocalDataDirty=!0})}checkBlockHeight(){return P(this,null,function*(){const s=(yield this.rpcExtra.getChainHead()).result.Height;this.onUpdateBlockHeight(s)})}checkTransactions(){return P(this,null,function*(){if(!this.isScanning)try{this.isScanning=!0;const e=this.address.toString(),s=o=>{const i=this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode],l=o;i<1&&(l>=1||l>i*1.1)&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=l,this.updateOnAddressesChecked())},a=({tx:o,progress:i})=>{o!=null&&(this.addTransaction(this.currencyInfo.currencyCode,o),this.onUpdateTransactions(),this.walletLocalData.blockHeight<o.blockHeight&&this.onUpdateBlockHeight(o.blockHeight)),s(i)},r=[this.scanTransactionsFromFilfox(e,a)];yield Promise.all(r),this.walletLocalData.lastAddressQueryHeight=this.walletLocalData.blockHeight,this.walletLocalDataDirty=!0,s(1)}catch(e){throw console.error(e),e}finally{this.isScanning=!1}})}scanTransactionsFromFilfox(e,s){return P(this,null,function*(){const a=new Set;let o=(yield this.filfoxApi.getAccountTransfers(e,0,1)).totalCount;const i=20;let l=Math.ceil(o/i),c=0;for(let p=l-1;p>=0;p--){const y=yield this.filfoxApi.getAccountTransfers(e,p,i);let E=y.transfers;if(y.totalCount!==o){const A=y.totalCount-o,O=(p+1)*(i/A),J=yield this.filfoxApi.getAccountTransfers(e,O,A);E=[...E,...J.transfers],o=y.totalCount,l=Math.ceil(o/i)}for(let A=E.length-1;A>=0;A--){if(!this.engineOn)return;const I=E[A];let O;if(I.height>=this.walletLocalData.lastAddressQueryHeight&&!a.has(I.message)){I.height>this.walletLocalData.lastAddressQueryHeight&&(this.walletLocalData.lastAddressQueryHeight=I.height,this.walletLocalDataDirty=!0);const z=yield this.filfoxApi.getMessageDetails(I.message);O=this.filfoxMessageToEdgeTransaction(z)}const J=o===0?1:++c/o;s({tx:O,progress:J}),a.add(I.message)}}})}scanTransactionsFromFilscan(e,s){return P(this,null,function*(){let r=0,o=0,i=-1;do{const l=yield this.filscanApi.getAccountMessages(e,r++,20);i=i===-1?l.total_count:i;const c=l.messages_by_account_id_list;for(const p of c){if(p.height<this.walletLocalData.lastAddressQueryHeight)return;const y=this.filscanMessageToEdgeTransaction(p),E=i===0?1:++o/i;s({tx:y,progress:E})}}while(o<i)})}filscanMessageToEdgeTransaction(e){const s=this.address.toString(),a=[],r="0";let o;return e.from===s?(o=`-${r}`,e.to!==s&&(o=(0,v.sub)(o,e.value))):(o=e.value,a.push(s)),{blockHeight:e.height,currencyCode:this.currencyInfo.currencyCode,date:e.block_time,isSend:o.startsWith("-"),memos:[],nativeAmount:o,networkFee:r,otherParams:{},ourReceiveAddresses:a,signedTx:"",txid:e.cid,walletId:this.walletId}}}function Ee(u,e,s,a){return P(this,null,function*(){const r=f(s),o=new L(u,e,r,a);return yield o.loadEngine(),o})}var H=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});class te{constructor(e){const{builtinTokens:s,currencyInfo:a,io:r,networkInfo:o}=e;this.builtinTokens=s,this.currencyInfo=a,this.io=r,this.networkInfo=o,this.derivationPath=`m/44'/${this.networkInfo.hdPathCoinType}'/0'/0/0`}isValidAddress(e){try{const s=this.normalizeAddress(e);return!(n.kL.isFilEthAddress(s)&&/^(0x)?[A-Fa-f0-9]+$/.test(e)&&(/[A-F]/.test(e)&&!M().isValidChecksumAddress(e)||!M().isValidAddress(e.toLowerCase()||"")))}catch{return!1}}normalizeAddress(e){try{return n.kL.fromEthAddress(n.PY[this.networkInfo.networkPrefix],e)}catch{}return n.kL.fromString(e)}importPrivateKey(e){return H(this,arguments,function*(s,a={}){const{pluginId:r}=this.currencyInfo;if(!(0,x.validateMnemonic)(s))throw new Error("Invalid mnemonic");const o=(yield(0,x.mnemonicToSeed)(s)).toString("hex");return{[`${r}Key`]:o,[`${r}Mnemonic`]:s}})}createPrivateKey(e){return H(this,null,function*(){const{pluginId:s}=this.currencyInfo;if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const a=D.YU.stringify(this.io.random(32)),r=(0,x.entropyToMnemonic)(a);return{[`${s}Key`]:a,[`${s}Mnemonic`]:r}})}checkPublicKey(e){return H(this,null,function*(){return(0,t.Vk)(w)(e)!=null})}derivePublicKey(e){return H(this,null,function*(){if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{pluginId:s}=this.currencyInfo,{hdPathCoinType:a}=this.networkInfo,r=h(s)(e.keys),o=yield(0,x.mnemonicToSeed)(r.mnemonic),p=(0,U.fromSeed)(o).deriveHardened(44).deriveHardened(a).deriveHardened(0).neutered().toBase58(),E=n.w5.deriveAccount(r.mnemonic,n.BG.SECP256K1,this.derivationPath,void 0,n.PY[this.networkInfo.networkPrefix]).address.toString();return{publicKey:p,address:E}})}parseUri(e,s,a){return H(this,null,function*(){const{pluginId:r}=this.currencyInfo,o={[r]:!0},{edgeParsedUri:i,edgeParsedUri:{publicAddress:l}}=(0,F.k)(this.currencyInfo,e,o,s!=null?s:this.currencyInfo.currencyCode,a);if(l==null||!this.isValidAddress(l))throw new Error("InvalidPublicAddressError");return i})}encodeUri(e){return H(this,arguments,function*(s,a=[]){const{pluginId:r}=this.currencyInfo,{nativeAmount:o,currencyCode:i,publicAddress:l}=s;if(!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");let c;if(o!=null){const y=(0,K.Qs)(i!=null?i:this.currencyInfo.currencyCode,this.currencyInfo,a);if(y==null)throw new Error("InternalErrorInvalidCurrencyCode");c=(0,v.div)(o,y.multiplier,18)}return(0,F.Q)(s,`${r}`,c)})}}function Ae(u){return H(this,null,function*(){return new te(u)})}},77258:function(Y,_,m){"use strict";m.d(_,{V7:function(){return $}});var n=m(82448),v=(X,T,w)=>new Promise((f,h)=>{var g=d=>{try{b(w.next(d))}catch(k){h(k)}},C=d=>{try{b(w.throw(d))}catch(k){h(k)}},b=d=>d.done?f(d.value):Promise.resolve(d.value).then(g,C);b((w=w.apply(X,T)).next())});const U=(0,n.su)({statusCode:n.mH,message:n.XC,error:n.XC}),x=X=>(0,n.$e)((0,n._C)(U,X)),t=(0,n.su)({cid:n.XC,from:n.XC,height:n.mH,method:n.XC,nonce:n.mH,receipt:(0,n.su)({exitCode:n.mH}),timestamp:n.mH,to:n.XC,value:n.XC}),B=(0,n.su)({cid:n.XC,height:n.mH,timestamp:n.mH,from:n.XC,to:n.XC,value:n.XC,gasLimit:n.mH,gasFeeCap:n.XC,gasPremium:n.XC,receipt:(0,n.su)({exitCode:n.mH,return:n.XC,gasUsed:n.mH}),baseFee:n.XC,fee:(0,n.su)({baseFeeBurn:n.XC,overEstimationBurn:n.XC,minerPenalty:n.XC,minerTip:n.XC,refund:n.XC}),transfers:(0,n._2)((0,n.su)({from:n.XC,fromId:n.XC,to:n.XC,toId:n.XC,value:n.XC,type:n.XC}))}),M=(0,n.su)({from:n.XC,height:n.mH,message:n.XC,timestamp:n.mH,to:n.XC,type:n.XC,value:n.XC}),D=(0,n.su)({messages:(0,n._2)(t),totalCount:n.mH}),F=B,K=(0,n.su)({transfers:(0,n._2)(M),totalCount:n.mH});class ${constructor(T,w){this.baseUrl=T,this.fetch=w}getAccountMessages(T,w,f=20){return v(this,null,function*(){const h=new URL(`${this.baseUrl}/address/${T}/messages`),g=new URLSearchParams({page:w.toString(),pageSize:f.toString()});h.search=g.toString();const b=yield(yield this.fetch(h.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),d=x(D)(b);if("error"in d)throw new Error(`Error response code ${d.statusCode}: ${d.message} ${d.error}`);return d})}getAccountTransfers(T,w,f=20){return v(this,null,function*(){const h=new URL(`${this.baseUrl}/address/${T}/transfers`),g=new URLSearchParams({page:w.toString(),pageSize:f.toString()});h.search=g.toString();const b=yield(yield this.fetch(h.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),d=x(K)(b);if("error"in d)throw new Error(`Error response code ${d.statusCode}: ${d.message} ${d.error}`);return d})}getMessageDetails(T){return v(this,null,function*(){const f=yield(yield this.fetch(`${this.baseUrl}/message/${T}`,{method:"GET",headers:{"content-type":"application/json"}})).text(),h=x(F)(f);if("error"in h)throw new Error(`Error response code ${h.statusCode}: ${h.message} ${h.error}`);return h})}}},69159:function(){},89214:function(){},52361:function(){},94616:function(){}}]);
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[8518],{79014:function(Y,_,m){"use strict";m.d(_,{Q:function(){return w},k:function(){return T}});var n=m(77591),v=m.n(n),U=m(24350),x=m(84564),t=m.n(x),B=m(76714),M=Object.defineProperty,D=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,$=(f,h,g)=>h in f?M(f,h,{enumerable:!0,configurable:!0,writable:!0,value:g}):f[h]=g,S=(f,h)=>{for(var g in h||(h={}))F.call(h,g)&&$(f,g,h[g]);if(D)for(var g of D(h))K.call(h,g)&&$(f,g,h[g]);return f};function T(f,h,g,C,b=[]){const d=S({},t()(h,{},!0)),k=h.startsWith(`${f.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!g[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${f.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const X={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},R=d.query.label,G=d.query.message,V=d.query.category;(R!=null||G!=null||V!=null||k)&&(X.metadata={},X.metadata.name=R,X.metadata.notes=G,X.metadata.category=V,X.metadata.gateway=k!=null?k:!1);const N=d.query.amount;if(N!=null&&typeof N=="string"){C==null&&(C=f.currencyCode);const j=(0,B.Qs)(C!=null?C:"",f,b);if(j==null)throw new Error("InternalErrorInvalidCurrencyCode");let W=(0,n.mul)(N,j.multiplier);W=(0,n.toFixed)(W,0,0),X.nativeAmount=W,X.currencyCode=C}return{edgeParsedUri:X,parsedUri:d}}function w(f,h,g){if(f.publicAddress==null)throw new Error("InvalidPublicAddressError");if(g==null&&f.label==null&&f.message==null)return f.publicAddress;{let C="";g!=null&&(C+="amount="+g+"&"),(f.label!=null||f.message!=null)&&(typeof f.label=="string"&&(C+="label="+f.label+"&"),typeof f.message=="string"&&(C+="message="+f.message+"&")),C=C.substr(0,C.length-1);const b={scheme:h,path:f.publicAddress,query:C};return(0,U.qC)(b)}}},59677:function(Y,_,m){"use strict";m.r(_),m.d(_,{FilecoinTools:function(){return te},makeCurrencyEngine:function(){return Ee},makeCurrencyTools:function(){return Ae}});var n=m(23145),v=m(77591),U=m(37786),x=m(2153),t=m(82448),B=m(21964),M=m.n(B),D=m(79325),F=m(79014),K=m(76714),$=m(62177);const S=(0,t.su)({}),T=(0,t.su)({sigJson:(0,t.Zz)((0,t.su)({Data:t.XC,Type:(0,t.Wf)(1,3)})),txJson:(0,t.su)({To:t.XC,From:t.XC,Nonce:t.mH,Value:t.XC,GasLimit:t.mH,GasFeeCap:t.XC,GasPremium:t.XC,Method:t.mH,Params:t.XC})}),w=(0,t.su)({address:t.XC,publicKey:t.XC}),f=(0,$.jd)(w),h=u=>{const e=(0,t.su)({[`${u}Mnemonic`]:t.XC,[`${u}Key`]:t.XC});return(0,t.W1)(s=>{const a=e(s);return{mnemonic:a[`${u}Mnemonic`],privateKey:a[`${u}Key`]}},s=>({[`${u}Mnemonic`]:s.mnemonic,[`${u}Key`]:s.privateKey}))};var g=m(94935),C=m(84650),b=m(72681),d=m(77258),k=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});const Z=u=>(0,t.su)({result:u}),X=(0,t.su)({code:t.mH,message:t.XC}),R=u=>(0,t.$e)((0,t._C)(X,Z(u))),G=(0,t.su)({height:t.mH,block_time:t.mH,cid:t.XC,from:t.XC,to:t.XC,value:t.XC,exit_code:t.XC,method_name:t.XC}),V=(0,t.su)({account_type:t.XC,account_info:(0,t.su)({account_basic:(0,t.su)({account_id:t.XC,account_address:t.XC,account_type:t.XC,account_balance:t.XC,nonce:t.mH,code_cid:t.XC,create_time:t.XC,latest_transfer_time:t.XC})})}),N=(0,t.su)({messages_by_account_id_list:(0,t.Vk)((0,t._2)(G),()=>[]),total_count:t.mH}),j=(0,t.su)({MessageDetails:(0,t.su)({message_basic:(0,t.su)({height:t.mH,block_time:t.mH,cid:t.XC,from:t.XC,to:t.XC,value:t.XC,exit_code:t.XC,method_name:t.XC}),blk_cids:(0,t._2)(t.XC),consume_list:(0,t._2)((0,t.su)({from:t.XC,to:t.XC,value:t.XC,consume_type:t.XC})),version:t.mH,nonce:t.mH,gas_fee_cap:t.XC,gas_premium:t.XC,gas_limit:t.mH,gas_used:t.XC,base_fee:t.XC,all_gas_fee:t.XC,eth_message:t.XC})});class W{constructor(e,s){this.baseUrl=e,this.fetch=s}getAccountInfo(e){return k(this,null,function*(){const a=yield(yield this.fetch(`${this.baseUrl}/AccountInfoByID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:e})})).text(),r=R(V)(a);if(!("result"in r))throw new Error(`Error response code ${r.code}: ${r.message}`);return r.result})}getAccountMessages(e,s,a=20){return k(this,null,function*(){const o=yield(yield this.fetch(`${this.baseUrl}/MessagesByAccountID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:e,address:"",filters:{index:s,page:0,limit:a,method_name:""}})})).text(),i=R(N)(o);if(!("result"in i))throw new Error(`Error response code ${i.code}: ${i.message}`);return i.result})}getMessageDetails(e){return k(this,null,function*(){const a=yield(yield this.fetch(`${this.baseUrl}/MessageDetails`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({message_cid:e})})).text(),r=R(j)(a);if(!("result"in r))throw new Error(`Error response code ${r.code}: ${r.message}`);return r.result})}}var ne=Math.pow,re=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});const oe=u=>(0,t.su)({id:t.mH,jsonrpc:t.XC,result:u}),ie=(0,t.su)({id:t.mH,jsonrpc:t.XC,error:(0,t.su)({code:t.mH,message:t.XC})}),ae=u=>(0,t.$e)((0,t._C)(ie,oe(u))),ce=(0,t.su)({Height:t.mH});class le{constructor(e,s){this.baseUrl=e,this.fetch=s}getChainHead(){return re(this,null,function*(){const e=Math.floor(Math.random()*ne(10,8)),a=yield(yield this.fetch(this.baseUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,jsonrpc:"2.0",method:"Filecoin.ChainHead",params:null})})).text(),r=ae(ce)(a);if("error"in r)throw new Error(`Error response code ${r.error.code}: ${r.error.message}`);return r})}}var ue=Object.defineProperty,de=Object.defineProperties,he=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertySymbols,fe=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable,ge=Reflect.get,ee=(u,e,s)=>e in u?ue(u,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[e]=s,ye=(u,e)=>{for(var s in e||(e={}))pe.call(e,s)&&ee(u,s,e[s]);if(q)for(var s of q(e))me.call(e,s)&&ee(u,s,e[s]);return u},Ce=(u,e)=>de(u,he(e)),Q=(u,e,s)=>ge(fe(u),s,e),P=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});const ve=15e3,we=3e4,Pe=15e3;class L extends C.P{constructor(e,s,a,r){super(e,s,a,r),this.filfoxMessageToEdgeTransaction=i=>{const l=this.address.toString(),c=[],p=i.transfers.filter(A=>A.type==="miner-fee"||A.type==="burner-fee").reduce((A,I)=>(0,v.add)(A,I.value),"0");let y;return i.from===l?(y=`-${p}`,i.to!==l&&(y=(0,v.sub)(y,i.value))):(y=i.value,c.push(l)),{blockHeight:i.height,currencyCode:this.currencyInfo.currencyCode,date:i.timestamp,isSend:y.startsWith("-"),memos:[],nativeAmount:y,networkFee:p,otherParams:{},ourReceiveAddresses:c,signedTx:"",txid:i.cid,walletId:this.walletId}};const{networkInfo:o}=e;this.address=n.kL.fromString(a.keys.address),this.availableAttoFil="0",this.isScanning=!1,this.networkInfo=o,this.pluginId=this.currencyInfo.pluginId,this.filRpc=new n.rP(n.Zc[e.networkInfo.rpcNode.networkName],{url:e.networkInfo.rpcNode.url,token:e.currencyInfo.currencyCode}),this.filfoxApi=new d.V7(e.networkInfo.filfoxUrl,e.io.fetchCors),this.filscanApi=new W(e.networkInfo.filscanUrl,e.io.fetchCors),this.rpcExtra=new le(e.networkInfo.rpcNode.url,e.io.fetchCors)}setOtherData(e){this.otherData=S(e)}initData(){this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=0,this.availableAttoFil="0"}initSubscriptions(){this.addToLoop("checkBalance",ve).catch(e=>this.log(e)),this.addToLoop("checkBlockHeight",we).catch(e=>this.log(e)),this.addToLoop("checkTransactions",Pe).catch(e=>this.log(e))}onUpdateBlockHeight(e){this.walletLocalData.blockHeight!==e&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}startEngine(){return P(this,null,function*(){this.engineOn=!0,this.initData(),this.initSubscriptions(),yield Q(L.prototype,this,"startEngine").call(this)})}killEngine(){return P(this,null,function*(){yield Q(L.prototype,this,"killEngine").call(this),yield new Promise(e=>{const s=setInterval(()=>{this.isScanning||(clearInterval(s),e())},300)})})}clearBlockchainCache(){return P(this,null,function*(){yield Q(L.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return P(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return P(this,null,function*(){const{address:e}=this.walletInfo.keys;return{publicAddress:e}})}getMaxSpendable(e){return P(this,null,function*(){var s;const a=e.spendTargets[0].publicAddress;if(a==null)throw new Error("Missing publicAddress");e.skipChecks=!0;const r=e.spendTargets[0];if(r==null)throw new Error("missing spendTargets");r.nativeAmount=(s=r.nativeAmount)!=null?s:"0";const o=yield this.makeSpend(e),i=(0,v.sub)(this.availableAttoFil,o.networkFee),l=n.YW.getNew(n.kL.fromString(a),this.address,n.WU.fromAtto(i),0);yield l.prepareToSend(this.filRpc);const{GasLimit:c,GasPremium:p,GasFeeCap:y}=l.toJSON(),E=(0,v.mul)(c.toString(),y),A=(0,v.sub)(this.availableAttoFil,E);return this.lastMaxSpendable={nativeAmount:A,params:{GasLimit:c,GasPremium:p,GasFeeCap:y}},A})}makeSpend(e){return P(this,null,function*(){e=(0,b.s)(e,this.currencyInfo);const{edgeSpendInfo:s,currencyCode:a,skipChecks:r}=this.makeSpendCheck(e),{memos:o=[]}=s,i=s.spendTargets[0];if(i==null)throw new Error("missing spendTargets");const{publicAddress:l,nativeAmount:c}=i;if(l==null)throw new Error("Missing publicAddress in EdgeSpendInfo");if(c==null)throw new g.$D;const p=this.tools.normalizeAddress(l),y=n.YW.getNew(p,this.address,n.WU.fromAtto(c),0);yield y.prepareToSend(this.filRpc);const E=y.toJSON();if(this.lastMaxSpendable!=null){const{nativeAmount:se,params:Te}=this.lastMaxSpendable;(0,v.eq)(se,se)&&(Object.assign(E,Te),delete this.lastMaxSpendable)}const A={sigJson:void 0,txJson:E},I=(0,v.mul)(E.GasLimit.toString(),E.GasFeeCap),O=(0,v.add)(c,I),J=(0,v.mul)(O,"-1"),z=this.availableAttoFil;if(!r&&(0,v.gt)(O,z))throw new g.C_;return{blockHeight:0,currencyCode:a,date:0,isSend:!0,memos:o,nativeAmount:J,networkFee:I,otherParams:A,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,s){return P(this,null,function*(){const a=T(e.otherParams),r=n.YW.fromJSON(a.txJson),o=h(this.pluginId)(s),i=n.w5.deriveAccount(o.mnemonic,n.BG.SECP256K1,this.tools.derivationPath),l=yield n.w5.signTransaction(i,r);return e.otherParams=Ce(ye({},e.otherParams),{sigJson:l.toJSON()}),e.date=Date.now()/1e3,e})}broadcastTx(e,s){return P(this,null,function*(){const a=T(e.otherParams);if(a.sigJson==null)throw new Error("Cannot broadcast unsigned transaction");const r=n.Pc.fromJSON(a.sigJson),o=n.YW.fromJSON(a.txJson),i=yield this.filRpc.broadcastTransaction(o,r);if("error"in i)throw new Error(i.error.message);return e.txid=i.result["/"],e})}getDisplayPrivateSeed(e){return h(this.pluginId)(e).mnemonic}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}loadEngine(){return P(this,null,function*(){yield Q(L.prototype,this,"loadEngine").call(this),this.engineOn=!0})}checkBalance(){return P(this,null,function*(){const e=yield this.filRpc.walletBalance(this.address);if("error"in e)throw new Error(e.error.message);const{result:s}=e;this.availableAttoFil=s,this.updateBalance(this.currencyInfo.currencyCode,s),this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.walletLocalDataDirty=!0})}checkBlockHeight(){return P(this,null,function*(){const s=(yield this.rpcExtra.getChainHead()).result.Height;this.onUpdateBlockHeight(s)})}checkTransactions(){return P(this,null,function*(){if(!this.isScanning)try{this.isScanning=!0;const e=this.address.toString(),s=o=>{const i=this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode],l=o;i<1&&(l>=1||l>i*1.1)&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=l,this.updateOnAddressesChecked())},a=({tx:o,progress:i})=>{o!=null&&(this.addTransaction(this.currencyInfo.currencyCode,o),this.onUpdateTransactions(),this.walletLocalData.blockHeight<o.blockHeight&&this.onUpdateBlockHeight(o.blockHeight)),s(i)},r=[this.scanTransactionsFromFilfox(e,a)];yield Promise.all(r),this.walletLocalData.lastAddressQueryHeight=this.walletLocalData.blockHeight,this.walletLocalDataDirty=!0,s(1)}catch(e){throw console.error(e),e}finally{this.isScanning=!1}})}scanTransactionsFromFilfox(e,s){return P(this,null,function*(){const a=new Set;let o=(yield this.filfoxApi.getAccountTransfers(e,0,1)).totalCount;const i=20;let l=Math.ceil(o/i),c=0;for(let p=l-1;p>=0;p--){const y=yield this.filfoxApi.getAccountTransfers(e,p,i);let E=y.transfers;if(y.totalCount!==o){const A=y.totalCount-o,O=(p+1)*(i/A),J=yield this.filfoxApi.getAccountTransfers(e,O,A);E=[...E,...J.transfers],o=y.totalCount,l=Math.ceil(o/i)}for(let A=E.length-1;A>=0;A--){if(!this.engineOn)return;const I=E[A];let O;if(I.height>=this.walletLocalData.lastAddressQueryHeight&&!a.has(I.message)){I.height>this.walletLocalData.lastAddressQueryHeight&&(this.walletLocalData.lastAddressQueryHeight=I.height,this.walletLocalDataDirty=!0);const z=yield this.filfoxApi.getMessageDetails(I.message);O=this.filfoxMessageToEdgeTransaction(z)}const J=o===0?1:++c/o;s({tx:O,progress:J}),a.add(I.message)}}})}scanTransactionsFromFilscan(e,s){return P(this,null,function*(){let r=0,o=0,i=-1;do{const l=yield this.filscanApi.getAccountMessages(e,r++,20);i=i===-1?l.total_count:i;const c=l.messages_by_account_id_list;for(const p of c){if(p.height<this.walletLocalData.lastAddressQueryHeight)return;const y=this.filscanMessageToEdgeTransaction(p),E=i===0?1:++o/i;s({tx:y,progress:E})}}while(o<i)})}filscanMessageToEdgeTransaction(e){const s=this.address.toString(),a=[],r="0";let o;return e.from===s?(o=`-${r}`,e.to!==s&&(o=(0,v.sub)(o,e.value))):(o=e.value,a.push(s)),{blockHeight:e.height,currencyCode:this.currencyInfo.currencyCode,date:e.block_time,isSend:o.startsWith("-"),memos:[],nativeAmount:o,networkFee:r,otherParams:{},ourReceiveAddresses:a,signedTx:"",txid:e.cid,walletId:this.walletId}}}function Ee(u,e,s,a){return P(this,null,function*(){const r=f(s),o=new L(u,e,r,a);return yield o.loadEngine(),o})}var H=(u,e,s)=>new Promise((a,r)=>{var o=c=>{try{l(s.next(c))}catch(p){r(p)}},i=c=>{try{l(s.throw(c))}catch(p){r(p)}},l=c=>c.done?a(c.value):Promise.resolve(c.value).then(o,i);l((s=s.apply(u,e)).next())});class te{constructor(e){const{builtinTokens:s,currencyInfo:a,io:r,networkInfo:o}=e;this.builtinTokens=s,this.currencyInfo=a,this.io=r,this.networkInfo=o,this.derivationPath=`m/44'/${this.networkInfo.hdPathCoinType}'/0'/0/0`}isValidAddress(e){try{const s=this.normalizeAddress(e);return!(n.kL.isFilEthAddress(s)&&/^(0x)?[A-Fa-f0-9]+$/.test(e)&&(/[A-F]/.test(e)&&!M().isValidChecksumAddress(e)||!M().isValidAddress(e.toLowerCase()||"")))}catch{return!1}}normalizeAddress(e){try{return n.kL.fromEthAddress(n.PY[this.networkInfo.networkPrefix],e)}catch{}return n.kL.fromString(e)}importPrivateKey(e){return H(this,arguments,function*(s,a={}){const{pluginId:r}=this.currencyInfo;if(!(0,x.validateMnemonic)(s))throw new Error("Invalid mnemonic");const o=(yield(0,x.mnemonicToSeed)(s)).toString("hex");return{[`${r}Key`]:o,[`${r}Mnemonic`]:s}})}createPrivateKey(e){return H(this,null,function*(){const{pluginId:s}=this.currencyInfo;if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const a=D.YU.stringify(this.io.random(32)),r=(0,x.entropyToMnemonic)(a);return{[`${s}Key`]:a,[`${s}Mnemonic`]:r}})}checkPublicKey(e){return H(this,null,function*(){return(0,t.Vk)(w)(e)!=null})}derivePublicKey(e){return H(this,null,function*(){if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{pluginId:s}=this.currencyInfo,{hdPathCoinType:a}=this.networkInfo,r=h(s)(e.keys),o=yield(0,x.mnemonicToSeed)(r.mnemonic),p=(0,U.fromSeed)(o).deriveHardened(44).deriveHardened(a).deriveHardened(0).neutered().toBase58(),E=n.w5.deriveAccount(r.mnemonic,n.BG.SECP256K1,this.derivationPath,void 0,n.PY[this.networkInfo.networkPrefix]).address.toString();return{publicKey:p,address:E}})}parseUri(e,s,a){return H(this,null,function*(){const{pluginId:r}=this.currencyInfo,o={[r]:!0},{edgeParsedUri:i,edgeParsedUri:{publicAddress:l}}=(0,F.k)(this.currencyInfo,e,o,s!=null?s:this.currencyInfo.currencyCode,a);if(l==null||!this.isValidAddress(l))throw new Error("InvalidPublicAddressError");return i})}encodeUri(e){return H(this,arguments,function*(s,a=[]){const{pluginId:r}=this.currencyInfo,{nativeAmount:o,currencyCode:i,publicAddress:l}=s;if(!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");let c;if(o!=null){const y=(0,K.Qs)(i!=null?i:this.currencyInfo.currencyCode,this.currencyInfo,a);if(y==null)throw new Error("InternalErrorInvalidCurrencyCode");c=(0,v.div)(o,y.multiplier,18)}return(0,F.Q)(s,`${r}`,c)})}}function Ae(u){return H(this,null,function*(){return new te(u)})}},77258:function(Y,_,m){"use strict";m.d(_,{V7:function(){return $}});var n=m(82448),v=(S,T,w)=>new Promise((f,h)=>{var g=d=>{try{b(w.next(d))}catch(k){h(k)}},C=d=>{try{b(w.throw(d))}catch(k){h(k)}},b=d=>d.done?f(d.value):Promise.resolve(d.value).then(g,C);b((w=w.apply(S,T)).next())});const U=(0,n.su)({statusCode:n.mH,message:n.XC,error:n.XC}),x=S=>(0,n.$e)((0,n._C)(U,S)),t=(0,n.su)({cid:n.XC,from:n.XC,height:n.mH,method:n.XC,nonce:n.mH,receipt:(0,n.su)({exitCode:n.mH}),timestamp:n.mH,to:n.XC,value:n.XC}),B=(0,n.su)({cid:n.XC,ethTransactionHash:n.XC,height:n.mH,timestamp:n.mH,from:n.XC,to:n.XC,value:n.XC,gasLimit:n.mH,gasFeeCap:n.XC,gasPremium:n.XC,receipt:(0,n.su)({exitCode:n.mH,return:n.XC,gasUsed:n.mH}),baseFee:n.XC,fee:(0,n.su)({baseFeeBurn:n.XC,overEstimationBurn:n.XC,minerPenalty:n.XC,minerTip:n.XC,refund:n.XC}),transfers:(0,n._2)((0,n.su)({from:n.XC,fromId:n.XC,to:n.XC,toId:n.XC,value:n.XC,type:n.XC}))}),M=(0,n.su)({from:n.XC,height:n.mH,message:n.XC,timestamp:n.mH,to:n.XC,type:n.XC,value:n.XC}),D=(0,n.su)({messages:(0,n._2)(t),totalCount:n.mH}),F=B,K=(0,n.su)({transfers:(0,n._2)(M),totalCount:n.mH});class ${constructor(T,w){this.baseUrl=T,this.fetch=w}getAccountMessages(T,w,f=20){return v(this,null,function*(){const h=new URL(`${this.baseUrl}/address/${T}/messages`),g=new URLSearchParams({page:w.toString(),pageSize:f.toString()});h.search=g.toString();const b=yield(yield this.fetch(h.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),d=x(D)(b);if("error"in d)throw new Error(`Error response code ${d.statusCode}: ${d.message} ${d.error}`);return d})}getAccountTransfers(T,w,f=20){return v(this,null,function*(){const h=new URL(`${this.baseUrl}/address/${T}/transfers`),g=new URLSearchParams({page:w.toString(),pageSize:f.toString()});h.search=g.toString();const b=yield(yield this.fetch(h.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),d=x(K)(b);if("error"in d)throw new Error(`Error response code ${d.statusCode}: ${d.message} ${d.error}`);return d})}getMessageDetails(T){return v(this,null,function*(){const f=yield(yield this.fetch(`${this.baseUrl}/message/${T}`,{method:"GET",headers:{"content-type":"application/json"}})).text(),h=x(F)(f);if("error"in h)throw new Error(`Error response code ${h.statusCode}: ${h.message} ${h.error}`);return h})}}},69159:function(){},89214:function(){},52361:function(){},94616:function(){}}]);
|