edge-currency-accountbased 3.2.0 → 3.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/android/src/main/assets/edge-currency-accountbased/2784.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/5336.chunk.js +8 -8
- package/android/src/main/assets/edge-currency-accountbased/edge-currency-accountbased.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/ethereum.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/solana.chunk.js +3 -3
- package/lib/algorand/algorandInfo.js +2 -2
- package/lib/ethereum/info/ethereumInfo.js +1 -1
- package/lib/ethereum/info/fantomInfo.js +1 -1
- package/lib/ethereum/info/goerliInfo.js +1 -1
- package/lib/ethereum/info/polygonInfo.js +1 -1
- package/lib/ethereum/networkAdapters/PulsechainScanAdapter.js +1 -1
- package/lib/solana/SolanaEngine.js +67 -11
- package/lib/solana/solanaInfo.js +2 -2
- package/lib/solana/solanaTypes.js +11 -6
- package/package.json +1 -1
- package/android/src/main/assets/edge-currency-accountbased/533.chunk.js +0 -1
|
@@ -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(r=>()=>be(this,null,function*(){return yield e(r)}));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(r=>be(this,null,function*(){return yield e(r)}));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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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,P.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,P.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:r=""}=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},s=yield this.ethEngine.fetchCors(i,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":r,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(o)}),l=ie()(i,{},!0);return s.ok||this.throwError(s,"fetchPostAmberdataRpc",l),yield s.json()}))})}fetchGetAmberdataApi(e){return ye(this,null,function*(){const{amberdataApiKey:t=""}=this.ethEngine.initOptions;return yield this.serialServers(n=>ye(this,null,function*(){const r=`${st._E}${e}`,a=yield this.ethEngine.fetchCors(r,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":t}});return a.ok||this.throwError(a,"fetchGetAmberdata",r),yield a.json()}))})}}var ae=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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(r=>ae(this,null,function*(){const a=yield this.fetchGetBlockbook(r,"/api/v2");return{server:r,result:a}}));return{blockHeight:(0,P.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:r,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,P.hZ)(r)}catch{throw this.ethEngine.error(`checkTxsBlockbook ${a} error BlockbookAddress ${JSON.stringify(r)}`),new Error(`checkTxsBlockbook ${a} returned invalid JSON for BlockbookAddress`)}const{nonce:o,tokens:s,balance:l}=i;t.newNonce=o,t.tokenBal!=null&&(t.tokenBal[this.ethEngine.currencyInfo.currencyCode]=l),t.server=a;for(const u of s)try{const{symbol:h,balance:f}=(0,P.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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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,P.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,r=`/${this.ethEngine.currencyInfo.pluginId}/dashboards/address/${n}?erc_20=true`;try{const i=yield this.fetchGetBlockchair(r,!1);t=(0,P.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,P.aB)(i),s=o.balance,l=o.token_address,u=o.token_symbol,h=this.ethEngine.getTokenInfo(u);h!=null&&h.contractAddress===l&&(a[u]=s)}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(r=>Te(this,null,function*(){const a=t&&n!=null?`&key=${n}`:"",i=`${r}${e}`,o=yield this.ethEngine.fetchCors(`${i}${a}`);return o.ok||this.throwError(o,"fetchGetBlockchair",i),yield o.json()}))})}}var Le=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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=>Le(this,null,function*(){return yield this.parallelServers(t=>Le(this,null,function*(){const n=`v1/${this.ethEngine.currencyInfo.currencyCode.toLowerCase()}/main/txs/push`,r=e.signedTx.replace("0x",""),a=yield this.fetchPostBlockcypher(n,{tx:r},t);return{result:this.broadcastResponseHandler(a,t,e),server:"blockcypher"}}))})}fetchPostBlockcypher(e,t,n){return Le(this,null,function*(){const{blockcypherApiKey:r}=this.ethEngine.initOptions;let a="";r!=null&&r.length>5&&(a="&token="+r);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)}),s=ie()(i,{},!0);return o.ok||this.throwError(o,"fetchPostBlockcypher",s.hostname),yield o.json()})}}var lt=E(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=E(86352),ge=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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 r=e[n];typeof r=="string"&&d(` ${n}: ${(0,c.div)(r,"1000000000",18)} gwei`)}},mt=(d,e,t,n,r)=>({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,r)}))}),yt=(d,e,t,n,r)=>ge(void 0,null,function*(){const{networkAdapterConfigs:a,supportsEIP1559:i=!1}=r;if(i)return;const o=a.find(w=>w.type==="rpc");if(o==null)return;const s=o.servers,l=(0,y.sD)(s,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)(P.tT)(f);if(m==null)throw new Error(`fetchFeesFromRpc ${l} returned invalid json: ${f}`);const{result:g}=m,v=(0,y.Z8)(g),b={lowFee:(0,c.mul)(v,"1"),standardFeeLow:(0,c.mul)(v,"1.06"),standardFeeHigh:(0,c.mul)(v,"1.12"),highFee:(0,c.mul)(v,"1.25")};return n(`fetchFeesFromRpc: ${e.currencyCode}`),Ce(n,b),b}),gt=(d,e,t,n,r)=>ge(void 0,null,function*(){const{networkAdapterConfigs:a}=r,i=a.find(N=>N.type==="evmscan");if(i==null)return;const o=i.servers,s=Ne(t,e,n);if(o==null||s==null)return;const l=`&apikey=${Array.isArray(s)?(0,y.sD)(s,1)[0]:s!=null?s:""}`,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:v,ProposeGasPrice:b,FastGasPrice:w}=(0,P.TI)(f.result),k=parseFloat(v);let C=parseFloat(b),S=parseFloat(w);C<=k&&(C=k+1),S<=C&&(S=C+1);const G=`${k*Y}`,B=`${(k+C)/2*Y}`,Q=`${S*Y}`,x=`${S*Y/Pe}`,$={lowFee:G,standardFeeLow:B,standardFeeHigh:Q,highFee:x};return n(`fetchFeesFromEvmScan: ${e.currencyCode}`),Ce(n,$),$}),vt=(d,e,t,n,r)=>ge(void 0,null,function*(){const{ethGasStationUrl:a}=r,i=Et(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,g=m>u.fastest?m:u.fastest;h=Math.round(h)*pe,f=Math.round(f)*pe,m=Math.round(m)*pe,g=Math.round(g)*pe;const v={lowFee:h.toString(),standardFeeLow:f.toString(),standardFeeHigh:m.toString(),highFee:g.toString()};return n(`fetchFeesFromEvmGasStation: ${e.currencyCode}`),Ce(n,v),v}),wt=(d,e,...t)=>ge(void 0,[d,e,...t],function*(n,{pluginId:r},a={}){const o=yield(yield(0,pt.Vn)(`v1/networkFees/${r}`,void 0,a.timeout,n)).json();return(0,P.b6)(o)}),Ne=(d,e,t)=>{const{evmScanApiKey:n,etherscanApiKey:r,ftmscanApiKey:a,bscscanApiKey:i,polygonscanApiKey:o}=d;if(n!=null)return n;const{currencyCode:s}=e;if(s==="ETH"&&r!=null)return t.warn("INIT OPTION 'etherscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),r;if(s==="FTM"&&a!=null)return t.warn("INIT OPTION 'ftmscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),a;if(s==="BNB"&&i!=null)return t.warn("INIT OPTION 'bscscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),i;if(s==="MATIC"&&o!=null)return t.warn("INIT OPTION 'polygonscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),o},Et=(d,e,t)=>{const{gasStationApiKey:n,ethGasStationApiKey:r}=d;if(n!=null)return n;const{currencyCode:a}=e;if(a==="ETH"&&r!=null)return t.warn("INIT OPTION 'ethGasStationApiKey' IS DEPRECATED. USE 'gasStationApiKey' INSTEAD"),r};var V=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.value).then(a,i);o((t=t.apply(d,e)).next())});const kt=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(r=>V(this,null,function*(){if(!r.includes("etherscan")&&!r.includes("blockscout"))throw new Error(`Unsupported command eth_blockNumber in ${r}`);let a="?module=proxy&action=eth_blockNumber";r.includes("blockscout")&&(a="?module=block&action=eth_block_number");const i=yield this.fetchGetEtherscan(r,a);if(typeof i.result!="string"){const o=`Invalid return value eth_blockNumber in ${r}`;throw this.ethEngine.error(o),new Error(o)}return{server:r,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}`,r=yield this.fetchGetEtherscan(t,n);return{result:this.broadcastResponseHandler(r,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:r}=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 s=`Invalid return value eth_getTransactionCount in ${i}`;throw this.ethEngine.error(s),new Error(s)}return{server:i,result:o}}));return{newNonce:ht(n).result,server:r}}),this.fetchTokenBalance=e=>V(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey;let n,r,a,i;try{if(e===this.ethEngine.currencyInfo.currencyCode){const o=`?module=account&action=balance&address=${t}&tag=latest`;n=yield this.serialServers(s=>V(this,null,function*(){const l=yield this.fetchGetEtherscan(s,o);if(typeof l.result!="string"||l.result===""){const u=`Invalid return value eth_getBalance in ${s}`;throw this.ethEngine.error(u),new Error(u)}return(0,lt.jD)(l.result),{server:s,result:l}})),r=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}}));r=u.result,a=u.server}}i=(0,P.tT)(r)}catch(o){throw this.ethEngine.error(`checkTokenBalEthscan token ${e} response ${String(n!=null?n:"")} `,o),new Error(`checkTokenBalEthscan invalid ${e} response ${JSON.stringify(r)}`)}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,r;const{startBlock:a,currencyCode:i}=e;let o,s;if(i===this.ethEngine.currencyInfo.currencyCode){const u=yield this.getAllTxsEthscan(a,i,P.EV,{searchRegularTxs:!0}),h=yield this.getAllTxsEthscan(a,i,P.xF,{searchRegularTxs:!1});o=(n=(t=u.server)!=null?t:h.server)!=null?n:"",s=[...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,P.T0,{contractAddress:h});o=(r=f.server)!=null?r:"",s=f.allTransactions}else return{}}const l={blockHeight:a,edgeTransactions:s};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}`,s=yield this.ethEngine.fetchCors(`${o}${i}`);return s.ok||this.throwError(s,"fetchGetEtherscan",o),yield s.json()})}getAllTxsEthscan(e,t,n,r){return V(this,null,function*(){const a=this.ethEngine.walletLocalData.publicKey;let i=1;const o=[];let s;const l=r.contractAddress,u=r.searchRegularTxs;for(;;){const h=kt;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}`,g=this.config.servers.length===0?{result:{result:[]},server:void 0}:yield this.serialServers(b=>V(this,null,function*(){const w=yield this.fetchGetEtherscan(b,m);if(typeof w.result!="object"||typeof w.result.length!="number"){const k=`Invalid return value getTransactions in ${b}`;throw w.result!=="Max rate limit reached"&&this.ethEngine.error(k),new Error(k)}return{server:b,result:w}}));s=g.server;const v=g.result.result;for(let b=0;b<v.length;b++)try{const w=n(v[b]),k=yield this.processEvmScanTransaction(w,t);o.push(k)}catch(w){throw this.ethEngine.error(`getAllTxsEthscan ${n.name}
|
|
8
8
|
${(0,y.HY)(w)}
|
|
9
|
-
${JSON.stringify(v[b])}`),new Error(`getAllTxsEthscan ${n.name} is invalid`)}if(v.length===0)break;i++}return{allTransactions:o,server:s}})}processEvmScanTransaction(e,t){return V(this,null,function*(){var n;const r=[],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,s="gasPrice"in e?e.gasPrice:void 0,l=s!=null?(0,c.mul)(s,e.gasUsed):"0";let u="0";if(i&&this.ethEngine.networkInfo.optimismRollupParams!=null){const w=yield this.ethEngine.ethNetwork.multicastRpc("eth_getTransactionReceipt",[a]),k=(0,P.zv)(w.result.result);u=(0,c.add)(u,(0,y.X0)(k.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",r.push(this.ethEngine.walletLocalData.publicKey));const g={from:[e.from],to:[e.to],gas:e.gas,gasPrice:s!=null?s:"",gasUsed:e.gasUsed,isFromMakeSpend:!1};let v=parseInt(e.blockNumber);return v<0&&(v=0),{blockHeight:v,currencyCode:t,date:parseInt(e.timeStamp),feeRateUsed:s!=null?Ie(s,e.gas,e.gasUsed):void 0,isSend:h.startsWith("-"),memos:[],nativeAmount:h,networkFee:f,otherParams:g,ourReceiveAddresses:r,parentNetworkFee:m,signedTx:"",txid:a,walletId:this.ethEngine.walletId}})}}var bt=E(77258),me=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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=[],r=t.transfers.filter(o=>o.type==="miner-fee"||o.type==="burner-fee").reduce((o,s)=>(0,c.add)(o,s.value),"0");let a;return t.from===e?(a=`-${r}`,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:r,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:r}=yield this.ethEngine.getFreshAddress(),a=s=>{const l=this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode],u=s;l<1&&(u>=1||u>l*1.1)&&(this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode]=u,this.ethEngine.updateOnAddressesChecked())},i=({tx:s,progress:l})=>{s!=null&&(this.ethEngine.addTransaction(n,s),this.onUpdateTransactions(),this.ethEngine.walletLocalData.blockHeight<s.blockHeight&&this.onUpdateBlockHeight(s.blockHeight)),a(l)},o=[this.scanTransactionsFromFilfox(r,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),s=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,g=(l+1)*(i/f),v=yield this.serialServers(b=>me(this,null,function*(){return yield this.makeFilfoxApi(b).getAccountTransfers(e,g,f)}));h=[...h,...v.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 g;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 b=yield this.serialServers(w=>me(this,null,function*(){return yield this.makeFilfoxApi(w).getMessageDetails(m.message)}));g=this.filfoxMessageToEdgeTransaction(e,b)}const v=a===0?1:++s/a;t({tx:g,progress:v}),n.add(m.message)}}})}}var Ae=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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,r=this.ethEngine.walletLocalData.publicKey,a=[];let i;for(;;){const s=yield this.queryTransactions(r,i);if(a.push(...s.items),i=s.next_page_params,s.items.some(l=>l.block<=t)||i==null)break}const o=a.map(s=>this.processScanTransaction(s,n));return{tokenTxs:{[n]:{blockHeight:t,edgeTransactions:o}},server:this.config.servers.join(",")}})}processScanTransaction(e,t){const n=[],r=e.hash;if(r==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,s=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=s):e.from.hash.toLowerCase()===e.to.hash.toLowerCase()?(l=(0,c.sub)("0",s),u=s):(l=(0,c.sub)((0,c.sub)("0",e.value),s),u=s):(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:parseInt(e.timestamp),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:r,walletId:this.ethEngine.walletId}}queryTransactions(e,t){return Ae(this,null,function*(){return yield this.serialServers(n=>Ae(this,null,function*(){const r=`addresses/${e}/transactions`,a=t!=null?new URLSearchParams(t).toString():"",i=`${n}/api/v2/${r}?${a}`,s=yield(yield this.ethEngine.fetchCors(i,{method:"GET",headers:{"content-type":"application/json"}})).text();return St(s)}))})}}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=E(96519),Ft=E(2593),Lt=E(21046),xt=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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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:r,server:a}=yield this.serialServers(o=>W(this,null,function*(){const s=yield this.fetchPostRPC("eth_blockNumber",[],n,o);if(s.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${o} included an error ${JSON.stringify(s.error)}`),new Error("Successful eth_blockNumber response object included an error");return{server:ie()(o).hostname,result:s}}));return{blockHeight:Be(r).result,server:a}}),this.broadcast=n=>W(this,null,function*(){const{chainParams:{chainId:r}}=this.ethEngine.networkInfo;return yield this.parallelServers(a=>W(this,null,function*(){const i="eth_sendRawTransaction",o=[n.signedTx],s=yield this.fetchPostRPC(i,o,r,a),l=ie()(a,{},!0);return{result:this.broadcastResponseHandler(s,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(r=>W(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],n,r).then(a=>{if(a.error!=null){const o=`multicast get_baseFeePerGas error response from ${r}: ${JSON.stringify(a.error)}`;throw this.ethEngine.warn(o),new Error(o)}return a.result.baseFeePerGas})}))}),this.multicastRpc=(n,r)=>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,r,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`);return{server:ie()(i).hostname,result:o}}))}),this.fetchNonce=()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo,r=this.ethEngine.walletLocalData.publicKey,{result:a,server:i}=yield this.serialServers(s=>W(this,null,function*(){const l=yield this.fetchPostRPC("eth_getTransactionCount",[r,"latest"],n,s);if(l.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${s} included an error ${JSON.stringify(l.error)}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:ie()(s).hostname,result:l}})),o=(0,P.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:r}}=this.ethEngine.networkInfo;let a,i,o,s;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"],r,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,s=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,s=f.server}}a=(0,P.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:s}}),this.fetchTokenBalances=this.config.ethBalCheckerContract==null?null:()=>W(this,null,function*(){const{allTokensMap:n,networkInfo:r,walletLocalData:a,currencyInfo:i}=this.ethEngine,{chainParams:o}=r,s={},l=[],u=this.config.ethBalCheckerContract;if(u==null)return s;const h="0x0000000000000000000000000000000000000000",f=[h];for(const g of Object.values(this.ethEngine.allTokensMap)){const v=(0,H.Oj)(g.networkLocation);v!=null&&f.unshift(v.contractAddress)}const m=yield this.serialServers(g=>W(this,null,function*(){const v=new ee.r(g,o.chainId),w=yield new $e.CH(u,xt,v).balances([a.publicKey],f);if(w.length!==f.length)throw new Error("checkEthBalChecker balances length mismatch");return w})).catch(g=>{throw new Error(`All rpc servers failed eth balance checks: ${String(g)}`)});for(let g=0;g<m.length;g++){const v=f[g].toLowerCase(),b=Ft.O$.from(m[g]);let w;if(v===h){const{currencyCode:k}=i;w=k}else{const k=v.replace("0x","");b.gt(Lt._Y)&&l.push(k);const C=n[k];if(C==null){this.logError("checkEthBalChecker",new Error(`checkEthBalChecker missing builtinToken: ${v}`));continue}const{currencyCode:S}=C;w=S}s[w]=b.toString()}return{tokenBal:s,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 r=n[1],a=(0,P.jq)(r),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,r){return W(this,null,function*(){const a={id:n,jsonrpc:"2.0",method:e,params:t};r=this.addRpcApiKey(r);const i=yield this.ethEngine.fetchCors(r,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(a)}),o=ie()(r,{},!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,Ge=(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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.value).then(a,i);o((t=t.apply(d,e)).next())});const Gt=2e4,Ht=2e4,He=2e4,Mt=2e4,Kt=4*2,jt=2*60,Ie=(d,e,t,n)=>{let r={};return r=_t(Ge(Ge({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}),r};class Ut{constructor(e){this.multicastRpc=(t,n)=>J(this,null,function*(){const r=this.qualifyNetworkAdapters("multicastRpc").map(i=>()=>J(this,null,function*(){return yield i.multicastRpc(t,n)}));return yield(0,y.QJ)(r)}),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,r)=>{var a,i,o,s,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((s=n.detectedTokenIds)!=null?s:[]),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]=r,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 r=[];let a;const i=t!==this.ethEngine.currencyInfo.currencyCode,o=e.attributes.value,s=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=s: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,r.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 g,v="0";return i&&h?g=a:v=a,{blockHeight:m,currencyCode:t,date:e.attributes.blockCreationTime,isSend:n.startsWith("-"),memos:[],nativeAmount:n,networkFee:v,otherParams:f,ourReceiveAddresses:r,parentNetworkFee:g,signedTx:"",txid:e.relationships.transaction.data.id,walletId:this.walletId}}broadcastTx(e){return J(this,null,function*(){const t=this.qualifyNetworkAdapters("broadcast").map(r=>J(this,null,function*(){return yield r.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 r=this.ethEngine.getTokenInfo(n);if(r!=null){const a=r.contractAddress;if(e!=null&&typeof a=="string"&&a.toLowerCase()===e.toLowerCase())return n}}}checkAndUpdate(e,t,n,r){return J(this,null,function*(){const a=Date.now();if(a-e>t)try{const i=yield r();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,Gt,n,()=>J(this,null,function*(){return yield this.check("fetchBlockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Ht,n,()=>J(this,null,function*(){return yield this.check("fetchNonce")}));const{currencyCode:r}=this.ethEngine.currencyInfo,a=this.ethEngine.enabledTokens;a.includes(r)||a.push(r);const i=this.networkAdapters.find(o=>o.fetchTokenBalances!=null)!=null;i&&(yield this.checkAndUpdate(this.ethNeeds.tokenBalsLastChecked,He,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,He,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 s,l;const u=(s=this.ethEngine.walletLocalData.lastTransactionQueryHeight[o])!=null?s: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(r=>Xt(r,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=E(93901),Jt=E(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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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 r,a,i,o,s,l,u,h,f;let m=!0,g,v;const{customNetworkFee:b}=d!=null?d:{};if(d.networkFeeOption===Me&&b!=null){const{gasLimit:N,gasPrice:O}=b;if((isNaN(N)||N==="")&&(isNaN(O)||O==="")){const R=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw R.name="ErrorBelowMinimumFee",R}if(O!=null&&O!==""){const R=(o=(a=(r=e.default)==null?void 0:r.gasPrice)==null?void 0:a.minGasPrice)!=null?o:(i=n.defaultNetworkFees.default.gasPrice)==null?void 0:i.minGasPrice;if(R!=null){const j=(0,c.mul)(O,Ke);if((0,c.lt)(j,R)||/^\s*$/.test(O)){const fe=new Error(`Gas price ${j} wei below minimum ${R} wei`);throw fe.name="ErrorBelowMinimumFee",fe}}v=(0,c.mul)(O,Ke)}if(N!=null&&N!==""){const R=(h=(l=(s=e.default)==null?void 0:s.gasLimit)==null?void 0:l.minGasLimit)!=null?h:(u=n.defaultNetworkFees.default.gasLimit)==null?void 0:u.minGasLimit;if(R!=null&&(0,c.lt)(N,R)||/^\s*$/.test(N)){const j=new Error(`Gas limit ${N} below minimum ${R}`);throw j.name="ErrorBelowMinimumFee",j}g=N,m=!1}}if(g!=null&&v!=null)return{gasLimit:g,gasPrice:v,useEstimatedGasLimit:!1};let w=e.default,k=e.default;if(typeof((f=d.spendTargets[0])==null?void 0:f.publicAddress)=="string"){const N=(0,y.f0)(d.spendTargets[0].publicAddress);typeof e[N]<"u"&&(k=e[N],m=!1,typeof k.gasPrice<"u"&&(w=k))}let C="regularTransaction";d.currencyCode!=null&&d.currencyCode!==t.currencyCode&&(C="tokenTransaction");let S="standard";typeof d.networkFeeOption=="string"&&d.networkFeeOption!==Me&&(S=d.networkFeeOption);const G=k.gasLimit!=null?k.gasLimit[C]:"21000";let B="";if(d.spendTargets[0].nativeAmount==null)throw new Error("ErrorInvalidNativeAmount");let Q=d.spendTargets[0].nativeAmount;if(C==="tokenTransaction"&&(Q=(0,c.div)(Q,"10")),w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const x=w.gasPrice;switch(S){case Qt:B=x.lowFee;break;case Zt:{if((0,c.gte)(Q,w.gasPrice.standardFeeHighAmount)){B=x.standardFeeHigh;break}if((0,c.lte)(Q,x.standardFeeLowAmount)){if(w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");B=w.gasPrice.standardFeeLow;break}const N=(0,c.sub)(x.standardFeeHighAmount,x.standardFeeLowAmount),O=(0,c.sub)(x.standardFeeHigh,x.standardFeeLow),R=(0,c.sub)(Q,x.standardFeeLowAmount),j=(0,c.mul)(R,O),fe=(0,c.div)(j,N);B=(0,c.add)(x.standardFeeLow,fe);break}case zt:B=w.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:g!=null?g:G,gasPrice:v!=null?v:B,useEstimatedGasLimit:m}}const Yt="1040",Ue=d=>{const{chainParams:e,data:t,dynamicOverhead:n,fixedOverhead:r,gasPriceL1Wei:a,gasLimit:i,nonce:o,to:s,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:s,value:l,data:t===null?void 0:t},{common:u}).raw(),v=Xe(f).map(S=>S==null?"":Jt.YU.stringify(S).toLowerCase()).join().match(/(.{1,2})/g);if(v==null)throw new Error("Invalid rawTx string");let b=0;for(let S=0;S<v.length;S++)v[S]==="00"?b+=4:b+=16;const w=(0,c.add)((0,c.add)(b.toString(),r),Yt),k=(0,c.div)(n,"1000000",18);return(0,c.ceil)((0,c.mul)((0,c.mul)(a,w),k),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 r=(0,c.sub)(n,t);return(0,c.lte)(r,"0")&&(r=(0,c.div)(n,"10",0)),{gasPrice:(0,c.mul)("1",n,16),minerTip:(0,c.mul)("1",r,16)}}})}let Fe={destinationAddress:"",l1Gas:"0",l1GasPrice:"10000000000"};const Je=d=>Se(void 0,null,function*(){const{rpcServers:e,nodeInterfaceAddress:t,destinationAddress:n,txData:r}=d;if(n===Fe.destinationAddress)return{l1Gas:Fe.l1Gas,l1GasPrice:Fe.l1GasPrice};const a=o=>Se(void 0,null,function*(){const s=new Wt.c(o),u=yield new $e.CH(t,Vt,s).callStatic.gasEstimateL1Component(n,!1,r,{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=E(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)),xe=(d,e,t)=>on(nn(d),t,e),K=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.value).then(a,i);o((t=t.apply(d,e)).next())});class Ee extends re.P{constructor(e,t,n,r,a,i){super(e,t,n,a),this.updateNetworkFeesFromBaseFeePerGas=()=>K(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 g=this.networkInfo.defaultNetworkFees.default,v=m.default.minPriorityFee||g.minPriorityFee,b=(l=m.default.baseFeeMultiplier)!=null?l:g.baseFeeMultiplier;if(v==null||b==null)return;const w={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const k of Object.keys(b)){const C=(0,c.mul)(b[k],f),S=(0,c.add)(C,v);w[k]=(0,c.div)(S,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),Ce(this.log,w),w}),this.initOptions=r,this.networkInfo=e.networkInfo,this.ethNetwork=new Ut(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},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:s}=mt(this.fetchCors,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=o,this.externalFeeProviders=[...s,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=F().hashPersonalMessage(f),{v:g,r:v,s:b}=F().ecsign(m,h);return F().toRpcSig(g,v,b)},signTypedData:(l,u)=>{const h=ft(l),f=le.from(u.privateKey,"hex"),{types:m}=h;function g(x,$=[]){if($.includes(x)||m[x]===void 0)return $;$.push(x);for(const N of m[x])for(const O of g(N.type,$))$.includes(O)||$.push(O);return $}function v(x){let $=g(x);$=$.filter(O=>O!==x),$=[x].concat($.sort());let N="";for(const O of $)N+=`${O}(${m[O].map(({name:R,type:j})=>`${j} ${R}`).join(",")})`;return N}function b(x){return F().keccak256(v(x))}function w(x,$){const N=[],O=[];N.push("bytes32"),O.push(b(x));for(const R of m[x]){let j=$[R.name];if(R.type==="string"||R.type==="bytes")N.push("bytes32"),j=F().keccak256(j),O.push(j);else if(m[R.type]!==void 0)N.push("bytes32"),j=F().keccak256(w(R.type,j)),O.push(j);else{if(R.type.lastIndexOf("]")===R.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");N.push(R.type),O.push(j)}}return I().rawEncode(N,O)}function k(x,$){return F().keccak256(w(x,$))}function C(){return F().keccak256(le.concat([le.from("1901","hex"),k("EIP712Domain",h.domain),k(h.primaryType,h.message)]))}const S=F().ecsign(C(),f),{v:G,r:B,s:Q}=S;return F().bufferToHex(le.concat([F().setLengthLeft(B,32),F().setLengthLeft(Q,32),F().toBuffer(G)]))},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=>K(this,null,function*(){var u,h;try{let f="0",m="0";switch(l.method){case"eth_sendTransaction":case"eth_signTransaction":{const g=(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:v,gasPrice:b,value:w}=g,k=C=>{var S,G;v==null?g.gas=(0,y.X0)(C):C=(0,y.Z8)(v);let B=(G=(S=this.networkFees.default.gasPrice)==null?void 0:S.standardFeeHigh)!=null?G:"0";b==null?g.gasPrice=(0,y.X0)(B):B=(0,y.Z8)(b),m=(0,c.mul)(C,B)};w!=null&&(f=(0,y.Z8)(w)),((u=this.networkFees.default.gasLimit)==null?void 0:u.tokenTransaction)==null?this.ethNetwork.multicastRpc("eth_estimateGas",[g]).then(C=>{const S=(0,c.add)(parseInt(C.result.result,16).toString(),"0");k(S)}).catch(C=>{this.warn("Wallet connect call_request failed to get gas limit",C)}):k((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=>K(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(l)})}}estimateGasLimit(e){return K(this,null,function*(){var t,n;const{contractAddress:r,estimateGasParams:a,miningFees:i,publicAddress:o}=e,s=a[0].data!=null;if(this.lastEstimatedGasLimit.gasLimit!==""&&this.lastEstimatedGasLimit.publicAddress===o&&this.lastEstimatedGasLimit.contractAddress===r)return this.lastEstimatedGasLimit.gasLimit;let l=i.gasLimit;try{const h=(yield this.ethNetwork.multicastRpc("eth_getCode",[a[0].to,"latest"])).result.result!=="0x",f=(m=0)=>K(this,null,function*(){const g=this.networkInfo.defaultNetworkFees.default.gasLimit;try{if(g!=null&&!h&&!s)l=g.regularTransaction;else{const v=yield this.ethNetwork.multicastRpc("eth_estimateGas",a);l=(0,c.add)(parseInt(v.result.result,16).toString(),"0"),h&&(l=(0,c.mul)(l,"2"))}this.lastEstimatedGasLimit={publicAddress:o,contractAddress:r,gasLimit:l}}catch{if(g==null){if(m>5)throw new Error("Unable to estimate gas limit after 5 tries. Please try again later");return yield f(m+1)}if(s)throw new Error("Unable to estimate gas limit. Please try again later");g.tokenTransaction!=null&&(l=g.tokenTransaction)}});if(yield f(),(0,c.lt)(l,(n=(t=this.networkFees.default.gasLimit)==null?void 0:t.minGasLimit)!=null?n:"21000"))throw l=i.gasLimit,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum")}catch(u){this.error("makeSpend Error determining gas limit ",u)}return l})}setOtherData(e){this.otherData=(0,P.gF)(e)}updateNetworkFees(){return K(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const n={};Object.keys(t).forEach(r=>{const a=r;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 K(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,P.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,P.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 K(this,null,function*(){yield xe(Ee.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return K(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:we;this.infoFeeProvider().then(n=>K(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 r=yield this.ethNetwork.getBaseFeePerGas();if(r==null)return;this.networkFees.default.baseFee=r}catch(r){this.error(`Error fetching base fee: ${JSON.stringify(r)}`)}})).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(),xe(Ee.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return K(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return K(this,null,function*(){const{publicKey:e}=this.walletLocalData;return{publicAddress:/[A-F]/.test(e)?e:F().toChecksumAddress(e.replace("0x",""))}})}getMaxSpendable(e){return K(this,null,function*(){e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:t,currencyCode:n}=this.makeSpendCheck(e),r=this.getBalance({currencyCode:e.currencyCode}),i=e.spendTargets[0].publicAddress;if(i==null)throw new Error("makeSpend Missing publicAddress");const{contractAddress:o,data:s,value:l}=this.getTxParameterInformation(t,n,this.currencyInfo);if(e.currencyCode===this.currencyInfo.currencyCode){const u=(h,f)=>K(this,null,function*(){const m=(0,c.sub)(f,h);if((0,c.lte)(m,"1"))return h;const g=(0,c.add)(h,(0,c.div)(m,"2"));e.spendTargets[0].nativeAmount=g;const v=je(e,this.networkFees,this.currencyInfo,this.networkInfo);v.useEstimatedGasLimit&&(v.gasLimit=yield this.estimateGasLimit({contractAddress:o,estimateGasParams:[{to:o!=null?o:i,from:this.walletLocalData.publicKey,gas:"0xffffff",value:l,data:s},"latest"],miningFees:v,publicAddress:i}));const b=(0,c.mul)(v.gasPrice,v.gasLimit);let w="0";if(this.optimismRollupParams!=null){const C={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:v.gasLimit,to:i,value:(0,y.X0)(g),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};w=Ue(C)}else if(this.networkInfo.arbitrumRollupParams!=null){const C=this.ethNetwork.networkAdapters.filter(B=>B.config.type==="rpc").map(B=>B.config.servers).flat(),{l1Gas:S,l1GasPrice:G}=yield Je({destinationAddress:i,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:C,txData:s!=null?s:"0x"});w=(0,c.mul)((0,c.mul)(S,G),"1.1")}const k=(0,c.add)((0,c.add)(g,b),w);return(0,c.gt)(k,r)?yield u(h,g):yield u(g,f)});return yield u("0",(0,c.add)(r,"1"))}else return e.spendTargets[0].nativeAmount=r,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}getTxParameterInformation(e,t,n){var r;const{memos:a=[]}=e,{spendTargets:i}=e,o=i[0],{publicAddress:s,nativeAmount:l}=o;let u=((r=a[0])==null?void 0:r.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=s;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 g=I().simpleEncode("transfer(address,uint256):(uint256)",s,(0,y.X0)(l!=null?l:"0"));h="0x0",u="0x"+le.from(g).toString("hex")}return{contractAddress:f,data:u,value:h}}}makeSpend(e){return K(this,null,function*(){var t,n,r;e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:a,currencyCode:i,skipChecks:o}=this.makeSpendCheck(e),{memos:s=[]}=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 A.$D;if(!F().isValidAddress(h))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let m;const g=je(a,this.networkFees,this.currencyInfo,this.networkInfo),v=this.networkInfo.supportsEIP1559===!0?2:0,b=yield We(v,g.gasPrice,(t=this.networkFees.default.baseFee)!=null?t:yield this.ethNetwork.getBaseFeePerGas());let w;if(l.length>0){const O=this.walletLocalData.otherData,R=this.walletLocalData.numUnconfirmedSpendTxs>0?O.unconfirmedNextNonce:O.nextNonce;w=(0,c.add)(R,l.length.toString())}const{contractAddress:k,data:C,value:S}=this.getTxParameterInformation(a,i,this.currencyInfo);k==null?m=de(te({from:[this.walletLocalData.publicKey],to:[h]},b),{gas:g.gasLimit,gasUsed:"0",nonceUsed:w,data:C,isFromMakeSpend:!0}):m=de(te({from:[this.walletLocalData.publicKey],to:[k]},b),{gas:g.gasLimit,gasUsed:"0",tokenRecipientAddress:h,nonceUsed:w,data:C,isFromMakeSpend:!0}),g.useEstimatedGasLimit&&(m.gas=yield this.estimateGasLimit({contractAddress:k,estimateGasParams:[{to:k!=null?k:h,from:this.walletLocalData.publicKey,gas:"0xffffff",value:S,data:C},"latest"],miningFees:g,publicAddress:h}));const G=(n=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?n:"0";let B=(0,c.mul)(g.gasPrice,m.gas),Q="0",x=null,$="0";if(this.optimismRollupParams!=null){const O={nonce:m.nonceUsed,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:m.gas,to:m.to[0],value:S,data:m.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};$=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:R,l1GasPrice:j}=yield Je({destinationAddress:h,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:O,txData:C!=null?C:"0x"});$=(0,c.mul)((0,c.mul)(R,j),"1.1"),m.gas=(0,c.add)(m.gas,R)}if(i===this.currencyInfo.currencyCode){if(B=(0,c.add)(B,$),Q=(0,c.add)(B,f),!o&&(0,c.gt)(Q,G))throw new A.C_;f=(0,c.mul)(Q,"-1")}else{if(x=(0,c.add)(B,$),!o&&(0,c.gt)(x,G))throw new A.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:x});const O=(r=this.walletLocalData.totalBalances[i])!=null?r:"0";if(!o&&(0,c.gt)(f,O))throw new A.C_;B="0",f=(0,c.mul)(f,"-1")}const N={blockHeight:0,currencyCode:i,date:0,feeRateUsed:Ie(g.gasPrice,m.gas,void 0,b.minerTip),isSend:f.startsWith("-"),memos:s,nativeAmount:f,networkFee:B,otherParams:m,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return x&&(N.parentNetworkFee=x),N})}signMessage(e,t,n){return K(this,null,function*(){const r=(0,P.sh)(this.currencyInfo.pluginId)(t);if((0,P.TP)(n.otherParams).typedData){const i=JSON.parse(e);try{return this.utils.signTypedData(i,r)}catch{return(0,L.signTypedData_v4)(le.from(r.privateKey,"hex"),{data:i})}}return this.utils.signMessage(e,r)})}signTx(e,t){return K(this,null,function*(){const n=(0,P.sh)(this.currencyInfo.pluginId)(t),r=(0,y.Xp)(e),a=(0,y.NC)(r.gas);let i;if(e.currencyCode===this.currencyInfo.currencyCode){const C=(0,c.add)(e.nativeAmount,e.networkFee);i=(0,c.mul)("-1",C,16)}else i=(0,c.mul)("-1",e.nativeAmount,16);(0,c.lt)(i,"0")&&(i="0x00");let o=r.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 s=(0,y.NC)(o);let l;if(r.data!=null)l=r.data,e.currencyCode!==this.currencyInfo.currencyCode&&(i="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)l="";else{const C=I().simpleEncode("transfer(address,uint256):(uint256)",r.tokenRecipientAddress,i);l="0x"+le.from(C).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:r.gasPrice,maxPriorityFeePerGas:r.minerTip}:{gasPrice:r.gasPrice},g=de(te({nonce:s},m),{gasLimit:a,to:r.to[0],value:i,data:l,type:f}),v=le.from(n.privateKey,"hex"),b=Oe().fromPrivateKey(v);this.warn(`signTx getAddressString ${b.getAddressString()}`);const k=T.nL.fromTxData(g,{common:h}).sign(v);return e.signedTx=(0,y.dg)(k.serialize()),e.txid=(0,y.dg)(k.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=o),this.warn(`signTx
|
|
9
|
+
${JSON.stringify(v[b])}`),new Error(`getAllTxsEthscan ${n.name} is invalid`)}if(v.length===0)break;i++}return{allTransactions:o,server:s}})}processEvmScanTransaction(e,t){return V(this,null,function*(){var n;const r=[],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,s="gasPrice"in e?e.gasPrice:void 0,l=s!=null?(0,c.mul)(s,e.gasUsed):"0";let u="0";if(i&&this.ethEngine.networkInfo.optimismRollupParams!=null){const w=yield this.ethEngine.ethNetwork.multicastRpc("eth_getTransactionReceipt",[a]),k=(0,P.zv)(w.result.result);u=(0,c.add)(u,(0,y.X0)(k.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",r.push(this.ethEngine.walletLocalData.publicKey));const g={from:[e.from],to:[e.to],gas:e.gas,gasPrice:s!=null?s:"",gasUsed:e.gasUsed,isFromMakeSpend:!1};let v=parseInt(e.blockNumber);return v<0&&(v=0),{blockHeight:v,currencyCode:t,date:parseInt(e.timeStamp),feeRateUsed:s!=null?Ie(s,e.gas,e.gasUsed):void 0,isSend:h.startsWith("-"),memos:[],nativeAmount:h,networkFee:f,otherParams:g,ourReceiveAddresses:r,parentNetworkFee:m,signedTx:"",txid:a,walletId:this.ethEngine.walletId}})}}var bt=E(77258),me=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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=[],r=t.transfers.filter(o=>o.type==="miner-fee"||o.type==="burner-fee").reduce((o,s)=>(0,c.add)(o,s.value),"0");let a;return t.from===e?(a=`-${r}`,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:r,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:r}=yield this.ethEngine.getFreshAddress(),a=s=>{const l=this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode],u=s;l<1&&(u>=1||u>l*1.1)&&(this.ethEngine.tokenCheckTransactionsStatus[this.ethEngine.currencyInfo.currencyCode]=u,this.ethEngine.updateOnAddressesChecked())},i=({tx:s,progress:l})=>{s!=null&&(this.ethEngine.addTransaction(n,s),this.onUpdateTransactions(),this.ethEngine.walletLocalData.blockHeight<s.blockHeight&&this.onUpdateBlockHeight(s.blockHeight)),a(l)},o=[this.scanTransactionsFromFilfox(r,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),s=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,g=(l+1)*(i/f),v=yield this.serialServers(b=>me(this,null,function*(){return yield this.makeFilfoxApi(b).getAccountTransfers(e,g,f)}));h=[...h,...v.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 g;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 b=yield this.serialServers(w=>me(this,null,function*(){return yield this.makeFilfoxApi(w).getMessageDetails(m.message)}));g=this.filfoxMessageToEdgeTransaction(e,b)}const v=a===0?1:++s/a;t({tx:g,progress:v}),n.add(m.message)}}})}}var Ae=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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,r=this.ethEngine.walletLocalData.publicKey,a=[];let i;for(;;){const s=yield this.queryTransactions(r,i);if(a.push(...s.items),i=s.next_page_params,s.items.some(l=>l.block<=t)||i==null)break}const o=a.map(s=>this.processScanTransaction(s,n));return{tokenTxs:{[n]:{blockHeight:t,edgeTransactions:o}},server:this.config.servers.join(",")}})}processScanTransaction(e,t){const n=[],r=e.hash;if(r==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,s=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=s):e.from.hash.toLowerCase()===e.to.hash.toLowerCase()?(l=(0,c.sub)("0",s),u=s):(l=(0,c.sub)((0,c.sub)("0",e.value),s),u=s):(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:r,walletId:this.ethEngine.walletId}}queryTransactions(e,t){return Ae(this,null,function*(){return yield this.serialServers(n=>Ae(this,null,function*(){const r=`addresses/${e}/transactions`,a=t!=null?new URLSearchParams(t).toString():"",i=`${n}/api/v2/${r}?${a}`,s=yield(yield this.ethEngine.fetchCors(i,{method:"GET",headers:{"content-type":"application/json"}})).text();return St(s)}))})}}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=E(96519),Ft=E(2593),Lt=E(21046),xt=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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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:r,server:a}=yield this.serialServers(o=>W(this,null,function*(){const s=yield this.fetchPostRPC("eth_blockNumber",[],n,o);if(s.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${o} included an error ${JSON.stringify(s.error)}`),new Error("Successful eth_blockNumber response object included an error");return{server:ie()(o).hostname,result:s}}));return{blockHeight:Be(r).result,server:a}}),this.broadcast=n=>W(this,null,function*(){const{chainParams:{chainId:r}}=this.ethEngine.networkInfo;return yield this.parallelServers(a=>W(this,null,function*(){const i="eth_sendRawTransaction",o=[n.signedTx],s=yield this.fetchPostRPC(i,o,r,a),l=ie()(a,{},!0);return{result:this.broadcastResponseHandler(s,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(r=>W(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],n,r).then(a=>{if(a.error!=null){const o=`multicast get_baseFeePerGas error response from ${r}: ${JSON.stringify(a.error)}`;throw this.ethEngine.warn(o),new Error(o)}return a.result.baseFeePerGas})}))}),this.multicastRpc=(n,r)=>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,r,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`);return{server:ie()(i).hostname,result:o}}))}),this.fetchNonce=()=>W(this,null,function*(){const{chainParams:{chainId:n}}=this.ethEngine.networkInfo,r=this.ethEngine.walletLocalData.publicKey,{result:a,server:i}=yield this.serialServers(s=>W(this,null,function*(){const l=yield this.fetchPostRPC("eth_getTransactionCount",[r,"latest"],n,s);if(l.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${s} included an error ${JSON.stringify(l.error)}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:ie()(s).hostname,result:l}})),o=(0,P.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:r}}=this.ethEngine.networkInfo;let a,i,o,s;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"],r,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,s=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,s=f.server}}a=(0,P.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:s}}),this.fetchTokenBalances=this.config.ethBalCheckerContract==null?null:()=>W(this,null,function*(){const{allTokensMap:n,networkInfo:r,walletLocalData:a,currencyInfo:i}=this.ethEngine,{chainParams:o}=r,s={},l=[],u=this.config.ethBalCheckerContract;if(u==null)return s;const h="0x0000000000000000000000000000000000000000",f=[h];for(const g of Object.values(this.ethEngine.allTokensMap)){const v=(0,H.Oj)(g.networkLocation);v!=null&&f.unshift(v.contractAddress)}const m=yield this.serialServers(g=>W(this,null,function*(){const v=new ee.r(g,o.chainId),w=yield new $e.CH(u,xt,v).balances([a.publicKey],f);if(w.length!==f.length)throw new Error("checkEthBalChecker balances length mismatch");return w})).catch(g=>{throw new Error(`All rpc servers failed eth balance checks: ${String(g)}`)});for(let g=0;g<m.length;g++){const v=f[g].toLowerCase(),b=Ft.O$.from(m[g]);let w;if(v===h){const{currencyCode:k}=i;w=k}else{const k=v.replace("0x","");b.gt(Lt._Y)&&l.push(k);const C=n[k];if(C==null){this.logError("checkEthBalChecker",new Error(`checkEthBalChecker missing builtinToken: ${v}`));continue}const{currencyCode:S}=C;w=S}s[w]=b.toString()}return{tokenBal:s,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 r=n[1],a=(0,P.jq)(r),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,r){return W(this,null,function*(){const a={id:n,jsonrpc:"2.0",method:e,params:t};r=this.addRpcApiKey(r);const i=yield this.ethEngine.fetchCors(r,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(a)}),o=ie()(r,{},!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,Ge=(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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.value).then(a,i);o((t=t.apply(d,e)).next())});const Gt=2e4,Ht=2e4,He=2e4,Mt=2e4,Kt=4*2,jt=2*60,Ie=(d,e,t,n)=>{let r={};return r=_t(Ge(Ge({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}),r};class Ut{constructor(e){this.multicastRpc=(t,n)=>J(this,null,function*(){const r=this.qualifyNetworkAdapters("multicastRpc").map(i=>()=>J(this,null,function*(){return yield i.multicastRpc(t,n)}));return yield(0,y.QJ)(r)}),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,r)=>{var a,i,o,s,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((s=n.detectedTokenIds)!=null?s:[]),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]=r,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 r=[];let a;const i=t!==this.ethEngine.currencyInfo.currencyCode,o=e.attributes.value,s=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=s: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,r.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 g,v="0";return i&&h?g=a:v=a,{blockHeight:m,currencyCode:t,date:e.attributes.blockCreationTime,isSend:n.startsWith("-"),memos:[],nativeAmount:n,networkFee:v,otherParams:f,ourReceiveAddresses:r,parentNetworkFee:g,signedTx:"",txid:e.relationships.transaction.data.id,walletId:this.walletId}}broadcastTx(e){return J(this,null,function*(){const t=this.qualifyNetworkAdapters("broadcast").map(r=>J(this,null,function*(){return yield r.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 r=this.ethEngine.getTokenInfo(n);if(r!=null){const a=r.contractAddress;if(e!=null&&typeof a=="string"&&a.toLowerCase()===e.toLowerCase())return n}}}checkAndUpdate(e,t,n,r){return J(this,null,function*(){const a=Date.now();if(a-e>t)try{const i=yield r();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,Gt,n,()=>J(this,null,function*(){return yield this.check("fetchBlockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Ht,n,()=>J(this,null,function*(){return yield this.check("fetchNonce")}));const{currencyCode:r}=this.ethEngine.currencyInfo,a=this.ethEngine.enabledTokens;a.includes(r)||a.push(r);const i=this.networkAdapters.find(o=>o.fetchTokenBalances!=null)!=null;i&&(yield this.checkAndUpdate(this.ethNeeds.tokenBalsLastChecked,He,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,He,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 s,l;const u=(s=this.ethEngine.walletLocalData.lastTransactionQueryHeight[o])!=null?s: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(r=>Xt(r,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=E(93901),Jt=E(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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.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 r,a,i,o,s,l,u,h,f;let m=!0,g,v;const{customNetworkFee:b}=d!=null?d:{};if(d.networkFeeOption===Me&&b!=null){const{gasLimit:N,gasPrice:O}=b;if((isNaN(N)||N==="")&&(isNaN(O)||O==="")){const R=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw R.name="ErrorBelowMinimumFee",R}if(O!=null&&O!==""){const R=(o=(a=(r=e.default)==null?void 0:r.gasPrice)==null?void 0:a.minGasPrice)!=null?o:(i=n.defaultNetworkFees.default.gasPrice)==null?void 0:i.minGasPrice;if(R!=null){const j=(0,c.mul)(O,Ke);if((0,c.lt)(j,R)||/^\s*$/.test(O)){const fe=new Error(`Gas price ${j} wei below minimum ${R} wei`);throw fe.name="ErrorBelowMinimumFee",fe}}v=(0,c.mul)(O,Ke)}if(N!=null&&N!==""){const R=(h=(l=(s=e.default)==null?void 0:s.gasLimit)==null?void 0:l.minGasLimit)!=null?h:(u=n.defaultNetworkFees.default.gasLimit)==null?void 0:u.minGasLimit;if(R!=null&&(0,c.lt)(N,R)||/^\s*$/.test(N)){const j=new Error(`Gas limit ${N} below minimum ${R}`);throw j.name="ErrorBelowMinimumFee",j}g=N,m=!1}}if(g!=null&&v!=null)return{gasLimit:g,gasPrice:v,useEstimatedGasLimit:!1};let w=e.default,k=e.default;if(typeof((f=d.spendTargets[0])==null?void 0:f.publicAddress)=="string"){const N=(0,y.f0)(d.spendTargets[0].publicAddress);typeof e[N]<"u"&&(k=e[N],m=!1,typeof k.gasPrice<"u"&&(w=k))}let C="regularTransaction";d.currencyCode!=null&&d.currencyCode!==t.currencyCode&&(C="tokenTransaction");let S="standard";typeof d.networkFeeOption=="string"&&d.networkFeeOption!==Me&&(S=d.networkFeeOption);const G=k.gasLimit!=null?k.gasLimit[C]:"21000";let B="";if(d.spendTargets[0].nativeAmount==null)throw new Error("ErrorInvalidNativeAmount");let Q=d.spendTargets[0].nativeAmount;if(C==="tokenTransaction"&&(Q=(0,c.div)(Q,"10")),w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const x=w.gasPrice;switch(S){case Qt:B=x.lowFee;break;case Zt:{if((0,c.gte)(Q,w.gasPrice.standardFeeHighAmount)){B=x.standardFeeHigh;break}if((0,c.lte)(Q,x.standardFeeLowAmount)){if(w.gasPrice==null)throw new Error("ErrorInvalidGasPrice");B=w.gasPrice.standardFeeLow;break}const N=(0,c.sub)(x.standardFeeHighAmount,x.standardFeeLowAmount),O=(0,c.sub)(x.standardFeeHigh,x.standardFeeLow),R=(0,c.sub)(Q,x.standardFeeLowAmount),j=(0,c.mul)(R,O),fe=(0,c.div)(j,N);B=(0,c.add)(x.standardFeeLow,fe);break}case zt:B=w.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:g!=null?g:G,gasPrice:v!=null?v:B,useEstimatedGasLimit:m}}const Yt="1040",Ue=d=>{const{chainParams:e,data:t,dynamicOverhead:n,fixedOverhead:r,gasPriceL1Wei:a,gasLimit:i,nonce:o,to:s,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:s,value:l,data:t===null?void 0:t},{common:u}).raw(),v=Xe(f).map(S=>S==null?"":Jt.YU.stringify(S).toLowerCase()).join().match(/(.{1,2})/g);if(v==null)throw new Error("Invalid rawTx string");let b=0;for(let S=0;S<v.length;S++)v[S]==="00"?b+=4:b+=16;const w=(0,c.add)((0,c.add)(b.toString(),r),Yt),k=(0,c.div)(n,"1000000",18);return(0,c.ceil)((0,c.mul)((0,c.mul)(a,w),k),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 r=(0,c.sub)(n,t);return(0,c.lte)(r,"0")&&(r=(0,c.div)(n,"10",0)),{gasPrice:(0,c.mul)("1",n,16),minerTip:(0,c.mul)("1",r,16)}}})}let Fe={destinationAddress:"",l1Gas:"0",l1GasPrice:"10000000000"};const Je=d=>Se(void 0,null,function*(){const{rpcServers:e,nodeInterfaceAddress:t,destinationAddress:n,txData:r}=d;if(n===Fe.destinationAddress)return{l1Gas:Fe.l1Gas,l1GasPrice:Fe.l1GasPrice};const a=o=>Se(void 0,null,function*(){const s=new Wt.c(o),u=yield new $e.CH(t,Vt,s).callStatic.gasEstimateL1Component(n,!1,r,{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=E(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)),xe=(d,e,t)=>on(nn(d),t,e),K=(d,e,t)=>new Promise((n,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.value).then(a,i);o((t=t.apply(d,e)).next())});class Ee extends re.P{constructor(e,t,n,r,a,i){super(e,t,n,a),this.updateNetworkFeesFromBaseFeePerGas=()=>K(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 g=this.networkInfo.defaultNetworkFees.default,v=m.default.minPriorityFee||g.minPriorityFee,b=(l=m.default.baseFeeMultiplier)!=null?l:g.baseFeeMultiplier;if(v==null||b==null)return;const w={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const k of Object.keys(b)){const C=(0,c.mul)(b[k],f),S=(0,c.add)(C,v);w[k]=(0,c.div)(S,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),Ce(this.log,w),w}),this.initOptions=r,this.networkInfo=e.networkInfo,this.ethNetwork=new Ut(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},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:s}=mt(this.fetchCors,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=o,this.externalFeeProviders=[...s,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=F().hashPersonalMessage(f),{v:g,r:v,s:b}=F().ecsign(m,h);return F().toRpcSig(g,v,b)},signTypedData:(l,u)=>{const h=ft(l),f=le.from(u.privateKey,"hex"),{types:m}=h;function g(x,$=[]){if($.includes(x)||m[x]===void 0)return $;$.push(x);for(const N of m[x])for(const O of g(N.type,$))$.includes(O)||$.push(O);return $}function v(x){let $=g(x);$=$.filter(O=>O!==x),$=[x].concat($.sort());let N="";for(const O of $)N+=`${O}(${m[O].map(({name:R,type:j})=>`${j} ${R}`).join(",")})`;return N}function b(x){return F().keccak256(v(x))}function w(x,$){const N=[],O=[];N.push("bytes32"),O.push(b(x));for(const R of m[x]){let j=$[R.name];if(R.type==="string"||R.type==="bytes")N.push("bytes32"),j=F().keccak256(j),O.push(j);else if(m[R.type]!==void 0)N.push("bytes32"),j=F().keccak256(w(R.type,j)),O.push(j);else{if(R.type.lastIndexOf("]")===R.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");N.push(R.type),O.push(j)}}return I().rawEncode(N,O)}function k(x,$){return F().keccak256(w(x,$))}function C(){return F().keccak256(le.concat([le.from("1901","hex"),k("EIP712Domain",h.domain),k(h.primaryType,h.message)]))}const S=F().ecsign(C(),f),{v:G,r:B,s:Q}=S;return F().bufferToHex(le.concat([F().setLengthLeft(B,32),F().setLengthLeft(Q,32),F().toBuffer(G)]))},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=>K(this,null,function*(){var u,h;try{let f="0",m="0";switch(l.method){case"eth_sendTransaction":case"eth_signTransaction":{const g=(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:v,gasPrice:b,value:w}=g,k=C=>{var S,G;v==null?g.gas=(0,y.X0)(C):C=(0,y.Z8)(v);let B=(G=(S=this.networkFees.default.gasPrice)==null?void 0:S.standardFeeHigh)!=null?G:"0";b==null?g.gasPrice=(0,y.X0)(B):B=(0,y.Z8)(b),m=(0,c.mul)(C,B)};w!=null&&(f=(0,y.Z8)(w)),((u=this.networkFees.default.gasLimit)==null?void 0:u.tokenTransaction)==null?this.ethNetwork.multicastRpc("eth_estimateGas",[g]).then(C=>{const S=(0,c.add)(parseInt(C.result.result,16).toString(),"0");k(S)}).catch(C=>{this.warn("Wallet connect call_request failed to get gas limit",C)}):k((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=>K(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(l)})}}estimateGasLimit(e){return K(this,null,function*(){var t,n;const{contractAddress:r,estimateGasParams:a,miningFees:i,publicAddress:o}=e,s=a[0].data!=null;if(this.lastEstimatedGasLimit.gasLimit!==""&&this.lastEstimatedGasLimit.publicAddress===o&&this.lastEstimatedGasLimit.contractAddress===r)return this.lastEstimatedGasLimit.gasLimit;let l=i.gasLimit;try{const h=(yield this.ethNetwork.multicastRpc("eth_getCode",[a[0].to,"latest"])).result.result!=="0x",f=(m=0)=>K(this,null,function*(){const g=this.networkInfo.defaultNetworkFees.default.gasLimit;try{if(g!=null&&!h&&!s)l=g.regularTransaction;else{const v=yield this.ethNetwork.multicastRpc("eth_estimateGas",a);l=(0,c.add)(parseInt(v.result.result,16).toString(),"0"),h&&(l=(0,c.mul)(l,"2"))}this.lastEstimatedGasLimit={publicAddress:o,contractAddress:r,gasLimit:l}}catch{if(g==null){if(m>5)throw new Error("Unable to estimate gas limit after 5 tries. Please try again later");return yield f(m+1)}if(s)throw new Error("Unable to estimate gas limit. Please try again later");g.tokenTransaction!=null&&(l=g.tokenTransaction)}});if(yield f(),(0,c.lt)(l,(n=(t=this.networkFees.default.gasLimit)==null?void 0:t.minGasLimit)!=null?n:"21000"))throw l=i.gasLimit,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum")}catch(u){this.error("makeSpend Error determining gas limit ",u)}return l})}setOtherData(e){this.otherData=(0,P.gF)(e)}updateNetworkFees(){return K(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const n={};Object.keys(t).forEach(r=>{const a=r;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 K(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,P.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,P.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 K(this,null,function*(){yield xe(Ee.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0"})}startEngine(){return K(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:we;this.infoFeeProvider().then(n=>K(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 r=yield this.ethNetwork.getBaseFeePerGas();if(r==null)return;this.networkFees.default.baseFee=r}catch(r){this.error(`Error fetching base fee: ${JSON.stringify(r)}`)}})).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(),xe(Ee.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return K(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return K(this,null,function*(){const{publicKey:e}=this.walletLocalData;return{publicAddress:/[A-F]/.test(e)?e:F().toChecksumAddress(e.replace("0x",""))}})}getMaxSpendable(e){return K(this,null,function*(){e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:t,currencyCode:n}=this.makeSpendCheck(e),r=this.getBalance({currencyCode:e.currencyCode}),i=e.spendTargets[0].publicAddress;if(i==null)throw new Error("makeSpend Missing publicAddress");const{contractAddress:o,data:s,value:l}=this.getTxParameterInformation(t,n,this.currencyInfo);if(e.currencyCode===this.currencyInfo.currencyCode){const u=(h,f)=>K(this,null,function*(){const m=(0,c.sub)(f,h);if((0,c.lte)(m,"1"))return h;const g=(0,c.add)(h,(0,c.div)(m,"2"));e.spendTargets[0].nativeAmount=g;const v=je(e,this.networkFees,this.currencyInfo,this.networkInfo);v.useEstimatedGasLimit&&(v.gasLimit=yield this.estimateGasLimit({contractAddress:o,estimateGasParams:[{to:o!=null?o:i,from:this.walletLocalData.publicKey,gas:"0xffffff",value:l,data:s},"latest"],miningFees:v,publicAddress:i}));const b=(0,c.mul)(v.gasPrice,v.gasLimit);let w="0";if(this.optimismRollupParams!=null){const C={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:v.gasLimit,to:i,value:(0,y.X0)(g),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};w=Ue(C)}else if(this.networkInfo.arbitrumRollupParams!=null){const C=this.ethNetwork.networkAdapters.filter(B=>B.config.type==="rpc").map(B=>B.config.servers).flat(),{l1Gas:S,l1GasPrice:G}=yield Je({destinationAddress:i,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:C,txData:s!=null?s:"0x"});w=(0,c.mul)((0,c.mul)(S,G),"1.1")}const k=(0,c.add)((0,c.add)(g,b),w);return(0,c.gt)(k,r)?yield u(h,g):yield u(g,f)});return yield u("0",(0,c.add)(r,"1"))}else return e.spendTargets[0].nativeAmount=r,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}getTxParameterInformation(e,t,n){var r;const{memos:a=[]}=e,{spendTargets:i}=e,o=i[0],{publicAddress:s,nativeAmount:l}=o;let u=((r=a[0])==null?void 0:r.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=s;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 g=I().simpleEncode("transfer(address,uint256):(uint256)",s,(0,y.X0)(l!=null?l:"0"));h="0x0",u="0x"+le.from(g).toString("hex")}return{contractAddress:f,data:u,value:h}}}makeSpend(e){return K(this,null,function*(){var t,n,r;e=(0,ve.s)(e,this.currencyInfo);const{edgeSpendInfo:a,currencyCode:i,skipChecks:o}=this.makeSpendCheck(e),{memos:s=[]}=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 A.$D;if(!F().isValidAddress(h))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let m;const g=je(a,this.networkFees,this.currencyInfo,this.networkInfo),v=this.networkInfo.supportsEIP1559===!0?2:0,b=yield We(v,g.gasPrice,(t=this.networkFees.default.baseFee)!=null?t:yield this.ethNetwork.getBaseFeePerGas());let w;if(l.length>0){const O=this.walletLocalData.otherData,R=this.walletLocalData.numUnconfirmedSpendTxs>0?O.unconfirmedNextNonce:O.nextNonce;w=(0,c.add)(R,l.length.toString())}const{contractAddress:k,data:C,value:S}=this.getTxParameterInformation(a,i,this.currencyInfo);k==null?m=de(te({from:[this.walletLocalData.publicKey],to:[h]},b),{gas:g.gasLimit,gasUsed:"0",nonceUsed:w,data:C,isFromMakeSpend:!0}):m=de(te({from:[this.walletLocalData.publicKey],to:[k]},b),{gas:g.gasLimit,gasUsed:"0",tokenRecipientAddress:h,nonceUsed:w,data:C,isFromMakeSpend:!0}),g.useEstimatedGasLimit&&(m.gas=yield this.estimateGasLimit({contractAddress:k,estimateGasParams:[{to:k!=null?k:h,from:this.walletLocalData.publicKey,gas:"0xffffff",value:S,data:C},"latest"],miningFees:g,publicAddress:h}));const G=(n=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?n:"0";let B=(0,c.mul)(g.gasPrice,m.gas),Q="0",x=null,$="0";if(this.optimismRollupParams!=null){const O={nonce:m.nonceUsed,gasPriceL1Wei:this.optimismRollupParams.gasPriceL1Wei,gasLimit:m.gas,to:m.to[0],value:S,data:m.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.optimismRollupParams.dynamicOverhead,fixedOverhead:this.optimismRollupParams.fixedOverhead};$=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:R,l1GasPrice:j}=yield Je({destinationAddress:h,nodeInterfaceAddress:this.networkInfo.arbitrumRollupParams.nodeInterfaceAddress,rpcServers:O,txData:C!=null?C:"0x"});$=(0,c.mul)((0,c.mul)(R,j),"1.1"),m.gas=(0,c.add)(m.gas,R)}if(i===this.currencyInfo.currencyCode){if(B=(0,c.add)(B,$),Q=(0,c.add)(B,f),!o&&(0,c.gt)(Q,G))throw new A.C_;f=(0,c.mul)(Q,"-1")}else{if(x=(0,c.add)(B,$),!o&&(0,c.gt)(x,G))throw new A.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:x});const O=(r=this.walletLocalData.totalBalances[i])!=null?r:"0";if(!o&&(0,c.gt)(f,O))throw new A.C_;B="0",f=(0,c.mul)(f,"-1")}const N={blockHeight:0,currencyCode:i,date:0,feeRateUsed:Ie(g.gasPrice,m.gas,void 0,b.minerTip),isSend:f.startsWith("-"),memos:s,nativeAmount:f,networkFee:B,otherParams:m,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return x&&(N.parentNetworkFee=x),N})}signMessage(e,t,n){return K(this,null,function*(){const r=(0,P.sh)(this.currencyInfo.pluginId)(t);if((0,P.TP)(n.otherParams).typedData){const i=JSON.parse(e);try{return this.utils.signTypedData(i,r)}catch{return(0,L.signTypedData_v4)(le.from(r.privateKey,"hex"),{data:i})}}return this.utils.signMessage(e,r)})}signTx(e,t){return K(this,null,function*(){const n=(0,P.sh)(this.currencyInfo.pluginId)(t),r=(0,y.Xp)(e),a=(0,y.NC)(r.gas);let i;if(e.currencyCode===this.currencyInfo.currencyCode){const C=(0,c.add)(e.nativeAmount,e.networkFee);i=(0,c.mul)("-1",C,16)}else i=(0,c.mul)("-1",e.nativeAmount,16);(0,c.lt)(i,"0")&&(i="0x00");let o=r.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 s=(0,y.NC)(o);let l;if(r.data!=null)l=r.data,e.currencyCode!==this.currencyInfo.currencyCode&&(i="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)l="";else{const C=I().simpleEncode("transfer(address,uint256):(uint256)",r.tokenRecipientAddress,i);l="0x"+le.from(C).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:r.gasPrice,maxPriorityFeePerGas:r.minerTip}:{gasPrice:r.gasPrice},g=de(te({nonce:s},m),{gasLimit:a,to:r.to[0],value:i,data:l,type:f}),v=le.from(n.privateKey,"hex"),b=Oe().fromPrivateKey(v);this.warn(`signTx getAddressString ${b.getAddressString()}`);const k=T.nL.fromTxData(g,{common:h}).sign(v);return e.signedTx=(0,y.dg)(k.serialize()),e.txid=(0,y.dg)(k.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 K(this,null,function*(){return yield this.ethNetwork.broadcastTx(e),this.warn(`SUCCESS broadcastTx
|
|
11
11
|
${(0,y.oX)(e)}`),e})}accelerate(e){return K(this,null,function*(){var t,n,r,a;const{currencyCode:i}=e,o=(0,p.Vk)(P.Al)(e.otherParams);let s=e.txid,l=yield this.findTransaction(i,(0,y.f0)(s));if(l===-1&&((o==null?void 0:o.replacedTxid)!=null&&o.replacedTxid!==""&&(s=o.replacedTxid,l=yield this.findTransaction(i,(0,y.f0)(s))),l===-1))return null;const u=this.transactionList[i][l],h=(0,p.Vk)(P.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,g=yield We(m,(0,c.mul)(h.gasPrice,"2"),(n=this.networkFees.default.baseFee)!=null?n:yield this.ethNetwork.getBaseFeePerGas()),v=h.gas,b=de(te(te({},h),g),{gas:v,replacedTxid:s});let{nativeAmount:w}=f,k=(0,c.mul)(g.gasPrice,v),C="0",S;const G=(r=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?r:"0";if(i===this.currencyInfo.currencyCode){if(C=(0,c.add)(k,w),(0,c.gt)(C,G))throw new A.C_;w=(0,c.mul)(C,"-1")}else{if(S=k,(0,c.gt)(k,G))throw new A.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:k});const B=(a=this.walletLocalData.totalBalances[i])!=null?a:"0";if((0,c.gt)(w,B))throw new A.C_;k="0",w=(0,c.mul)(w,"-1")}return de(te({},e),{txid:"",feeRateUsed:Ie(g.gasPrice,v,h.gasUsed,g.minerTip),nativeAmount:w,networkFee:k,otherParams:b,parentNetworkFee:S})})}saveTx(e){return K(this,null,function*(){var t;const n=(0,p.Vk)(P.Al)(e.otherParams);if((n==null?void 0:n.replacedTxid)!=null){const{currencyCode:r}=e,a=(0,y.f0)(n.replacedTxid),i=this.findTransaction(r,a);if(i!==-1){const o=this.transactionList[r][i],s=e.metadata,l=de(te({},o),{metadata:s,blockHeight:-1});this.addTransaction(r,l)}}if(e.blockHeight===0){const r=(t=e.otherParams)==null?void 0:t.nonceUsed;r!=null&&(this.otherData.unconfirmedNextNonce=(0,c.add)(r,"1"))}xe(Ee.prototype,this,"saveTx").call(this,e)})}}function an(d,e,t,n){return K(this,null,function*(){const{currencyInfo:r,initOptions:a}=d,i=(0,P.VX)(t),o=new Ee(d,e,i,(0,P.dp)(a),n,r);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,r)=>{var a=s=>{try{o(t.next(s))}catch(l){r(l)}},i=s=>{try{o(t.throw(s))}catch(l){r(l)}},o=s=>s.done?n(s.value):Promise.resolve(s.value).then(a,i);o((t=t.apply(d,e)).next())});class et{constructor(e){const{builtinTokens:t,currencyInfo:n,io:r,networkInfo:a,initOptions:i}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=r,this.networkInfo=a,this.initOptions=i}getDisplayPrivateKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo;return(0,P.sh)(t)(e.keys).privateKey})}getDisplayPublicKey(e){return q(this,null,function*(){const{keys:t}=(0,P.VX)(e);return t.publicKey})}importPrivateKey(e){return q(this,null,function*(){const{pluginId:t}=this.currencyInfo,{pluginMnemonicKeyName:n,pluginRegularKeyName:r}=this.networkInfo;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const a=Z.Buffer.from(e.replace(/^0x/,""),"hex");if(!F().isValidPrivate(a))throw new Error("Invalid private key");const i=a.toString("hex"),o={[r]: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,[r]: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:r,pluginRegularKeyName:a}=this.networkInfo;if(e.type!==`wallet:${t}`)throw new Error("Invalid wallet type");let i;if(e.keys[r]!=null){const o=(0,X.mnemonicToSeedSync)(e.keys[r]),s=se().fromMasterSeed(o),l=`m/44'/${n}'/0'/0`,f=s.derivePath(`${l}/0`).getWallet().getPublicKey(),m=F().pubToAddress(f).toString("hex");i=F().toChecksumAddress(m)}else{const o=Z.Buffer.from(e.keys[a].replace(/^0x/,""),"hex");if(!F().isValidPrivate(o))throw new Error("Invalid private key");i=`0x${F().privateToAddress(o).toString("hex")}`}if(!F().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)),r=`m/44'/${t}'/0'/0`;return n.derivePath(`${r}/0`).getWallet().getPrivateKeyString().replace(/^0x/,"")})}parseUri(e,t,n){return q(this,null,function*(){var r,a,i,o,s;const l={};this.networkInfo.uriNetworks.forEach(v=>{l[v]=!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,g]=f.split("-");if(g||(g=m,m="pay"),f=g,/[A-F]/.test(f)&&!F().isValidChecksumAddress(f))throw new Error("InvalidPublicAddressError");if(f=f.toLowerCase(),!F().isValidAddress(f||""))throw new Error("InvalidPublicAddressError");if(m==="token"||m==="token_info"){if(!u.query)throw new Error("InvalidUriError");const v=(r=u.query.symbol)!=null?r:"SYM";if(v.length<2||v.length>5)throw new Error("Wrong Token symbol");const b=(a=u.query.name)!=null?a:v,w=(i=u.query.decimals)!=null?i:"18";let k="1000000000000000000";const C=parseInt(w);if(C<0||C>18)throw new Error("Wrong number of decimals");k="1"+"0".repeat(C);const S=(o=u.query.type)!=null?o:this.networkInfo.ercTokenStandard;return{token:{currencyCode:v,contractAddress:g.toLowerCase(),currencyName:b,multiplier:k,denominations:[{name:v,multiplier:k}],type:S.toUpperCase()}}}if(m==="pay"){const v=f,b=u.pathname.split("/")[1],w=u.query;switch(b){case"transfer":{const k=(s=w.address)!=null?s:"",C=v!=null?v:"",S=w.uint256!=null?(0,y.EE)(w.uint256):h.nativeAmount,G=this.currencyInfo.metaTokens.find(B=>B.contractAddress===C);if(t!=null&&(G==null||G.currencyCode!==t))throw new Error("InternalErrorInvalidCurrencyCode");if(!F().isValidAddress(k))throw new Error("InvalidPublicAddressError");if(!F().isValidAddress(C))throw new Error("InvalidContractAddressError");return qe(Ye({},h),{currencyCode:G==null?void 0:G.currencyCode,nativeAmount:S,publicAddress:k})}case void 0:{const k=v,C=w.value!=null?(0,y.EE)(w.value):h.nativeAmount;return qe(Ye({},h),{publicAddress:k,nativeAmount:C})}default:throw new Error("UnsupportedContractFunction")}}throw new Error("InvalidUriError")})}encodeUri(e){return q(this,arguments,function*(t,n=[]){const{publicAddress:r,nativeAmount:a,currencyCode:i}=t;if(!F().isValidAddress(r))throw new Error("InvalidPublicAddressError");let s;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");s=(0,c.div)(a,u.multiplier,18)}return(0,_.Q)(t,this.currencyInfo.pluginId,s)})}getSplittableTypes(e){return Object.keys(M.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||!F().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(ke,ne,E){"use strict";E.d(ne,{V7:function(){return y}});var c=E(82448),X=(M,P,D)=>new Promise((T,p)=>{var A=I=>{try{U(D.next(I))}catch(oe){p(oe)}},L=I=>{try{U(D.throw(I))}catch(oe){p(oe)}},U=I=>I.done?T(I.value):Promise.resolve(I.value).then(A,L);U((D=D.apply(M,P)).next())});const Z=(0,c.su)({statusCode:c.mH,message:c.XC,error:c.XC}),z=M=>(0,c.$e)((0,c._C)(Z,M)),F=(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)(F),totalCount:c.mH}),H=ce,_=(0,c.su)({transfers:(0,c._2)(se),totalCount:c.mH});class y{constructor(P,D){this.baseUrl=P,this.fetch=D}getAccountMessages(P,D,T=20){return X(this,null,function*(){const p=new URL(`${this.baseUrl}/address/${P}/messages`),A=new URLSearchParams({page:D.toString(),pageSize:T.toString()});p.search=A.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(P,D,T=20){return X(this,null,function*(){const p=new URL(`${this.baseUrl}/address/${P}/transfers`),A=new URLSearchParams({page:D.toString(),pageSize:T.toString()});p.search=A.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(P){return X(this,null,function*(){const T=yield(yield this.fetch(`${this.baseUrl}/message/${P}`,{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(ke,ne,E){"use strict";E.d(ne,{_E:function(){return _},dh:function(){return D},wI:function(){return y}});var c=E(68142),X=E.n(c),Z=E(79325),z=E(3666),F=E.n(z),ce=E(76714),se=E(48764).Buffer;const{utils:{crypto:{decode58Check:ee,getBase58CheckAddress:H}}}=F(),_=T=>{const p=ee(T);return Z.YU.stringify(p)},y=T=>{const p=Z.YU.parse(T);return H(Array.from(p))},M="a9059cbb",P=T=>{if(!T.startsWith(M))throw new Error("Not a TRC20 data payload");const p=T.replace(M,""),A=`41${p.substring(24,64)}`,L=y(A),U=p.substring(64,128),I=hexToDecimal(U);return[L,I]},D=(T,p)=>{const A=_(T).replace(/^(41)/,"0x"),L=X().simpleEncode("transfer(address,uint256):(uint256)",A,p);return se.from(L).toString("hex")}},89214:function(){},52361:function(){},94616:function(){},88924:function(){},55024:function(){}}]);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[8601],{79014:function(ae,U,l){"use strict";l.d(U,{Q:function(){return ne},k:function(){return te}});var R=l(77591),y=l.n(R),I=l(24350),b=l(84564),A=l.n(b),B=l(76714),L=Object.defineProperty,$=Object.getOwnPropertySymbols,M=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,J=(m,k,w)=>k in m?L(m,k,{enumerable:!0,configurable:!0,writable:!0,value:w}):m[k]=w,ee=(m,k)=>{for(var w in k||(k={}))M.call(k,w)&&J(m,w,k[w]);if($)for(var w of $(k))n.call(k,w)&&J(m,w,k[w]);return m};function te(m,k,w,v,N=[]){const g=ee({},A()(k,{},!0)),F=k.startsWith(`${m.pluginId}://`);if(g.protocol!=null&&(g.protocol=g.protocol.replace(":","")),g.protocol!=null&&g.protocol!==""&&!w[g.protocol])throw new Error(`Uri protocol '${g.protocol}' is not supported for ${m.pluginId}.`);if(g.host===""&&g.pathname==="")throw new Error("Path and host not found in uri.");const E={publicAddress:g.host!==""?g.host:g.pathname.split("/")[0]},X=g.query.label,Z=g.query.message,q=g.query.category;(X!=null||Z!=null||q!=null||F)&&(E.metadata={},E.metadata.name=X,E.metadata.notes=Z,E.metadata.category=q,E.metadata.gateway=F!=null?F:!1);const W=g.query.amount;if(W!=null&&typeof W=="string"){v==null&&(v=m.currencyCode);const G=(0,B.Qs)(v!=null?v:"",m,N);if(G==null)throw new Error("InternalErrorInvalidCurrencyCode");let D=(0,R.mul)(W,G.multiplier);D=(0,R.toFixed)(D,0,0),E.nativeAmount=D,E.currencyCode=v}return{edgeParsedUri:E,parsedUri:g}}function ne(m,k,w){if(m.publicAddress==null)throw new Error("InvalidPublicAddressError");if(w==null&&m.label==null&&m.message==null)return m.publicAddress;{let v="";w!=null&&(v+="amount="+w+"&"),(m.label!=null||m.message!=null)&&(typeof m.label=="string"&&(v+="label="+m.label+"&"),typeof m.message=="string"&&(v+="message="+m.message+"&")),v=v.substr(0,v.length-1);const N={scheme:k,path:m.publicAddress,query:v};return(0,I.qC)(N)}}},99599:function(ae,U,l){"use strict";l.d(U,{K:function(){return R}});const R={parse(y){const I=encodeURI(y),b=new Uint8Array(I.length);let A=0;for(let B=0;B<I.length;++B){const L=I.charCodeAt(B);L===37?(b[A++]=parseInt(I.slice(B+1,B+3),16),B+=2):b[A++]=L}return b.subarray(0,A)},stringify(y){let I="";for(let b=0;b<y.length;++b){const A=y[b];I+="%"+(A>>4).toString(16)+(A&15).toString(16)}return decodeURIComponent(I)}}},18226:function(ae,U,l){"use strict";l.r(U),l.d(U,{SolanaTools:function(){return de},makeCurrencyEngine:function(){return Oe},makeCurrencyTools:function(){return Me}});var R=l(78412),y=l(77591),I=l(2153),b=l(48764),A=l(62678),B=l(79325),L=l(20918),$=l(79014),M=l(76714),n=l(82448),J=l(62177);const ee=(0,n.su)({newestTxid:(0,n.Vk)(n.XC,"")}),te=(0,n.su)({value:n.mH}),ne=(0,n.su)({signature:n.XC,blocktime:(0,n.Zz)(n.mH),err:n.JC}),m=(0,n.su)({value:(0,n.su)({blockhash:n.XC,feeCalculator:(0,n.su)({lamportsPerSignature:n.mH})})}),k=J.BQ,w=f=>{const e=(0,n.su)({[`${f}Mnemonic`]:n.XC,[`${f}Key`]:n.XC});return(0,n.W1)(t=>{const s=e(t);return{mnemonic:s[`${f}Mnemonic`],privateKey:s[`${f}Key`]}},t=>({[`${f}Mnemonic`]:t.mnemonic,[`${f}Key`]:t.privateKey}))},v=f=>(0,n.su)({result:f}),N=(0,n.vq)(v((0,n._2)(ne))),g=v(te),F=(0,n.su)({value:(0,n.su)({amount:n.XC})}),ce=v(F),E=(0,n.su)({value:(0,n._C)(n.gu,(0,n.su)({}))}),X=(0,n.su)({accountIndex:n.mH,mint:n.XC,owner:n.XC,programId:n.XC,uiTokenAmount:(0,n.su)({amount:n.XC})}),Z=(0,n.su)({meta:(0,n.su)({err:(0,n.Zz)(n.JC),fee:n.mH,innerInstructions:(0,n._2)(n.JC),postBalances:(0,n._2)(n.mH),postTokenBalances:(0,n._2)((0,n.Vk)(X)),preBalances:(0,n._2)(n.mH),preTokenBalances:(0,n._2)((0,n.Vk)(X))}),slot:n.mH,transaction:(0,n.su)({message:(0,n.su)({accountKeys:(0,n._2)((0,n.su)({pubkey:n.XC})),instructions:(0,n._2)(n.JC),recentBlockhash:n.XC}),signatures:(0,n._2)(n.XC)})}),q=v(Z),W=v(n.mH),G=(0,n.su)({alchemyApiKey:(0,n.Zz)(n.XC),poktPortalApiKey:(0,n.Zz)(n.XC)});var D=l(20302),fe=l(77043),me=l(49687),H=l(94935),ye=l(84650),pe=l(72681),ge=l(99599),ke=l(48764).Buffer,we=Object.defineProperty,le=Object.getOwnPropertySymbols,ve=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable,Ie=Reflect.get,ue=(f,e,t)=>e in f?we(f,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):f[e]=t,Pe=(f,e)=>{for(var t in e||(e={}))Ce.call(e,t)&&ue(f,t,e[t]);if(le)for(var t of le(e))Te.call(e,t)&&ue(f,t,e[t]);return f},be=(f,e,t)=>Ie(ve(f),t,e),C=(f,e,t)=>new Promise((s,r)=>{var a=o=>{try{c(t.next(o))}catch(h){r(h)}},u=o=>{try{c(t.throw(o))}catch(h){r(h)}},c=o=>o.done?s(o.value):Promise.resolve(o.value).then(a,u);c((t=t.apply(f,e)).next())});const{PublicKey:K,Keypair:Be,SystemProgram:Se,Transaction:he,TransactionInstruction:Ae}=R,Ee=5e3,se=2e4,Ke=3e3;class re extends ye.P{constructor(e,t,s,r){super(e,t,s,r),this.networkInfo=e.networkInfo,this.initOptions=e.initOptions,this.chainCode=t.currencyInfo.currencyCode,this.fetchCors=(0,M.zR)(e.io),this.feePerSignature="5000",this.recentBlockhash="",this.base58PublicKey=s.keys.publicKey,this.progressRatio=0,this.addressCache=new Map,this.minimumAddressBalance="0"}setOtherData(e){this.otherData=ee(e)}fetchRpc(e){return C(this,arguments,function*(t,s=[]){const r={method:t,params:s};return(yield this.fetchRpcBulk([r]))[0].result})}fetchRpcBulk(e,t){return C(this,null,function*(){const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e.map((u,c)=>Pe({jsonrpc:"2.0",id:c+1},u)))},a=(t!=null?t:this.networkInfo.rpcNodes).map(u=>()=>C(this,null,function*(){const c=G(this.initOptions),h=/{{(.*)}}/g.exec(u);if(h!=null){const T=h[1],p=c[T];if(typeof p=="string")u=u.replace(h[0],p);else throw p==null?new Error(`Missing ${T} in 'initOptions' for ${this.currencyInfo.pluginId}`):new Error("Incorrect apikey type for RPC")}const d=yield this.fetchCors(u,s);if(!d.ok)throw new Error(`fetchRpc ${s.method} failed error: ${d.status}`);return yield d.json()}));return yield(0,M.QJ)(a)})}queryBalance(){return C(this,null,function*(){var e,t,s;try{const r=[{method:"getBalance",params:[this.base58PublicKey,{commitment:this.networkInfo.commitment}]}],a=[...Object.keys(this.allTokensMap)],u=new K(this.base58PublicKey),c=new K(this.networkInfo.tokenPublicKey),o=new K(this.networkInfo.associatedTokenPublicKey);for(const p of a){const i=yield(0,D.Am)(new K(p),u,!1,c,o);r.push({method:"getTokenAccountBalance",params:[i.toBase58(),{commitment:this.networkInfo.commitment,encoding:"jsonParsed"}]})}const h=yield this.fetchRpcBulk(r),[d,...x]=h,T=g(d);this.updateBalance(this.chainCode,T.result.value.toString());for(const[p,i]of a.entries()){const S=(0,n.Vk)(ce)(x[p]),P=(s=(t=(e=S==null?void 0:S.result)==null?void 0:e.value)==null?void 0:t.amount)!=null?s:"0";this.updateBalance(this.allTokensMap[i].currencyCode,P)}}catch(r){this.error(`Error checking ${this.chainCode} address balance`,r)}})}queryBlockheight(){return C(this,null,function*(){try{const e=(0,n.mH)(yield this.fetchRpc("getSlot"));e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(e){this.error("queryBlockheight Error ",e)}})}queryMinimumBalance(){return C(this,null,function*(){try{const e=(0,n.mH)(yield this.fetchRpc("getMinimumBalanceForRentExemption",[50]));this.minimumAddressBalance=e.toString()}catch(e){this.error("queryMinimumBalance Error ",e)}})}queryFee(){return C(this,null,function*(){try{const e=yield this.fetchRpc("getRecentBlockhash"),{blockhash:t,feeCalculator:{lamportsPerSignature:s}}=m(e).value;this.feePerSignature=s.toString(),this.recentBlockhash=t}catch(e){this.error("queryFee Error ",e)}})}processSolanaTransaction(e,t,s){const r=[],{amount:a,networkFee:u,parentNetworkFee:c,tokenId:o}=t,h=o!=null?this.allTokensMap[o].currencyCode:this.chainCode;(0,y.gte)(a,"0")&&r.push(this.base58PublicKey);const d={blockHeight:e.slot,currencyCode:h,date:s,isSend:a.startsWith("-"),memos:[],nativeAmount:a,networkFee:u,ourReceiveAddresses:r,parentNetworkFee:c,signedTx:"",txid:e.transaction.signatures[0],walletId:this.walletId};this.addTransaction(h,d)}parseTxAmounts(e){var t;const s=[],r=e.transaction.message.accountKeys.findIndex(i=>i.pubkey===this.base58PublicKey);if(r<0||e.meta==null)return s;const{fee:a,preBalances:u,postBalances:c,preTokenBalances:o,postTokenBalances:h}=e.meta,d=a.toString(),x=(c[r]-u[r]).toString();if(x!=="0"){const i=(0,y.lt)(x,"0");s.push({amount:i?(0,y.sub)(x,d):x,networkFee:i?d:"0"})}const T=i=>i==null||i.owner!==this.base58PublicKey||i.programId!==this.networkInfo.tokenPublicKey||this.allTokensMap[i.mint]==null,p=new Map;for(const i of h)i==null||T(i)||p.set(i.mint,i.uiTokenAmount.amount);for(const i of o){if(i==null||T(i))continue;const S=(t=p.get(i.mint))!=null?t:"0";p.set(i.mint,(0,y.sub)(S,i.uiTokenAmount.amount))}return p.forEach((i,S)=>{s.push({amount:i,networkFee:"0",parentNetworkFee:(0,y.lt)(i,"0")?d:void 0,tokenId:S})}),s}queryTransactions(){return C(this,null,function*(){var e;let t=null;const s=this.otherData.newestTxid!==""?this.otherData.newestTxid:null;let r=[];try{for(;;){const o=[this.base58PublicKey,{until:s,before:t,limit:this.networkInfo.txQueryLimit,commitment:this.networkInfo.commitment}],h=yield this.fetchRpcBulk([{method:"getSignaturesForAddress",params:o}],this.networkInfo.rpcNodesArchival),d=N(h)[0].result;if(r=r.concat(d),d.length<this.networkInfo.txQueryLimit)break;t=d[this.networkInfo.txQueryLimit-1].signature}}catch(o){this.error("getTransactionSignatures failed with error: ",o);return}if(r.length===0){this.updateTxStatus(1),this.updateOnAddressesChecked();return}const a=50;let u=0;const c=r.map(o=>({method:"getTransaction",params:[o.signature,{encoding:"jsonParsed",commitment:this.networkInfo.commitment,maxSupportedTransactionVersion:0}]})).reverse();for(let o=0;o<c.length;o+=a){const h=c.slice(o,o+a>c.length-1?void 0:o+a),d=yield this.fetchRpcBulk(h,this.networkInfo.rpcNodesArchival),T=d.map(i=>q(i).result.slot).map(i=>({method:"getBlockTime",params:[i]})),p=yield this.fetchRpcBulk(T,this.networkInfo.rpcNodesArchival);for(let i=0;i<d.length;i++){if(((e=d[i].result.meta)==null?void 0:e.err)!=null)continue;this.parseTxAmounts(d[i].result).forEach(z=>{this.processSolanaTransaction(d[i].result,z,W(p[i]).result),u++}),this.otherData.newestTxid=r[i].signature;const P=1-u/r.length;P!==this.progressRatio&&(Math.abs(P-this.progressRatio)>.25||P===1)&&(this.progressRatio=P,this.updateTxStatus(this.progressRatio),this.updateOnAddressesChecked())}}this.walletLocalDataDirty=!0,this.updateTxStatus(1),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}updateTxStatus(e){[this.chainCode,...this.enabledTokenIds.map(s=>this.allTokensMap[s].currencyCode)].forEach(s=>{this.tokenCheckTransactionsStatus[s]=e}),this.updateOnAddressesChecked()}startEngine(){return C(this,null,function*(){this.engineOn=!0,this.addToLoop("queryBlockheight",se).catch(()=>{}),this.addToLoop("queryMinimumBalance",se).catch(()=>{}),this.addToLoop("queryFee",se).catch(()=>{}),this.addToLoop("queryBalance",Ee).catch(()=>{}),this.addToLoop("queryTransactions",Ke).catch(()=>{}),yield be(re.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return C(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return C(this,null,function*(){const{currencyCode:t}=e;let s=this.getBalance({currencyCode:t});if(t===this.currencyInfo.currencyCode)s=(0,y.sub)(s,this.feePerSignature);else{const r=this.getBalance({currencyCode:this.currencyInfo.currencyCode});if((0,y.lt)((0,y.sub)(r,this.minimumAddressBalance),"0"))throw new H.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:this.feePerSignature})}if((0,y.lt)(s,"0"))throw new H.C_;return s})}makeSpend(e){return C(this,null,function*(){var t,s,r;e=(0,pe.s)(e,this.currencyInfo);const{edgeSpendInfo:a,currencyCode:u}=this.makeSpendCheck(e),{memos:c=[],tokenId:o}=a;if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:h,publicAddress:d}=a.spendTargets[0];if(d==null)throw new Error("makeSpend Missing publicAddress");if(h==null)throw new H.$D;const x=o!=null;let T="0",p=this.feePerSignature,i;const S=(t=this.walletLocalData.totalBalances[u])!=null?t:"0",P=new K(this.base58PublicKey),z=new K(d),Y=new K(this.networkInfo.tokenPublicKey),oe=new K(this.networkInfo.associatedTokenPublicKey),Le={recentBlockhash:this.recentBlockhash,feePayer:P},Q=new he(Le);if(x){const V=new K(o),ie=yield(0,D.Am)(V,z,!1,Y,oe);let _=this.addressCache.get(d);if(_===void 0&&(E(yield this.fetchRpc("getAccountInfo",[ie.toBase58(),{commitment:this.networkInfo.commitment,encoding:"jsonParsed"}])).value==null?(_=!1,this.addressCache.set(d,!1)):(_=!0,this.addressCache.set(d,!0))),_||(Q.add((0,fe.Ek)(P,ie,z,V,Y,oe)),p=(0,y.add)(p,this.feePerSignature)),i=p,p="0",T=h,(0,y.gt)(h,S))throw new H.C_;const Ue=(s=this.walletLocalData.totalBalances[this.chainCode])!=null?s:"0";if((0,y.gt)((0,y.add)(i,this.minimumAddressBalance),Ue))throw new H.C_({currencyCode:this.chainCode,networkFee:i});const He=yield(0,D.Am)(V,P,!1,Y,oe);Q.add((0,me.$B)(He,ie,P,BigInt(h),[],Y))}else T=(0,y.add)(h,p),Q.add(Se.transfer({fromPubkey:P,toPubkey:z,lamports:parseInt(h)}));if(!(0,y.eq)(T,S)){if((0,y.gt)((0,y.add)(T,this.minimumAddressBalance),S))throw new H.C_}if(((r=c[0])==null?void 0:r.type)==="text"){const V=new Ae({keys:[{pubkey:P,isSigner:!0,isWritable:!0}],programId:new K(this.networkInfo.memoPublicKey),data:ke.from(ge.K.parse(c[0].value))});Q.add(V)}const De={unsignedSerializedSolTx:Q.serialize({requireAllSignatures:!1})};return{blockHeight:0,currencyCode:u,date:0,isSend:!0,memos:c,nativeAmount:(0,y.mul)(T,"-1"),networkFee:p,otherParams:De,ourReceiveAddresses:[],parentNetworkFee:i,signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,t){return C(this,null,function*(){const s=w(this.currencyInfo.pluginId)(t),{unsignedSerializedSolTx:r}=(0,M.Xp)(e);if(r==null)throw new Error("Missing unsignedSerializedSolTx");const a=Be.fromSecretKey(Uint8Array.from(B.YU.parse(s.privateKey))),u=he.from(r);return u.recentBlockhash=this.recentBlockhash,u.sign({publicKey:a.publicKey,secretKey:a.secretKey}),e.signedTx=u.serialize().toString("base64"),this.warn(`signTx
|
|
2
|
-
${(0,M.oX)(e)}`),this.addressCache=new Map(Array.from(this.addressCache.entries()).filter(([
|
|
3
|
-
${(0,M.oX)(e)}`)}catch(t){throw this.warn("FAILURE broadcastTx failed: ",t),t}return e})}}function
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[8601],{79014:function(he,H,h){"use strict";h.d(H,{Q:function(){return oe},k:function(){return re}});var L=h(77591),u=h.n(L),b=h(24350),B=h(84564),E=h.n(B),A=h(76714),F=Object.defineProperty,z=Object.getOwnPropertySymbols,M=Object.prototype.hasOwnProperty,n=Object.prototype.propertyIsEnumerable,G=(y,k,g)=>k in y?F(y,k,{enumerable:!0,configurable:!0,writable:!0,value:g}):y[k]=g,se=(y,k)=>{for(var g in k||(k={}))M.call(k,g)&&G(y,g,k[g]);if(z)for(var g of z(k))n.call(k,g)&&G(y,g,k[g]);return y};function re(y,k,g,w,R=[]){const p=se({},E()(k,{},!0)),W=k.startsWith(`${y.pluginId}://`);if(p.protocol!=null&&(p.protocol=p.protocol.replace(":","")),p.protocol!=null&&p.protocol!==""&&!g[p.protocol])throw new Error(`Uri protocol '${p.protocol}' is not supported for ${y.pluginId}.`);if(p.host===""&&p.pathname==="")throw new Error("Path and host not found in uri.");const K={publicAddress:p.host!==""?p.host:p.pathname.split("/")[0]},Z=p.query.label,Q=p.query.message,j=p.query.category;(Z!=null||Q!=null||j!=null||W)&&(K.metadata={},K.metadata.name=Z,K.metadata.notes=Q,K.metadata.category=j,K.metadata.gateway=W!=null?W:!1);const V=p.query.amount;if(V!=null&&typeof V=="string"){w==null&&(w=y.currencyCode);const _=(0,A.Qs)(w!=null?w:"",y,R);if(_==null)throw new Error("InternalErrorInvalidCurrencyCode");let q=(0,L.mul)(V,_.multiplier);q=(0,L.toFixed)(q,0,0),K.nativeAmount=q,K.currencyCode=w}return{edgeParsedUri:K,parsedUri:p}}function oe(y,k,g){if(y.publicAddress==null)throw new Error("InvalidPublicAddressError");if(g==null&&y.label==null&&y.message==null)return y.publicAddress;{let w="";g!=null&&(w+="amount="+g+"&"),(y.label!=null||y.message!=null)&&(typeof y.label=="string"&&(w+="label="+y.label+"&"),typeof y.message=="string"&&(w+="message="+y.message+"&")),w=w.substr(0,w.length-1);const R={scheme:k,path:y.publicAddress,query:w};return(0,b.qC)(R)}}},99599:function(he,H,h){"use strict";h.d(H,{K:function(){return L}});const L={parse(u){const b=encodeURI(u),B=new Uint8Array(b.length);let E=0;for(let A=0;A<b.length;++A){const F=b.charCodeAt(A);F===37?(B[E++]=parseInt(b.slice(A+1,A+3),16),A+=2):B[E++]=F}return B.subarray(0,E)},stringify(u){let b="";for(let B=0;B<u.length;++B){const E=u[B];b+="%"+(E>>4).toString(16)+(E&15).toString(16)}return decodeURIComponent(b)}}},18226:function(he,H,h){"use strict";h.r(H),h.d(H,{SolanaTools:function(){return pe},makeCurrencyEngine:function(){return De},makeCurrencyTools:function(){return Ne}});var L=h(78412),u=h(77591),b=h(2153),B=h(48764),E=h(62678),A=h(79325),F=h(20918),z=h(79014),M=h(76714),n=h(82448),G=h(62177);const se=(0,n.su)({newestTxid:(0,n.Vk)(n.XC,"")}),re=(0,n.su)({value:n.mH}),oe=(0,n.su)({signature:n.XC,blocktime:(0,n.Zz)(n.mH),err:n.JC}),y=(0,n.su)({value:(0,n.su)({blockhash:n.XC})}),k=(0,n._2)((0,n.su)({prioritizationFee:n.mH,slot:n.mH})),g=G.BQ,w=d=>{const e=(0,n.su)({[`${d}Mnemonic`]:n.XC,[`${d}Key`]:n.XC});return(0,n.W1)(t=>{const s=e(t);return{mnemonic:s[`${d}Mnemonic`],privateKey:s[`${d}Key`]}},t=>({[`${d}Mnemonic`]:t.mnemonic,[`${d}Key`]:t.privateKey}))},R=d=>(0,n.su)({result:d}),p=(0,n.vq)(R((0,n._2)(oe))),W=R(re),de=(0,n.su)({value:(0,n.su)({amount:n.XC})}),K=R(de),Z=(0,n.su)({value:(0,n._C)(n.gu,(0,n.su)({}))}),Q=(0,n.su)({accountIndex:n.mH,mint:n.XC,owner:n.XC,programId:n.XC,uiTokenAmount:(0,n.su)({amount:n.XC})}),j=(0,n.su)({meta:(0,n.su)({err:(0,n.Zz)(n.JC),fee:n.mH,innerInstructions:(0,n._2)(n.JC),postBalances:(0,n._2)(n.mH),postTokenBalances:(0,n._2)((0,n.Vk)(Q)),preBalances:(0,n._2)(n.mH),preTokenBalances:(0,n._2)((0,n.Vk)(Q))}),slot:n.mH,transaction:(0,n.su)({message:(0,n.su)({accountKeys:(0,n._2)((0,n.su)({pubkey:n.XC})),instructions:(0,n._2)(n.JC),recentBlockhash:n.XC}),signatures:(0,n._2)(n.XC)})}),V=R(j),_=R(n.mH),q=(0,n.su)({alchemyApiKey:(0,n.Zz)(n.XC),poktPortalApiKey:(0,n.Zz)(n.XC)}),ge=(0,n.su)({microLamports:n.XC});var ie=h(20302),ke=h(77043),we=h(49687),N=h(94935),ve=h(84650),Ce=h(72681),Te=h(99599),Ie=h(48764).Buffer,Pe=Object.defineProperty,me=Object.getOwnPropertySymbols,be=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable,Se=Reflect.get,ye=(d,e,t)=>e in d?Pe(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,Ee=(d,e)=>{for(var t in e||(e={}))Be.call(e,t)&&ye(d,t,e[t]);if(me)for(var t of me(e))Ae.call(e,t)&&ye(d,t,e[t]);return d},Ke=(d,e,t)=>Se(be(d),t,e),v=(d,e,t)=>new Promise((s,r)=>{var a=o=>{try{l(t.next(o))}catch(f){r(f)}},c=o=>{try{l(t.throw(o))}catch(f){r(f)}},l=o=>o.done?s(o.value):Promise.resolve(o.value).then(a,c);l((t=t.apply(d,e)).next())});const{ComputeBudgetProgram:Oe,PublicKey:O,Keypair:xe,SystemProgram:Re,Transaction:fe,TransactionInstruction:Le}=L,Me=5e3,Y=2e4,Fe=3e3;class ae extends ve.P{constructor(e,t,s,r){super(e,t,s,r),this.networkInfo=e.networkInfo,this.initOptions=e.initOptions,this.chainCode=t.currencyInfo.currencyCode,this.fetchCors=(0,M.zR)(e.io),this.feePerSignature="5000",this.priorityFee="0",this.recentBlockhash="",this.base58PublicKey=s.keys.publicKey,this.progressRatio=0,this.addressCache=new Map,this.minimumAddressBalance="0"}setOtherData(e){this.otherData=se(e)}fetchRpc(e){return v(this,arguments,function*(t,s=[]){const r={method:t,params:s};return(yield this.fetchRpcBulk([r]))[0].result})}fetchRpcBulk(e,t){return v(this,null,function*(){const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e.map((c,l)=>Ee({jsonrpc:"2.0",id:l+1},c)))},a=(t!=null?t:this.networkInfo.rpcNodes).map(c=>()=>v(this,null,function*(){const l=q(this.initOptions),f=/{{(.*)}}/g.exec(c);if(f!=null){const P=f[1],C=l[P];if(typeof C=="string")c=c.replace(f[0],C);else throw C==null?new Error(`Missing ${P} in 'initOptions' for ${this.currencyInfo.pluginId}`):new Error("Incorrect apikey type for RPC")}const m=yield this.fetchCors(c,s);if(!m.ok)throw new Error(`fetchRpc ${s.method} failed error: ${m.status}`);return yield m.json()}));return yield(0,M.QJ)(a)})}queryBalance(){return v(this,null,function*(){var e,t,s;try{const r=[{method:"getBalance",params:[this.base58PublicKey,{commitment:this.networkInfo.commitment}]}],a=[...Object.keys(this.allTokensMap)],c=new O(this.base58PublicKey),l=new O(this.networkInfo.tokenPublicKey),o=new O(this.networkInfo.associatedTokenPublicKey);for(const C of a){const i=yield(0,ie.Am)(new O(C),c,!1,l,o);r.push({method:"getTokenAccountBalance",params:[i.toBase58(),{commitment:this.networkInfo.commitment,encoding:"jsonParsed"}]})}const f=yield this.fetchRpcBulk(r),[m,...I]=f,P=W(m);this.updateBalance(this.chainCode,P.result.value.toString());for(const[C,i]of a.entries()){const T=(0,n.Vk)(K)(I[C]),S=(s=(t=(e=T==null?void 0:T.result)==null?void 0:e.value)==null?void 0:t.amount)!=null?s:"0";this.updateBalance(this.allTokensMap[i].currencyCode,S)}}catch(r){this.error(`Error checking ${this.chainCode} address balance`,r)}})}queryBlockheight(){return v(this,null,function*(){try{const e=(0,n.mH)(yield this.fetchRpc("getSlot"));e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(e){this.error("queryBlockheight Error ",e)}})}queryMinimumBalance(){return v(this,null,function*(){try{const e=(0,n.mH)(yield this.fetchRpc("getMinimumBalanceForRentExemption",[50]));this.minimumAddressBalance=e.toString()}catch(e){this.error("queryMinimumBalance Error ",e)}})}queryFee(){return v(this,null,function*(){try{const e=yield this.fetchRpc("getRecentPrioritizationFees"),s=k(e).sort((r,a)=>r.slot-a.slot)[0];this.priorityFee=s.prioritizationFee.toString()}catch(e){this.error("queryFee Error ",e)}})}queryBlockhash(){return v(this,null,function*(){try{const e=yield this.fetchRpc("getLatestBlockhash"),{blockhash:t}=y(e).value;this.recentBlockhash=t}catch(e){this.error("queryBlockhash Error ",e)}})}processSolanaTransaction(e,t,s){const r=[],{amount:a,networkFee:c,parentNetworkFee:l,tokenId:o}=t,f=o!=null?this.allTokensMap[o].currencyCode:this.chainCode;(0,u.gte)(a,"0")&&r.push(this.base58PublicKey);const m={blockHeight:e.slot,currencyCode:f,date:s,isSend:a.startsWith("-"),memos:[],nativeAmount:a,networkFee:c,ourReceiveAddresses:r,parentNetworkFee:l,signedTx:"",txid:e.transaction.signatures[0],walletId:this.walletId};this.addTransaction(f,m)}parseTxAmounts(e){var t;const s=[],r=e.transaction.message.accountKeys.findIndex(i=>i.pubkey===this.base58PublicKey);if(r<0||e.meta==null)return s;const{fee:a,preBalances:c,postBalances:l,preTokenBalances:o,postTokenBalances:f}=e.meta,m=a.toString(),I=(l[r]-c[r]).toString();if(I!=="0"){const i=(0,u.lt)(I,"0");s.push({amount:i?(0,u.sub)(I,m):I,networkFee:i?m:"0"})}const P=i=>i==null||i.owner!==this.base58PublicKey||i.programId!==this.networkInfo.tokenPublicKey||this.allTokensMap[i.mint]==null,C=new Map;for(const i of f)i==null||P(i)||C.set(i.mint,i.uiTokenAmount.amount);for(const i of o){if(i==null||P(i))continue;const T=(t=C.get(i.mint))!=null?t:"0";C.set(i.mint,(0,u.sub)(T,i.uiTokenAmount.amount))}return C.forEach((i,T)=>{s.push({amount:i,networkFee:"0",parentNetworkFee:(0,u.lt)(i,"0")?m:void 0,tokenId:T})}),s}queryTransactions(){return v(this,null,function*(){var e;let t=null;const s=this.otherData.newestTxid!==""?this.otherData.newestTxid:null;let r=[];try{for(;;){const o=[this.base58PublicKey,{until:s,before:t,limit:this.networkInfo.txQueryLimit,commitment:this.networkInfo.commitment}],f=yield this.fetchRpcBulk([{method:"getSignaturesForAddress",params:o}],this.networkInfo.rpcNodesArchival),m=p(f)[0].result;if(r=r.concat(m),m.length<this.networkInfo.txQueryLimit)break;t=m[this.networkInfo.txQueryLimit-1].signature}}catch(o){this.error("getTransactionSignatures failed with error: ",o);return}if(r.length===0){this.updateTxStatus(1),this.updateOnAddressesChecked();return}const a=50;let c=0;const l=r.map(o=>({method:"getTransaction",params:[o.signature,{encoding:"jsonParsed",commitment:this.networkInfo.commitment,maxSupportedTransactionVersion:0}]})).reverse();for(let o=0;o<l.length;o+=a){const f=l.slice(o,o+a>l.length-1?void 0:o+a),m=yield this.fetchRpcBulk(f,this.networkInfo.rpcNodesArchival),P=m.map(i=>V(i).result.slot).map(i=>({method:"getBlockTime",params:[i]})),C=yield this.fetchRpcBulk(P,this.networkInfo.rpcNodesArchival);for(let i=0;i<m.length;i++){if(((e=m[i].result.meta)==null?void 0:e.err)!=null)continue;this.parseTxAmounts(m[i].result).forEach(J=>{this.processSolanaTransaction(m[i].result,J,_(C[i]).result),c++}),this.otherData.newestTxid=r[i].signature;const S=1-c/r.length;S!==this.progressRatio&&(Math.abs(S-this.progressRatio)>.25||S===1)&&(this.progressRatio=S,this.updateTxStatus(this.progressRatio),this.updateOnAddressesChecked())}}this.walletLocalDataDirty=!0,this.updateTxStatus(1),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}updateTxStatus(e){[this.chainCode,...this.enabledTokenIds.map(s=>this.allTokensMap[s].currencyCode)].forEach(s=>{this.tokenCheckTransactionsStatus[s]=e}),this.updateOnAddressesChecked()}startEngine(){return v(this,null,function*(){this.engineOn=!0,this.addToLoop("queryBlockheight",Y).catch(()=>{}),this.addToLoop("queryMinimumBalance",Y).catch(()=>{}),this.addToLoop("queryFee",Y).catch(()=>{}),this.addToLoop("queryBlockhash",Y).catch(()=>{}),this.addToLoop("queryBalance",Me).catch(()=>{}),this.addToLoop("queryTransactions",Fe).catch(()=>{}),yield Ke(ae.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return v(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return v(this,null,function*(){const{currencyCode:t}=e,s=this.getBalance({currencyCode:t});e.spendTargets[0].nativeAmount="1";const r=yield this.makeSpend(e);let a;if(t===this.currencyInfo.currencyCode)a=(0,u.sub)(s,r.networkFee);else{const c=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),l=(0,u.sub)(c,r.networkFee);if((0,u.lt)((0,u.sub)(l,this.minimumAddressBalance),"0"))throw new N.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:this.feePerSignature});a=s}if((0,u.lt)(a,"0"))throw new N.C_;return a})}makeSpend(e){return v(this,null,function*(){var t,s,r;e=(0,Ce.s)(e,this.currencyInfo);const{edgeSpendInfo:a,currencyCode:c}=this.makeSpendCheck(e),{customNetworkFee:l,memos:o=[],networkFeeOption:f,tokenId:m}=a;if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:I,publicAddress:P}=a.spendTargets[0];if(P==null)throw new Error("makeSpend Missing publicAddress");if(I==null)throw new N.$D;const C=m!=null;let i="0",T=this.feePerSignature,S;const J=(t=this.walletLocalData.totalBalances[c])!=null?t:"0",$=new O(this.base58PublicKey),ce=new O(P),te=new O(this.networkInfo.tokenPublicKey),le=new O(this.networkInfo.associatedTokenPublicKey),$e={recentBlockhash:this.recentBlockhash,feePayer:$},X=new fe($e);let D="0";switch(f){case"low":D=(0,u.max)("0",(0,u.mul)(this.priorityFee,"0.75"));break;case"standard":D=this.priorityFee;break;case"high":D=(0,u.max)("1",(0,u.mul)(this.priorityFee,"1.25"));break;case"custom":{D=ge(l).microLamports;break}}if((0,u.gt)(D,"0")){const U=Oe.setComputeUnitPrice({microLamports:parseInt(D)});X.add(U),T=(0,u.add)(T,D)}if(C){const U=new O(m),ue=yield(0,ie.Am)(U,ce,!1,te,le);let ne=this.addressCache.get(P);if(ne===void 0&&(Z(yield this.fetchRpc("getAccountInfo",[ue.toBase58(),{commitment:this.networkInfo.commitment,encoding:"jsonParsed"}])).value==null?(ne=!1,this.addressCache.set(P,!1)):(ne=!0,this.addressCache.set(P,!0))),ne||(X.add((0,ke.Ek)($,ue,ce,U,te,le)),T=(0,u.add)(T,this.feePerSignature)),S=T,T="0",i=I,(0,u.gt)(I,J))throw new N.C_;const ze=(s=this.walletLocalData.totalBalances[this.chainCode])!=null?s:"0";if((0,u.gt)((0,u.add)(S,this.minimumAddressBalance),ze))throw new N.C_({currencyCode:this.chainCode,networkFee:S});const We=yield(0,ie.Am)(U,$,!1,te,le);X.add((0,we.$B)(We,ue,$,BigInt(I),[],te))}else i=(0,u.add)(I,T),X.add(Re.transfer({fromPubkey:$,toPubkey:ce,lamports:parseInt(I)}));if(!(0,u.eq)(i,J)){if((0,u.gt)((0,u.add)(i,this.minimumAddressBalance),J))throw new N.C_}if(((r=o[0])==null?void 0:r.type)==="text"){const U=new Le({keys:[{pubkey:$,isSigner:!0,isWritable:!0}],programId:new O(this.networkInfo.memoPublicKey),data:Ie.from(Te.K.parse(o[0].value))});X.add(U)}const Xe={unsignedSerializedSolTx:X.serialize({requireAllSignatures:!1})};return{blockHeight:0,currencyCode:c,date:0,isSend:!0,memos:o,nativeAmount:(0,u.mul)(i,"-1"),networkFee:T,otherParams:Xe,ourReceiveAddresses:[],parentNetworkFee:S,signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,t){return v(this,null,function*(){const s=w(this.currencyInfo.pluginId)(t),{unsignedSerializedSolTx:r}=(0,M.Xp)(e);if(r==null)throw new Error("Missing unsignedSerializedSolTx");const a=xe.fromSecretKey(Uint8Array.from(A.YU.parse(s.privateKey))),c=fe.from(r);return c.recentBlockhash=this.recentBlockhash,c.sign({publicKey:a.publicKey,secretKey:a.secretKey}),e.signedTx=c.serialize().toString("base64"),this.warn(`signTx
|
|
2
|
+
${(0,M.oX)(e)}`),this.addressCache=new Map(Array.from(this.addressCache.entries()).filter(([l,o])=>o)),e})}broadcastTx(e){return v(this,null,function*(){if(e.signedTx==null)throw new Error("Missing signedTx");try{const t=[e.signedTx,{encoding:"base64"}],s=(0,n.XC)(yield this.fetchRpc("sendTransaction",t));e.txid=s,e.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
3
|
+
${(0,M.oX)(e)}`)}catch(t){throw this.warn("FAILURE broadcastTx failed: ",t),t}return e})}}function De(d,e,t,s){return v(this,null,function*(){const r=g(t),a=new ae(d,e,r,s);return yield a.loadEngine(),a})}var x=(d,e,t)=>new Promise((s,r)=>{var a=o=>{try{l(t.next(o))}catch(f){r(f)}},c=o=>{try{l(t.throw(o))}catch(f){r(f)}},l=o=>o.done?s(o.value):Promise.resolve(o.value).then(a,c);l((t=t.apply(d,e)).next())});const{Keypair:Ue,PublicKey:ee}=L,He=(d,e)=>x(void 0,null,function*(){const t=yield(0,b.mnemonicToSeed)(d),s=E.derivePath(e,A.YU.stringify(t)).key;return Ue.fromSeed(Uint8Array.from(s))});class pe{constructor(e){const{builtinTokens:t,currencyInfo:s,io:r,networkInfo:a}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=r,this.networkInfo=a}getDisplayPrivateKey(e){return x(this,null,function*(){const{pluginId:t}=this.currencyInfo;return w(t)(e.keys).mnemonic})}getDisplayPublicKey(e){return x(this,null,function*(){const{keys:t}=g(e);return t.publicKey})}importPrivateKey(e){return x(this,null,function*(){const{pluginId:t}=this.currencyInfo;if(!(0,b.validateMnemonic)(e))throw new Error("Invalid mnemonic");const r=yield He(e,this.networkInfo.derivationPath);return{[`${t}Mnemonic`]:e,[`${t}Key`]:B.Buffer.from(r.secretKey).toString("hex"),publicKey:r.publicKey.toBase58()}})}createPrivateKey(e){return x(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const t=B.Buffer.from(this.io.random(32)),s=(0,b.entropyToMnemonic)(t);return yield this.importPrivateKey(s)})}derivePublicKey(e){return x(this,null,function*(){const{pluginId:t}=this.currencyInfo;if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(e.keys[`${t}Mnemonic`]==null)throw new Error("Missing mnemonic");return{publicKey:(yield this.importPrivateKey(e.keys[`${t}Mnemonic`])).publicKey.toString()}})}parseUri(e,t,s){return x(this,null,function*(){const{pluginId:r}=this.currencyInfo,a={[r]:!0},{parsedUri:c,edgeParsedUri:l}=(0,z.k)(this.currencyInfo,e,a,t!=null?t:this.currencyInfo.currencyCode,s);let o="";if(l.publicAddress!=null&&(o=l.publicAddress),!ee.isOnCurve(new ee(o).toBytes()))throw new Error("InvalidPublicAddressError");return l.uniqueIdentifier=c.query.memo,l})}encodeUri(e){return x(this,arguments,function*(t,s=[]){const{pluginId:r}=this.currencyInfo,{nativeAmount:a,currencyCode:c,publicAddress:l}=t;if(!ee.isOnCurve(new ee(l).toBytes()))throw new Error("InvalidPublicAddressError");let o;if(typeof a=="string"){const m=(0,M.Qs)(c!=null?c:this.currencyInfo.currencyCode,this.currencyInfo,s);if(m==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,u.div)(a,m.multiplier,18)}return(0,z.Q)(t,r,o)})}getTokenId(e){return x(this,null,function*(){(0,F.Rp)(e);const t=(0,F.Oj)(e.networkLocation);if(t==null)throw new Error("ErrorInvalidContractAddress");return t.contractAddress})}}function Ne(d){return x(this,null,function*(){return new pe(d)})}},52361:function(){},94616:function(){},55024:function(){}}]);
|
|
@@ -39,8 +39,8 @@ const currencyInfo = {
|
|
|
39
39
|
walletType: 'wallet:algorand',
|
|
40
40
|
|
|
41
41
|
// Explorers:
|
|
42
|
-
addressExplorer: 'https://
|
|
43
|
-
transactionExplorer: 'https://
|
|
42
|
+
addressExplorer: 'https://explorer.bitquery.io/algorand/address/%s',
|
|
43
|
+
transactionExplorer: 'https://explorer.bitquery.io/algorand/tx/%s',
|
|
44
44
|
|
|
45
45
|
denominations: [
|
|
46
46
|
{
|
|
@@ -1068,7 +1068,7 @@ const networkInfo = {
|
|
|
1068
1068
|
'https://eth-mainnet.alchemyapi.io/v2/-{{alchemyApiKey}}',
|
|
1069
1069
|
'https://mainnet.infura.io/v3/{{infuraProjectId}}',
|
|
1070
1070
|
'https://rpc.ankr.com/eth',
|
|
1071
|
-
'https://eth-mainnet.
|
|
1071
|
+
'https://eth-mainnet.rpc.grove.city/v1/{{poktPortalApiKey}}',
|
|
1072
1072
|
'https://cloudflare-eth.com'
|
|
1073
1073
|
],
|
|
1074
1074
|
ethBalCheckerContract: '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39'
|
|
@@ -277,7 +277,7 @@ const networkInfo = {
|
|
|
277
277
|
{
|
|
278
278
|
type: 'rpc',
|
|
279
279
|
servers: [
|
|
280
|
-
'https://fantom-mainnet.
|
|
280
|
+
'https://fantom-mainnet.rpc.grove.city/v1/{{poktPortalApiKey}}',
|
|
281
281
|
'https://polished-empty-cloud.fantom.quiknode.pro/{{quiknodeApiKey}}/',
|
|
282
282
|
'https://rpc.ankr.com/fantom',
|
|
283
283
|
'https://rpc.ftm.tools'
|
|
@@ -96,7 +96,7 @@ const networkInfo = {
|
|
|
96
96
|
{
|
|
97
97
|
type: 'rpc',
|
|
98
98
|
servers: [
|
|
99
|
-
'https://eth-goerli.
|
|
99
|
+
'https://eth-goerli.rpc.grove.city/v1/{{poktPortalApiKey}}',
|
|
100
100
|
'https://eth-goerli.alchemyapi.io/v2/-{{alchemyApiKey}}',
|
|
101
101
|
'https://goerli.infura.io/v3/{{infuraProjectId}}'
|
|
102
102
|
]
|
|
@@ -170,7 +170,7 @@ const networkInfo = {
|
|
|
170
170
|
'https://rpc-mainnet.maticvigil.com',
|
|
171
171
|
'https://matic-mainnet.chainstacklabs.com',
|
|
172
172
|
'https://rpc.ankr.com/polygon',
|
|
173
|
-
'https://poly-mainnet.
|
|
173
|
+
'https://poly-mainnet.rpc.grove.city/v1/{{poktPortalApiKey}}',
|
|
174
174
|
'https://rpc-mainnet.matic.quiknode.pro/{{quiknodeApiKey}}/'
|
|
175
175
|
],
|
|
176
176
|
ethBalCheckerContract: '0x2352c63A83f9Fd126af8676146721Fa00924d7e4'
|
|
@@ -146,7 +146,7 @@ var _types3 = require('./types');
|
|
|
146
146
|
const edgeTransaction = {
|
|
147
147
|
blockHeight,
|
|
148
148
|
currencyCode,
|
|
149
|
-
date:
|
|
149
|
+
date: new Date(scanTx.timestamp).getTime() / 1000,
|
|
150
150
|
feeRateUsed:
|
|
151
151
|
gasPrice != null
|
|
152
152
|
? _EthereumNetwork.getFeeRateUsed.call(void 0, gasPrice, scanTx.gas_limit, scanTx.gas_used)
|